difftreelog
refactor use type-safe propertywriter to set/delete properties
in: master
12 files changed
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -172,6 +172,20 @@
fail!(<pallet_common::Error<T>>::UnsupportedOperation);
}
+ fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ // No token properties are defined on fungibles
+ up_data_structs::TokenProperties::new()
+ }
+
+ fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
+ // No token properties are defined on fungibles
+ }
+
+ fn properties_exist(&self, _token: TokenId) -> bool {
+ // No token properties are defined on fungibles
+ false
+ }
+
fn set_token_property_permissions(
&self,
_sender: &<T>::CrossAccountId,
@@ -277,6 +291,15 @@
Err(up_data_structs::TokenOwnerError::MultipleOwners)
}
+ fn check_token_indirect_owner(
+ &self,
+ _token: TokenId,
+ _maybe_owner: &<T>::CrossAccountId,
+ _nesting_budget: &dyn up_data_structs::budget::Budget,
+ ) -> Result<bool, frame_support::sp_runtime::DispatchError> {
+ Ok(false)
+ }
+
fn token_owners(&self, _token: TokenId) -> Vec<<T>::CrossAccountId> {
vec![]
}
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, CreateCollectionData, CollectionId, Property, PropertyKey, PropertyValue,
- CollectionPermissions, NestingPermissions, AccessMode, MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
+ CollectionPermissions, NestingPermissions, AccessMode, PropertiesPermissionMap,
+ MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Get, fungible::Balanced, Imbalance, tokens::Precision},
@@ -123,6 +124,16 @@
)
}
+pub fn load_is_admin_and_property_permissions<T: Config>(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+) -> (bool, PropertiesPermissionMap) {
+ (
+ collection.is_owner_or_admin(sender),
+ <Pallet<T>>::property_permissions(collection.id),
+ )
+}
+
/// Helper macros, which handles all benchmarking preparation in semi-declarative way
///
/// `name` is a substrate account
@@ -215,4 +226,12 @@
assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);
}: {collection_handle.check_allowlist(&sender)?;}
+
+ init_token_properties_common {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: sub;
+ sender: cross_from_sub(sender);
+ };
+ }: {load_is_admin_and_property_permissions(&collection, &sender);}
}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -56,6 +56,7 @@
use core::{
ops::{Deref, DerefMut},
slice::from_ref,
+ marker::PhantomData,
};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
use sp_std::vec::Vec;
@@ -97,6 +98,9 @@
pub mod helpers;
#[allow(missing_docs)]
pub mod weights;
+
+use weights::WeightInfo;
+
/// Weight info.
pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
@@ -864,19 +868,7 @@
QueryKind = OptionQuery,
>;
}
-
-/// Represents the change mode for the token property.
-pub enum SetPropertyMode {
- /// The token already exists.
- ExistingToken,
- /// New token.
- NewToken {
- /// The creator of the token is the recipient.
- mint_target_is_sender: bool,
- },
-}
-
/// Value representation with delayed initialization time.
pub struct LazyValue<T, F: FnOnce() -> T> {
value: Option<T>,
@@ -892,19 +884,33 @@
}
}
- /// Get the value. If it call furst time the value will be initialized.
+ /// Get the value. If it is called the first time, the value will be initialized.
pub fn value(&mut self) -> &T {
- if self.value.is_none() {
- self.value = Some(self.f.take().unwrap()())
- }
+ self.compute_value_if_not_already();
+ self.value.as_ref().unwrap()
+ }
- self.value.as_ref().unwrap()
+ /// Get the value. If it is called the first time, the value will be initialized.
+ pub fn value_mut(&mut self) -> &mut T {
+ self.compute_value_if_not_already();
+ self.value.as_mut().unwrap()
}
- /// Is value initialized.
+ fn into_inner(mut self) -> T {
+ self.compute_value_if_not_already();
+ self.value.unwrap()
+ }
+
+ /// Is value initialized?
pub fn has_value(&self) -> bool {
self.value.is_some()
}
+
+ fn compute_value_if_not_already(&mut self) {
+ if self.value.is_none() {
+ self.value = Some(self.f.take().unwrap()())
+ }
+ }
}
fn check_token_permissions<T, FCA, FTO, FTE>(
@@ -926,10 +932,19 @@
fail!(<Error<T>>::NoPermission);
}
- let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;
- if !token_certainly_exist && !is_token_exist.value() {
- fail!(<Error<T>>::TokenNotFound);
+ let token_exist_due_to_owner_check_success =
+ is_token_owner.has_value() && (*is_token_owner.value())?;
+
+ // If the token owner check has occurred and succeeded,
+ // we know the token exists (otherwise, the owner check must fail).
+ if !token_exist_due_to_owner_check_success {
+ // If the token owner check didn't occur,
+ // we must check the token's existence ourselves.
+ if !is_token_exist.value() {
+ fail!(<Error<T>>::TokenNotFound);
+ }
}
+
Ok(())
}
@@ -1312,92 +1327,6 @@
Ok(())
}
- /// A batch operation to add, edit or remove properties for a token.
- /// It sets or removes a token's properties according to
- /// `properties_updates` contents:
- /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
- /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
- ///
- /// All affected properties should have `mutable` permission
- /// to be **deleted** or to be **set more than once**,
- /// and the sender should have permission to edit those properties.
- ///
- /// This function fires an event for each property change.
- /// In case of an error, all the changes (including the events) will be reverted
- /// since the function is transactional.
- #[allow(clippy::too_many_arguments)]
- pub fn modify_token_properties<FTO, FTE>(
- collection: &CollectionHandle<T>,
- sender: &T::CrossAccountId,
- token_id: TokenId,
- is_token_exist: &mut LazyValue<bool, FTE>,
- properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- mut stored_properties: TokenProperties,
- is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,
- set_token_properties: impl FnOnce(TokenProperties),
- log: evm_coder::ethereum::Log,
- ) -> DispatchResult
- where
- FTO: FnOnce() -> Result<bool, DispatchError>,
- FTE: FnOnce() -> bool,
- {
- let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));
- let mut permissions = LazyValue::new(|| Self::property_permissions(collection.id));
-
- let mut changed = false;
- for (key, value) in properties_updates {
- let permission = permissions
- .value()
- .get(&key)
- .cloned()
- .unwrap_or_else(PropertyPermission::none);
-
- let property_exists = stored_properties.get(&key).is_some();
-
- match permission {
- PropertyPermission { mutable: false, .. } if property_exists => {
- return Err(<Error<T>>::NoPermission.into());
- }
-
- PropertyPermission {
- collection_admin,
- token_owner,
- ..
- } => check_token_permissions::<T, _, FTO, FTE>(
- collection_admin,
- token_owner,
- &mut is_collection_admin,
- is_token_owner,
- is_token_exist,
- )?,
- }
-
- match value {
- Some(value) => {
- stored_properties
- .try_set(key.clone(), value)
- .map_err(<Error<T>>::from)?;
-
- Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));
- }
- None => {
- stored_properties.remove(&key).map_err(<Error<T>>::from)?;
-
- Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));
- }
- }
-
- changed = true;
- }
-
- if changed {
- <PalletEvm<T>>::deposit_log(log);
- set_token_properties(stored_properties);
- }
-
- Ok(())
- }
-
/// Sets or unsets the approval of a given operator.
///
/// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.
@@ -2166,6 +2095,22 @@
budget: &dyn Budget,
) -> DispatchResultWithPostInfo;
+ /// Get token properties raw map.
+ ///
+ /// * `token_id` - The token which properties are needed.
+ fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;
+
+ /// Set token properties raw map.
+ ///
+ /// * `token_id` - The token for which the properties are being set.
+ /// * `map` - The raw map containing the token's properties.
+ fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);
+
+ /// Whether the given token has properties.
+ ///
+ /// * `token_id` - The token in question.
+ fn properties_exist(&self, token: TokenId) -> bool;
+
/// Set token property permissions.
///
/// * `sender` - Must be either the owner of the token or its admin.
@@ -2309,6 +2254,18 @@
/// * `token` - The token for which you need to find out the owner.
fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;
+ /// Checks if the `maybe_owner` is the indirect owner of the `token`.
+ ///
+ /// * `token` - Id token to check.
+ /// * `maybe_owner` - The account to check.
+ /// * `nesting_budget` - A budget that can be spent on nesting tokens.
+ fn check_token_indirect_owner(
+ &self,
+ token: TokenId,
+ maybe_owner: &T::CrossAccountId,
+ nesting_budget: &dyn Budget,
+ ) -> Result<bool, DispatchError>;
+
/// Returns 10 tokens owners in no particular order.
///
/// * `token` - The token for which you need to find out the owners.
@@ -2420,6 +2377,348 @@
}
}
+/// A marker structure that enables the writer implementation
+/// to provide the interface to write properties to **newly created** tokens.
+pub struct NewTokenPropertyWriter;
+
+/// A marker structure that enables the writer implementation
+/// to provide the interface to write properties to **already existing** tokens.
+pub struct ExistingTokenPropertyWriter;
+
+/// The type-safe interface for writing properties (setting or deleting) to tokens.
+/// It has two distinct implementations for newly created tokens and existing ones.
+///
+/// This type utilizes the lazy evaluation to avoid repeating the computation
+/// of several performance-heavy or PoV-heavy tasks,
+/// such as checking the indirect ownership or reading the token property permissions.
+pub struct PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ WriterVariant,
+ FIsAdmin,
+ FPropertyPermissions,
+ FCheckTokenExist,
+ FGetProperties,
+> where
+ T: Config,
+ FIsAdmin: FnOnce() -> bool,
+ FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+{
+ collection: &'a Handle,
+ is_collection_admin: LazyValue<bool, FIsAdmin>,
+ property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,
+ check_token_exist: FCheckTokenExist,
+ get_properties: FGetProperties,
+ _phantom: PhantomData<(T, WriterVariant)>,
+}
+
+impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>
+ PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ NewTokenPropertyWriter,
+ FIsAdmin,
+ FPropertyPermissions,
+ FCheckTokenExist,
+ FGetProperties,
+ > where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+ FIsAdmin: FnOnce() -> bool,
+ FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+ FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+ FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+ /// A function to write properties to a **newly created** token.
+ pub fn write_token_properties(
+ &mut self,
+ mint_target_is_sender: bool,
+ token_id: TokenId,
+ properties_updates: impl Iterator<Item = Property>,
+ log: evm_coder::ethereum::Log,
+ ) -> DispatchResult {
+ self.internal_write_token_properties(
+ token_id,
+ properties_updates.map(|p| (p.key, Some(p.value))),
+ |_| Ok(mint_target_is_sender),
+ log,
+ )
+ }
+}
+
+impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>
+ PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ ExistingTokenPropertyWriter,
+ FIsAdmin,
+ FPropertyPermissions,
+ FCheckTokenExist,
+ FGetProperties,
+ > where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+ FIsAdmin: FnOnce() -> bool,
+ FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+ FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+ FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+ /// A function to write properties to an **already existing** token.
+ pub fn write_token_properties(
+ &mut self,
+ sender: &T::CrossAccountId,
+ token_id: TokenId,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ nesting_budget: &dyn Budget,
+ log: evm_coder::ethereum::Log,
+ ) -> DispatchResult {
+ self.internal_write_token_properties(
+ token_id,
+ properties_updates,
+ |collection| collection.check_token_indirect_owner(token_id, sender, nesting_budget),
+ log,
+ )
+ }
+}
+
+impl<
+ 'a,
+ T,
+ Handle,
+ WriterVariant,
+ FIsAdmin,
+ FPropertyPermissions,
+ FCheckTokenExist,
+ FGetProperties,
+ >
+ PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ WriterVariant,
+ FIsAdmin,
+ FPropertyPermissions,
+ FCheckTokenExist,
+ FGetProperties,
+ > where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+ FIsAdmin: FnOnce() -> bool,
+ FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,
+ FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,
+ FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,
+{
+ fn internal_write_token_properties<FCheckTokenOwner>(
+ &mut self,
+ token_id: TokenId,
+ properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
+ check_token_owner: FCheckTokenOwner,
+ log: evm_coder::ethereum::Log,
+ ) -> DispatchResult
+ where
+ FCheckTokenOwner: FnOnce(&Handle) -> Result<bool, DispatchError>,
+ {
+ let get_properties = self.get_properties;
+ let mut stored_properties = LazyValue::new(move || get_properties(token_id));
+
+ let mut is_token_owner = LazyValue::new(|| check_token_owner(self.collection));
+
+ let check_token_exist = self.check_token_exist;
+ let mut is_token_exist = LazyValue::new(move || check_token_exist(token_id));
+
+ for (key, value) in properties_updates {
+ let permission = self
+ .property_permissions
+ .value()
+ .get(&key)
+ .cloned()
+ .unwrap_or_else(PropertyPermission::none);
+
+ match permission {
+ PropertyPermission { mutable: false, .. }
+ if stored_properties.value().get(&key).is_some() =>
+ {
+ return Err(<Error<T>>::NoPermission.into());
+ }
+
+ PropertyPermission {
+ collection_admin,
+ token_owner,
+ ..
+ } => check_token_permissions::<T, _, _, _>(
+ collection_admin,
+ token_owner,
+ &mut self.is_collection_admin,
+ &mut is_token_owner,
+ &mut is_token_exist,
+ )?,
+ }
+
+ match value {
+ Some(value) => {
+ stored_properties
+ .value_mut()
+ .try_set(key.clone(), value)
+ .map_err(<Error<T>>::from)?;
+
+ <Pallet<T>>::deposit_event(Event::TokenPropertySet(
+ self.collection.id,
+ token_id,
+ key,
+ ));
+ }
+ None => {
+ stored_properties
+ .value_mut()
+ .remove(&key)
+ .map_err(<Error<T>>::from)?;
+
+ <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(
+ self.collection.id,
+ token_id,
+ key,
+ ));
+ }
+ }
+ }
+
+ let properties_changed = stored_properties.has_value();
+ if properties_changed {
+ <PalletEvm<T>>::deposit_log(log);
+
+ self.collection
+ .set_token_properties_map(token_id, stored_properties.into_inner());
+ }
+
+ Ok(())
+ }
+}
+
+/// Create a [`PropertyWriter`] for newly created tokens.
+pub fn property_writer_for_new_token<'a, T, Handle>(
+ collection: &'a Handle,
+ sender: &'a T::CrossAccountId,
+) -> PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ NewTokenPropertyWriter,
+ impl FnOnce() -> bool + 'a,
+ impl FnOnce() -> PropertiesPermissionMap + 'a,
+ impl Copy + FnOnce(TokenId) -> bool + 'a,
+ impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,
+>
+where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+ PropertyWriter {
+ collection,
+ is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
+ property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
+ check_token_exist: |token_id| {
+ debug_assert!(collection.token_exists(token_id));
+ true
+ },
+ get_properties: |token_id| {
+ debug_assert!(!collection.properties_exist(token_id));
+ TokenProperties::new()
+ },
+ _phantom: PhantomData,
+ }
+}
+
+#[cfg(feature = "runtime-benchmarks")]
+/// Create a `PropertyWriter` with preloaded `is_collection_admin` and `property_permissions.
+/// Also:
+/// * it will return `true` for the token ownership check.
+/// * it will return empty stored properties without reading them from the storage.
+pub fn collection_info_loaded_property_writer<T, Handle>(
+ collection: &Handle,
+ is_collection_admin: bool,
+ property_permissions: PropertiesPermissionMap,
+) -> PropertyWriter<
+ T,
+ Handle,
+ NewTokenPropertyWriter,
+ impl FnOnce() -> bool,
+ impl FnOnce() -> PropertiesPermissionMap,
+ impl Copy + FnOnce(TokenId) -> bool,
+ impl Copy + FnOnce(TokenId) -> TokenProperties,
+>
+where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+ PropertyWriter {
+ collection,
+ is_collection_admin: LazyValue::new(move || is_collection_admin),
+ property_permissions: LazyValue::new(move || property_permissions),
+ check_token_exist: |_token_id| true,
+ get_properties: |_token_id| TokenProperties::new(),
+ _phantom: PhantomData,
+ }
+}
+
+/// Create a [`PropertyWriter`] for already existing tokens.
+pub fn property_writer_for_existing_token<'a, T, Handle>(
+ collection: &'a Handle,
+ sender: &'a T::CrossAccountId,
+) -> PropertyWriter<
+ 'a,
+ T,
+ Handle,
+ ExistingTokenPropertyWriter,
+ impl FnOnce() -> bool + 'a,
+ impl FnOnce() -> PropertiesPermissionMap + 'a,
+ impl Copy + FnOnce(TokenId) -> bool + 'a,
+ impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,
+>
+where
+ T: Config,
+ Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,
+{
+ PropertyWriter {
+ collection,
+ is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
+ property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
+ check_token_exist: |token_id| collection.token_exists(token_id),
+ get_properties: |token_id| collection.get_token_properties_map(token_id),
+ _phantom: PhantomData,
+ }
+}
+
+/// Computes the weight delta for newly created tokens with properties.
+/// * `properties_nums` - The properties num of each created token.
+/// * `init_token_properties` - The function to obtain the weight from a token's properties num.
+pub fn init_token_properties_delta<T: Config, I: Fn(u32) -> Weight>(
+ properties_nums: impl Iterator<Item = u32>,
+ init_token_properties: I,
+) -> Weight {
+ let mut delta = properties_nums
+ .filter_map(|properties_num| {
+ if properties_num > 0 {
+ Some(init_token_properties(properties_num))
+ } else {
+ None
+ }
+ })
+ .fold(Weight::zero(), |a, b| a.saturating_add(b));
+
+ // If at least once the `init_token_properties` was called,
+ // it means at least one newly created token has properties.
+ // Becuase of that, some common collection data also was loaded and we need to add this weight.
+ // However, these common data was loaded only once which is guaranteed by the `PropertyWriter`.
+ if !delta.is_zero() {
+ delta = delta.saturating_add(<SelfWeightOf<T>>::init_token_properties_common())
+ }
+
+ delta
+}
+
#[cfg(any(feature = "tests", test))]
#[allow(missing_docs)]
pub mod tests {
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -25,7 +25,7 @@
weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
};
use pallet_structure::Error as StructureError;
-use sp_runtime::ArithmeticError;
+use sp_runtime::{ArithmeticError, DispatchError};
use sp_std::{vec::Vec, vec};
use up_data_structs::{Property, PropertyKey, PropertyValue, PropertyKeyPermission};
@@ -364,6 +364,20 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
+ fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ // No token properties are defined on fungibles
+ up_data_structs::TokenProperties::new()
+ }
+
+ fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
+ // No token properties are defined on fungibles
+ }
+
+ fn properties_exist(&self, _token: TokenId) -> bool {
+ // No token properties are defined on fungibles
+ false
+ }
+
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -402,6 +416,15 @@
Err(TokenOwnerError::MultipleOwners)
}
+ fn check_token_indirect_owner(
+ &self,
+ _token: TokenId,
+ _maybe_owner: &T::CrossAccountId,
+ _nesting_budget: &dyn Budget,
+ ) -> Result<bool, DispatchError> {
+ Ok(false)
+ }
+
/// Returns 10 tokens owners in no particular order.
fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -20,7 +20,9 @@
use frame_benchmarking::{benchmarks, account};
use pallet_common::{
bench_init,
- benchmarking::{create_collection_raw, property_key, property_value},
+ benchmarking::{
+ create_collection_raw, property_key, property_value, load_is_admin_and_property_permissions,
+ },
CommonCollectionOperations,
};
use sp_std::prelude::*;
@@ -198,14 +200,15 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
- reset_token_properties {
+ init_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
+
let perms = (0..b).map(|k| PropertyKeyPermission {
key: property_key(k as usize),
permission: PropertyPermission {
@@ -220,8 +223,26 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::NewToken { mint_target_is_sender: true }, &Unlimited)?}
+ let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner);
+ }: {
+ let mut property_writer = pallet_common::collection_info_loaded_property_writer(
+ &collection,
+ is_collection_admin,
+ property_permissions,
+ );
+
+ property_writer.write_token_properties(
+ true,
+ item,
+ props.into_iter(),
+ crate::erc::ERC721TokenEvent::TokenChanged {
+ token_id: item.into(),
+ }
+ .to_log(T::ContractAddress::get()),
+ )?
+ }
+
delete_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
bench_init!{
@@ -242,7 +263,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, owner.clone())?;
- <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?;
let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,49 +23,40 @@
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
+ weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf, init_token_properties_delta,
};
+use pallet_structure::Pallet as PalletStructure;
use sp_runtime::DispatchError;
use sp_std::{vec::Vec, vec};
use crate::{
AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,
- SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,
+ SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted, TokenProperties,
};
pub struct CommonWeights<T: Config>(PhantomData<T>);
impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {
match data {
- CreateItemExData::NFT(t) => {
- <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
- + t.iter()
- .filter_map(|t| {
- if t.properties.len() > 0 {
- Some(<SelfWeightOf<T>>::reset_token_properties(
- t.properties.len() as u32,
- ))
- } else {
- None
- }
- })
- .fold(Weight::zero(), |a, b| a.saturating_add(b))
- }
+ CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32)
+ .saturating_add(init_token_properties_delta::<T, _>(
+ t.iter().map(|t| t.properties.len() as u32),
+ <SelfWeightOf<T>>::init_token_properties,
+ )),
_ => Weight::zero(),
}
}
fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
- <SelfWeightOf<T>>::create_multiple_items(data.len() as u32)
- + data
- .iter()
- .filter_map(|t| match t {
- up_data_structs::CreateItemData::NFT(n) if n.properties.len() > 0 => Some(
- <SelfWeightOf<T>>::reset_token_properties(n.properties.len() as u32),
- ),
- _ => None,
- })
- .fold(Weight::zero(), |a, b| a.saturating_add(b))
+ <SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
+ init_token_properties_delta::<T, _>(
+ data.iter().map(|t| match t {
+ up_data_structs::CreateItemData::NFT(n) => n.properties.len() as u32,
+ _ => 0,
+ }),
+ <SelfWeightOf<T>>::init_token_properties,
+ ),
+ )
}
fn burn_item() -> Weight {
@@ -247,7 +238,6 @@
&sender,
token_id,
properties.into_iter(),
- pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
@@ -275,6 +265,14 @@
)
}
+ fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ <TokenProperties<T>>::get((self.id, token_id))
+ }
+
+ fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::set((self.id, token_id), map)
+ }
+
fn set_token_property_permissions(
&self,
sender: &T::CrossAccountId,
@@ -289,6 +287,10 @@
)
}
+ fn properties_exist(&self, token: TokenId) -> bool {
+ <TokenProperties<T>>::contains_key((self.id, token))
+ }
+
fn burn_item(
&self,
sender: T::CrossAccountId,
@@ -459,6 +461,21 @@
.ok_or(TokenOwnerError::NotFound)
}
+ fn check_token_indirect_owner(
+ &self,
+ token: TokenId,
+ maybe_owner: &T::CrossAccountId,
+ nesting_budget: &dyn Budget,
+ ) -> Result<bool, DispatchError> {
+ <PalletStructure<T>>::check_indirectly_owned(
+ maybe_owner.clone(),
+ self.id,
+ token,
+ None,
+ nesting_budget,
+ )
+ }
+
/// Returns token owners.
fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
self.token_owner(token).map_or_else(|_| vec![], |t| vec![t])
pallets/nonfungible/src/erc.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 Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::BoundedVec;31use up_data_structs::{32 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33 CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36 dispatch_to_evm, frontier_contract,37 execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43 eth::{self, TokenUri},44 CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53 TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59 /// The token has been changed.60 TokenChanged {61 /// Token ID.62 #[indexed]63 token_id: U256,64 },65}6667/// Token minting parameters68#[derive(AbiCoder, Default, Debug)]69pub struct MintTokenData {70 /// Minted token owner71 pub owner: eth::CrossAddress,72 /// Minted token properties73 pub properties: Vec<eth::Property>,74}7576frontier_contract! {77 macro_rules! NonfungibleHandle_result {...}78 impl<T: Config> Contract for NonfungibleHandle<T> {...}79}8081/// @title A contract that allows to set and delete token properties and change token property permissions.82#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]83impl<T: Config> NonfungibleHandle<T> {84 /// @notice Set permissions for token property.85 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.86 /// @param key Property key.87 /// @param isMutable Permission to mutate property.88 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.89 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.90 #[solidity(hide)]91 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]92 fn set_token_property_permission(93 &mut self,94 caller: Caller,95 key: String,96 is_mutable: bool,97 collection_admin: bool,98 token_owner: bool,99 ) -> Result<()> {100 let caller = T::CrossAccountId::from_eth(caller);101 <Pallet<T>>::set_token_property_permissions(102 self,103 &caller,104 vec![PropertyKeyPermission {105 key: <Vec<u8>>::from(key)106 .try_into()107 .map_err(|_| "too long key")?,108 permission: PropertyPermission {109 mutable: is_mutable,110 collection_admin,111 token_owner,112 },113 }],114 )115 .map_err(dispatch_to_evm::<T>)116 }117118 /// @notice Set permissions for token property.119 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.120 /// @param permissions Permissions for keys.121 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]122 fn set_token_property_permissions(123 &mut self,124 caller: Caller,125 permissions: Vec<eth::TokenPropertyPermission>,126 ) -> Result<()> {127 let caller = T::CrossAccountId::from_eth(caller);128 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;129130 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)131 .map_err(dispatch_to_evm::<T>)132 }133134 /// @notice Get permissions for token properties.135 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {136 let perms = <Pallet<T>>::token_property_permission(self.id);137 Ok(perms138 .into_iter()139 .map(eth::TokenPropertyPermission::from)140 .collect())141 }142143 /// @notice Set token property value.144 /// @dev Throws error if `msg.sender` has no permission to edit the property.145 /// @param tokenId ID of the token.146 /// @param key Property key.147 /// @param value Property value.148 #[solidity(hide)]149 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]150 fn set_property(151 &mut self,152 caller: Caller,153 token_id: U256,154 key: String,155 value: Bytes,156 ) -> Result<()> {157 let caller = T::CrossAccountId::from_eth(caller);158 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;159 let key = <Vec<u8>>::from(key)160 .try_into()161 .map_err(|_| "key too long")?;162 let value = value.0.try_into().map_err(|_| "value too long")?;163164 let nesting_budget = self165 .recorder166 .weight_calls_budget(<StructureWeight<T>>::find_parent());167168 <Pallet<T>>::set_token_property(169 self,170 &caller,171 TokenId(token_id),172 Property { key, value },173 &nesting_budget,174 )175 .map_err(dispatch_to_evm::<T>)176 }177178 /// @notice Set token properties value.179 /// @dev Throws error if `msg.sender` has no permission to edit the property.180 /// @param tokenId ID of the token.181 /// @param properties settable properties182 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]183 fn set_properties(184 &mut self,185 caller: Caller,186 token_id: U256,187 properties: Vec<eth::Property>,188 ) -> Result<()> {189 let caller = T::CrossAccountId::from_eth(caller);190 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;191192 let nesting_budget = self193 .recorder194 .weight_calls_budget(<StructureWeight<T>>::find_parent());195196 let properties = properties197 .into_iter()198 .map(eth::Property::try_into)199 .collect::<Result<Vec<_>>>()?;200201 <Pallet<T>>::set_token_properties(202 self,203 &caller,204 TokenId(token_id),205 properties.into_iter(),206 pallet_common::SetPropertyMode::ExistingToken,207 &nesting_budget,208 )209 .map_err(dispatch_to_evm::<T>)210 }211212 /// @notice Delete token property value.213 /// @dev Throws error if `msg.sender` has no permission to edit the property.214 /// @param tokenId ID of the token.215 /// @param key Property key.216 #[solidity(hide)]217 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]218 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {219 let caller = T::CrossAccountId::from_eth(caller);220 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;221 let key = <Vec<u8>>::from(key)222 .try_into()223 .map_err(|_| "key too long")?;224225 let nesting_budget = self226 .recorder227 .weight_calls_budget(<StructureWeight<T>>::find_parent());228229 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)230 .map_err(dispatch_to_evm::<T>)231 }232233 /// @notice Delete token properties value.234 /// @dev Throws error if `msg.sender` has no permission to edit the property.235 /// @param tokenId ID of the token.236 /// @param keys Properties key.237 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]238 fn delete_properties(239 &mut self,240 token_id: U256,241 caller: Caller,242 keys: Vec<String>,243 ) -> Result<()> {244 let caller = T::CrossAccountId::from_eth(caller);245 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;246 let keys = keys247 .into_iter()248 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))249 .collect::<Result<Vec<_>>>()?;250251 let nesting_budget = self252 .recorder253 .weight_calls_budget(<StructureWeight<T>>::find_parent());254255 <Pallet<T>>::delete_token_properties(256 self,257 &caller,258 TokenId(token_id),259 keys.into_iter(),260 &nesting_budget,261 )262 .map_err(dispatch_to_evm::<T>)263 }264265 /// @notice Get token property value.266 /// @dev Throws error if key not found267 /// @param tokenId ID of the token.268 /// @param key Property key.269 /// @return Property value bytes270 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {271 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;272 let key = <Vec<u8>>::from(key)273 .try_into()274 .map_err(|_| "key too long")?;275276 let props = <TokenProperties<T>>::get((self.id, token_id));277 let prop = props.get(&key).ok_or("key not found")?;278279 Ok(prop.to_vec().into())280 }281}282283#[derive(ToLog)]284pub enum ERC721Events {285 /// @dev This emits when ownership of any NFT changes by any mechanism.286 /// This event emits when NFTs are created (`from` == 0) and destroyed287 /// (`to` == 0). Exception: during contract creation, any number of NFTs288 /// may be created and assigned without emitting Transfer. At the time of289 /// any transfer, the approved address for that NFT (if any) is reset to none.290 Transfer {291 #[indexed]292 from: Address,293 #[indexed]294 to: Address,295 #[indexed]296 token_id: U256,297 },298 /// @dev This emits when the approved address for an NFT is changed or299 /// reaffirmed. The zero address indicates there is no approved address.300 /// When a Transfer event emits, this also indicates that the approved301 /// address for that NFT (if any) is reset to none.302 Approval {303 #[indexed]304 owner: Address,305 #[indexed]306 approved: Address,307 #[indexed]308 token_id: U256,309 },310 /// @dev This emits when an operator is enabled or disabled for an owner.311 /// The operator can manage all NFTs of the owner.312 #[allow(dead_code)]313 ApprovalForAll {314 #[indexed]315 owner: Address,316 #[indexed]317 operator: Address,318 approved: bool,319 },320}321322/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension323/// @dev See https://eips.ethereum.org/EIPS/eip-721324#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]325impl<T: Config> NonfungibleHandle<T>326where327 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,328{329 /// @notice A descriptive name for a collection of NFTs in this contract330 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`331 #[solidity(hide, rename_selector = "name")]332 fn name_proxy(&self) -> String {333 self.name()334 }335336 /// @notice An abbreviated name for NFTs in this contract337 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`338 #[solidity(hide, rename_selector = "symbol")]339 fn symbol_proxy(&self) -> String {340 self.symbol()341 }342343 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.344 ///345 /// @dev If the token has a `url` property and it is not empty, it is returned.346 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.347 /// If the collection property `baseURI` is empty or absent, return "" (empty string)348 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix349 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).350 ///351 /// @return token's const_metadata352 #[solidity(rename_selector = "tokenURI")]353 fn token_uri(&self, token_id: U256) -> Result<String> {354 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;355356 match get_token_property(self, token_id_u32, &key::url()).as_deref() {357 Err(_) | Ok("") => (),358 Ok(url) => {359 return Ok(url.into());360 }361 };362363 let base_uri =364 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())365 .map(BoundedVec::into_inner)366 .map(String::from_utf8)367 .transpose()368 .map_err(|e| {369 Error::Revert(alloc::format!(370 "Can not convert value \"baseURI\" to string with error \"{e}\""371 ))372 })?;373374 let base_uri = match base_uri.as_deref() {375 None | Some("") => {376 return Ok("".into());377 }378 Some(base_uri) => base_uri.into(),379 };380381 Ok(382 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {383 Err(_) | Ok("") => base_uri,384 Ok(suffix) => base_uri + suffix,385 },386 )387 }388}389390/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension391/// @dev See https://eips.ethereum.org/EIPS/eip-721392#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]393impl<T: Config> NonfungibleHandle<T> {394 /// @notice Enumerate valid NFTs395 /// @param index A counter less than `totalSupply()`396 /// @return The token identifier for the `index`th NFT,397 /// (sort order not specified)398 fn token_by_index(&self, index: U256) -> U256 {399 index400 }401402 /// @dev Not implemented403 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {404 // TODO: Not implemetable405 Err("not implemented".into())406 }407408 /// @notice Count NFTs tracked by this contract409 /// @return A count of valid NFTs tracked by this contract, where each one of410 /// them has an assigned and queryable owner not equal to the zero address411 fn total_supply(&self) -> Result<U256> {412 self.consume_store_reads(1)?;413 Ok(<Pallet<T>>::total_supply(self).into())414 }415}416417/// @title ERC-721 Non-Fungible Token Standard418/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md419#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]420impl<T: Config> NonfungibleHandle<T> {421 /// @notice Count all NFTs assigned to an owner422 /// @dev NFTs assigned to the zero address are considered invalid, and this423 /// function throws for queries about the zero address.424 /// @param owner An address for whom to query the balance425 /// @return The number of NFTs owned by `owner`, possibly zero426 fn balance_of(&self, owner: Address) -> Result<U256> {427 self.consume_store_reads(1)?;428 let owner = T::CrossAccountId::from_eth(owner);429 let balance = <AccountBalance<T>>::get((self.id, owner));430 Ok(balance.into())431 }432 /// @notice Find the owner of an NFT433 /// @dev NFTs assigned to zero address are considered invalid, and queries434 /// about them do throw.435 /// @param tokenId The identifier for an NFT436 /// @return The address of the owner of the NFT437 fn owner_of(&self, token_id: U256) -> Result<Address> {438 self.consume_store_reads(1)?;439 let token: TokenId = token_id.try_into()?;440 Ok(*<TokenData<T>>::get((self.id, token))441 .ok_or("token not found")?442 .owner443 .as_eth())444 }445 /// @dev Not implemented446 #[solidity(rename_selector = "safeTransferFrom")]447 fn safe_transfer_from_with_data(448 &mut self,449 _from: Address,450 _to: Address,451 _token_id: U256,452 _data: Bytes,453 ) -> Result<()> {454 // TODO: Not implemetable455 Err("not implemented".into())456 }457 /// @dev Not implemented458 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {459 // TODO: Not implemetable460 Err("not implemented".into())461 }462463 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE464 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE465 /// THEY MAY BE PERMANENTLY LOST466 /// @dev Throws unless `msg.sender` is the current owner or an authorized467 /// operator for this NFT. Throws if `from` is not the current owner. Throws468 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.469 /// @param from The current owner of the NFT470 /// @param to The new owner471 /// @param tokenId The NFT to transfer472 #[weight(<CommonWeights<T>>::transfer_from())]473 fn transfer_from(474 &mut self,475 caller: Caller,476 from: Address,477 to: Address,478 token_id: U256,479 ) -> Result<()> {480 let caller = T::CrossAccountId::from_eth(caller);481 let from = T::CrossAccountId::from_eth(from);482 let to = T::CrossAccountId::from_eth(to);483 let token = token_id.try_into()?;484 let budget = self485 .recorder486 .weight_calls_budget(<StructureWeight<T>>::find_parent());487488 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)489 .map_err(|e| dispatch_to_evm::<T>(e.error))?;490 Ok(())491 }492493 /// @notice Set or reaffirm the approved address for an NFT494 /// @dev The zero address indicates there is no approved address.495 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized496 /// operator of the current owner.497 /// @param approved The new approved NFT controller498 /// @param tokenId The NFT to approve499 #[weight(<SelfWeightOf<T>>::approve())]500 fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {501 let caller = T::CrossAccountId::from_eth(caller);502 let approved = T::CrossAccountId::from_eth(approved);503 let token = token_id.try_into()?;504505 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))506 .map_err(dispatch_to_evm::<T>)?;507 Ok(())508 }509510 /// @notice Sets or unsets the approval of a given operator.511 /// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.512 /// @param operator Operator513 /// @param approved Should operator status be granted or revoked?514 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]515 fn set_approval_for_all(516 &mut self,517 caller: Caller,518 operator: Address,519 approved: bool,520 ) -> Result<()> {521 let caller = T::CrossAccountId::from_eth(caller);522 let operator = T::CrossAccountId::from_eth(operator);523524 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)525 .map_err(dispatch_to_evm::<T>)?;526 Ok(())527 }528529 /// @notice Get the approved address for a single NFT530 /// @dev Throws if `tokenId` is not a valid NFT531 /// @param tokenId The NFT to find the approved address for532 /// @return The approved address for this NFT, or the zero address if there is none533 fn get_approved(&self, token_id: U256) -> Result<Address> {534 let token_id = token_id.try_into()?;535 let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;536 Ok(if let Some(operator) = operator {537 *operator.as_eth()538 } else {539 Address::zero()540 })541 }542543 /// @notice Tells whether the given `owner` approves the `operator`.544 #[weight(<SelfWeightOf<T>>::allowance_for_all())]545 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {546 let owner = T::CrossAccountId::from_eth(owner);547 let operator = T::CrossAccountId::from_eth(operator);548549 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))550 }551}552553/// @title ERC721 Token that can be irreversibly burned (destroyed).554#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]555impl<T: Config> NonfungibleHandle<T> {556 /// @notice Burns a specific ERC721 token.557 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized558 /// operator of the current owner.559 /// @param tokenId The NFT to approve560 #[weight(<SelfWeightOf<T>>::burn_item())]561 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {562 let caller = T::CrossAccountId::from_eth(caller);563 let token = token_id.try_into()?;564565 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;566 Ok(())567 }568}569570/// @title ERC721 minting logic.571#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]572impl<T: Config> NonfungibleHandle<T> {573 /// @notice Function to mint a token.574 /// @param to The new owner575 /// @return uint256 The id of the newly minted token576 #[weight(<SelfWeightOf<T>>::create_item())]577 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {578 let token_id: U256 = <TokensMinted<T>>::get(self.id)579 .checked_add(1)580 .ok_or("item id overflow")?581 .into();582 self.mint_check_id(caller, to, token_id)?;583 Ok(token_id)584 }585586 /// @notice Function to mint a token.587 /// @dev `tokenId` should be obtained with `nextTokenId` method,588 /// unlike standard, you can't specify it manually589 /// @param to The new owner590 /// @param tokenId ID of the minted NFT591 #[solidity(hide, rename_selector = "mint")]592 #[weight(<SelfWeightOf<T>>::create_item())]593 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {594 let caller = T::CrossAccountId::from_eth(caller);595 let to = T::CrossAccountId::from_eth(to);596 let token_id: u32 = token_id.try_into()?;597 let budget = self598 .recorder599 .weight_calls_budget(<StructureWeight<T>>::find_parent());600601 if <TokensMinted<T>>::get(self.id)602 .checked_add(1)603 .ok_or("item id overflow")?604 != token_id605 {606 return Err("item id should be next".into());607 }608609 <Pallet<T>>::create_item(610 self,611 &caller,612 CreateItemData::<T> {613 properties: BoundedVec::default(),614 owner: to,615 },616 &budget,617 )618 .map_err(dispatch_to_evm::<T>)?;619620 Ok(true)621 }622623 /// @notice Function to mint token with the given tokenUri.624 /// @param to The new owner625 /// @param tokenUri Token URI that would be stored in the NFT properties626 /// @return uint256 The id of the newly minted token627 #[solidity(rename_selector = "mintWithTokenURI")]628 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]629 fn mint_with_token_uri(630 &mut self,631 caller: Caller,632 to: Address,633 token_uri: String,634 ) -> Result<U256> {635 let token_id: U256 = <TokensMinted<T>>::get(self.id)636 .checked_add(1)637 .ok_or("item id overflow")?638 .into();639 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;640 Ok(token_id)641 }642643 /// @notice Function to mint token with the given tokenUri.644 /// @dev `tokenId` should be obtained with `nextTokenId` method,645 /// unlike standard, you can't specify it manually646 /// @param to The new owner647 /// @param tokenId ID of the minted NFT648 /// @param tokenUri Token URI that would be stored in the NFT properties649 #[solidity(hide, rename_selector = "mintWithTokenURI")]650 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]651 fn mint_with_token_uri_check_id(652 &mut self,653 caller: Caller,654 to: Address,655 token_id: U256,656 token_uri: String,657 ) -> Result<bool> {658 let key = key::url();659 let permission = get_token_permission::<T>(self.id, &key)?;660 if !permission.collection_admin {661 return Err("Operation is not allowed".into());662 }663664 let caller = T::CrossAccountId::from_eth(caller);665 let to = T::CrossAccountId::from_eth(to);666 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;667 let budget = self668 .recorder669 .weight_calls_budget(<StructureWeight<T>>::find_parent());670671 if <TokensMinted<T>>::get(self.id)672 .checked_add(1)673 .ok_or("item id overflow")?674 != token_id675 {676 return Err("item id should be next".into());677 }678679 let mut properties = CollectionPropertiesVec::default();680 properties681 .try_push(Property {682 key,683 value: token_uri684 .into_bytes()685 .try_into()686 .map_err(|_| "token uri is too long")?,687 })688 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;689690 <Pallet<T>>::create_item(691 self,692 &caller,693 CreateItemData::<T> {694 properties,695 owner: to,696 },697 &budget,698 )699 .map_err(dispatch_to_evm::<T>)?;700 Ok(true)701 }702}703704fn get_token_property<T: Config>(705 collection: &CollectionHandle<T>,706 token_id: u32,707 key: &up_data_structs::PropertyKey,708) -> Result<String> {709 collection.consume_store_reads(1)?;710 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))711 .map_err(|_| Error::Revert("Token properties not found".into()))?;712 if let Some(property) = properties.get(key) {713 return Ok(String::from_utf8_lossy(property).into());714 }715716 Err("Property tokenURI not found".into())717}718719fn get_token_permission<T: Config>(720 collection_id: CollectionId,721 key: &PropertyKey,722) -> Result<PropertyPermission> {723 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)724 .map_err(|_| Error::Revert("No permissions for collection".into()))?;725 let a = token_property_permissions726 .get(key)727 .map(Clone::clone)728 .ok_or_else(|| {729 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();730 Error::Revert(alloc::format!("No permission for key {key}"))731 })?;732 Ok(a)733}734735/// @title Unique extensions for ERC721.736#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]737impl<T: Config> NonfungibleHandle<T>738where739 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,740{741 /// @notice A descriptive name for a collection of NFTs in this contract742 fn name(&self) -> String {743 decode_utf16(self.name.iter().copied())744 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))745 .collect::<String>()746 }747748 /// @notice An abbreviated name for NFTs in this contract749 fn symbol(&self) -> String {750 String::from_utf8_lossy(&self.token_prefix).into()751 }752753 /// @notice A description for the collection.754 fn description(&self) -> String {755 decode_utf16(self.description.iter().copied())756 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))757 .collect::<String>()758 }759760 /// Returns the owner (in cross format) of the token.761 ///762 /// @param tokenId Id for the token.763 #[solidity(hide)]764 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {765 Self::owner_of_cross(self, token_id)766 }767768 /// Returns the owner (in cross format) of the token.769 ///770 /// @param tokenId Id for the token.771 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {772 Self::token_owner(self, token_id.try_into()?)773 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))774 .map_err(|_| Error::Revert("token not found".into()))775 }776777 /// @notice Count all NFTs assigned to an owner778 /// @param owner An cross address for whom to query the balance779 /// @return The number of NFTs owned by `owner`, possibly zero780 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {781 self.consume_store_reads(1)?;782 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));783 Ok(balance.into())784 }785786 /// Returns the token properties.787 ///788 /// @param tokenId Id for the token.789 /// @param keys Properties keys. Empty keys for all propertyes.790 /// @return Vector of properties key/value pairs.791 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {792 let keys = keys793 .into_iter()794 .map(|key| {795 <Vec<u8>>::from(key)796 .try_into()797 .map_err(|_| Error::Revert("key too large".into()))798 })799 .collect::<Result<Vec<_>>>()?;800801 <Self as CommonCollectionOperations<T>>::token_properties(802 self,803 token_id.try_into()?,804 if keys.is_empty() { None } else { Some(keys) },805 )806 .into_iter()807 .map(eth::Property::try_from)808 .collect::<Result<Vec<_>>>()809 }810811 /// @notice Set or reaffirm the approved address for an NFT812 /// @dev The zero address indicates there is no approved address.813 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized814 /// operator of the current owner.815 /// @param approved The new substrate address approved NFT controller816 /// @param tokenId The NFT to approve817 #[weight(<SelfWeightOf<T>>::approve())]818 fn approve_cross(819 &mut self,820 caller: Caller,821 approved: eth::CrossAddress,822 token_id: U256,823 ) -> Result<()> {824 let caller = T::CrossAccountId::from_eth(caller);825 let approved = approved.into_sub_cross_account::<T>()?;826 let token = token_id.try_into()?;827828 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))829 .map_err(dispatch_to_evm::<T>)?;830 Ok(())831 }832833 /// @notice Transfer ownership of an NFT834 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`835 /// is the zero address. Throws if `tokenId` is not a valid NFT.836 /// @param to The new owner837 /// @param tokenId The NFT to transfer838 #[weight(<CommonWeights<T>>::transfer())]839 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {840 let caller = T::CrossAccountId::from_eth(caller);841 let to = T::CrossAccountId::from_eth(to);842 let token = token_id.try_into()?;843 let budget = self844 .recorder845 .weight_calls_budget(<StructureWeight<T>>::find_parent());846847 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)848 .map_err(|e| dispatch_to_evm::<T>(e.error))?;849 Ok(())850 }851852 /// @notice Transfer ownership of an NFT853 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`854 /// is the zero address. Throws if `tokenId` is not a valid NFT.855 /// @param to The new owner856 /// @param tokenId The NFT to transfer857 #[weight(<CommonWeights<T>>::transfer())]858 fn transfer_cross(859 &mut self,860 caller: Caller,861 to: eth::CrossAddress,862 token_id: U256,863 ) -> Result<()> {864 let caller = T::CrossAccountId::from_eth(caller);865 let to = to.into_sub_cross_account::<T>()?;866 let token = token_id.try_into()?;867 let budget = self868 .recorder869 .weight_calls_budget(<StructureWeight<T>>::find_parent());870871 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)872 .map_err(|e| dispatch_to_evm::<T>(e.error))?;873 Ok(())874 }875876 /// @notice Transfer ownership of an NFT from cross account address to cross account address877 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`878 /// is the zero address. Throws if `tokenId` is not a valid NFT.879 /// @param from Cross acccount address of current owner880 /// @param to Cross acccount address of new owner881 /// @param tokenId The NFT to transfer882 #[weight(<CommonWeights<T>>::transfer_from())]883 fn transfer_from_cross(884 &mut self,885 caller: Caller,886 from: eth::CrossAddress,887 to: eth::CrossAddress,888 token_id: U256,889 ) -> Result<()> {890 let caller = T::CrossAccountId::from_eth(caller);891 let from = from.into_sub_cross_account::<T>()?;892 let to = to.into_sub_cross_account::<T>()?;893 let token_id = token_id.try_into()?;894 let budget = self895 .recorder896 .weight_calls_budget(<StructureWeight<T>>::find_parent());897 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)898 .map_err(|e| dispatch_to_evm::<T>(e.error))?;899 Ok(())900 }901902 /// @notice Burns a specific ERC721 token.903 /// @dev Throws unless `msg.sender` is the current owner or an authorized904 /// operator for this NFT. Throws if `from` is not the current owner. Throws905 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.906 /// @param from The current owner of the NFT907 /// @param tokenId The NFT to transfer908 #[solidity(hide)]909 #[weight(<SelfWeightOf<T>>::burn_from())]910 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {911 let caller = T::CrossAccountId::from_eth(caller);912 let from = T::CrossAccountId::from_eth(from);913 let token = token_id.try_into()?;914 let budget = self915 .recorder916 .weight_calls_budget(<StructureWeight<T>>::find_parent());917918 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)919 .map_err(dispatch_to_evm::<T>)?;920 Ok(())921 }922923 /// @notice Burns a specific ERC721 token.924 /// @dev Throws unless `msg.sender` is the current owner or an authorized925 /// operator for this NFT. Throws if `from` is not the current owner. Throws926 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.927 /// @param from The current owner of the NFT928 /// @param tokenId The NFT to transfer929 #[weight(<SelfWeightOf<T>>::burn_from())]930 fn burn_from_cross(931 &mut self,932 caller: Caller,933 from: eth::CrossAddress,934 token_id: U256,935 ) -> Result<()> {936 let caller = T::CrossAccountId::from_eth(caller);937 let from = from.into_sub_cross_account::<T>()?;938 let token = token_id.try_into()?;939 let budget = self940 .recorder941 .weight_calls_budget(<StructureWeight<T>>::find_parent());942943 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)944 .map_err(dispatch_to_evm::<T>)?;945 Ok(())946 }947948 /// @notice Returns next free NFT ID.949 fn next_token_id(&self) -> Result<U256> {950 self.consume_store_reads(1)?;951 Ok(<Pallet<T>>::next_token_id(self)952 .map_err(dispatch_to_evm::<T>)?953 .into())954 }955956 /// @notice Function to mint multiple tokens.957 /// @dev `tokenIds` should be an array of consecutive numbers and first number958 /// should be obtained with `nextTokenId` method959 /// @param to The new owner960 /// @param tokenIds IDs of the minted NFTs961 #[solidity(hide)]962 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]963 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {964 let caller = T::CrossAccountId::from_eth(caller);965 let to = T::CrossAccountId::from_eth(to);966 let mut expected_index = <TokensMinted<T>>::get(self.id)967 .checked_add(1)968 .ok_or("item id overflow")?;969 let budget = self970 .recorder971 .weight_calls_budget(<StructureWeight<T>>::find_parent());972973 let total_tokens = token_ids.len();974 for id in token_ids.into_iter() {975 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;976 if id != expected_index {977 return Err("item id should be next".into());978 }979 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;980 }981 let data = (0..total_tokens)982 .map(|_| CreateItemData::<T> {983 properties: BoundedVec::default(),984 owner: to.clone(),985 })986 .collect();987988 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)989 .map_err(dispatch_to_evm::<T>)?;990 Ok(true)991 }992993 /// @notice Function to mint a token.994 /// @param data Array of pairs of token owner and token's properties for minted token995 #[weight(<SelfWeightOf<T>>::create_multiple_items(data.len() as u32) + <SelfWeightOf<T>>::set_token_properties(data.len() as u32))]996 fn mint_bulk_cross(&mut self, caller: Caller, data: Vec<MintTokenData>) -> Result<bool> {997 let caller = T::CrossAccountId::from_eth(caller);998 let budget = self999 .recorder1000 .weight_calls_budget(<StructureWeight<T>>::find_parent());10011002 let mut create_nft_data = Vec::with_capacity(data.len());1003 for MintTokenData { owner, properties } in data {1004 let owner = owner.into_sub_cross_account::<T>()?;1005 create_nft_data.push(CreateItemData::<T> {1006 properties: properties1007 .into_iter()1008 .map(|property| property.try_into())1009 .collect::<Result<Vec<_>>>()?1010 .try_into()1011 .map_err(|_| "too many properties")?,1012 owner,1013 });1014 }10151016 <Pallet<T>>::create_multiple_items(self, &caller, create_nft_data, &budget)1017 .map_err(dispatch_to_evm::<T>)?;1018 Ok(true)1019 }10201021 /// @notice Function to mint multiple tokens with the given tokenUris.1022 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1023 /// numbers and first number should be obtained with `nextTokenId` method1024 /// @param to The new owner1025 /// @param tokens array of pairs of token ID and token URI for minted tokens1026 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1027 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1028 fn mint_bulk_with_token_uri(1029 &mut self,1030 caller: Caller,1031 to: Address,1032 tokens: Vec<TokenUri>,1033 ) -> Result<bool> {1034 let key = key::url();1035 let caller = T::CrossAccountId::from_eth(caller);1036 let to = T::CrossAccountId::from_eth(to);1037 let mut expected_index = <TokensMinted<T>>::get(self.id)1038 .checked_add(1)1039 .ok_or("item id overflow")?;1040 let budget = self1041 .recorder1042 .weight_calls_budget(<StructureWeight<T>>::find_parent());10431044 let mut data = Vec::with_capacity(tokens.len());1045 for TokenUri { id, uri } in tokens {1046 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1047 if id != expected_index {1048 return Err("item id should be next".into());1049 }1050 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10511052 let mut properties = CollectionPropertiesVec::default();1053 properties1054 .try_push(Property {1055 key: key.clone(),1056 value: uri1057 .into_bytes()1058 .try_into()1059 .map_err(|_| "token uri is too long")?,1060 })1061 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10621063 data.push(CreateItemData::<T> {1064 properties,1065 owner: to.clone(),1066 });1067 }10681069 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1070 .map_err(dispatch_to_evm::<T>)?;1071 Ok(true)1072 }10731074 /// @notice Function to mint a token.1075 /// @param to The new owner crossAccountId1076 /// @param properties Properties of minted token1077 /// @return uint256 The id of the newly minted token1078 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1079 fn mint_cross(1080 &mut self,1081 caller: Caller,1082 to: eth::CrossAddress,1083 properties: Vec<eth::Property>,1084 ) -> Result<U256> {1085 let token_id = <TokensMinted<T>>::get(self.id)1086 .checked_add(1)1087 .ok_or("item id overflow")?;10881089 let to = to.into_sub_cross_account::<T>()?;10901091 let properties = properties1092 .into_iter()1093 .map(eth::Property::try_into)1094 .collect::<Result<Vec<_>>>()?1095 .try_into()1096 .map_err(|_| Error::Revert("too many properties".to_string()))?;10971098 let caller = T::CrossAccountId::from_eth(caller);10991100 let budget = self1101 .recorder1102 .weight_calls_budget(<StructureWeight<T>>::find_parent());11031104 <Pallet<T>>::create_item(1105 self,1106 &caller,1107 CreateItemData::<T> {1108 properties,1109 owner: to,1110 },1111 &budget,1112 )1113 .map_err(dispatch_to_evm::<T>)?;11141115 Ok(token_id.into())1116 }11171118 /// @notice Returns collection helper contract address1119 fn collection_helper_address(&self) -> Address {1120 T::ContractAddress::get()1121 }1122}11231124#[solidity_interface(1125 name = UniqueNFT,1126 is(1127 ERC721,1128 ERC721Enumerable,1129 ERC721UniqueExtensions,1130 ERC721UniqueMintable,1131 ERC721Burnable,1132 ERC721Metadata(if(this.flags.erc721metadata)),1133 Collection(via(common_mut returns CollectionHandle<T>)),1134 TokenProperties,1135 ),1136 enum(derive(PreDispatch)),1137)]1138impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11391140// Not a tests, but code generators1141generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1142generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11431144impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1145where1146 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1147{1148 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11491150 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1151 call::<T, UniqueNFTCall<T>, _, _>(handle, self)1152 }1153}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 Pallet EVM API18//!19//! Provides ERC-721 standart support implementation and EVM API for unique extensions for Nonfungible Pallet.20//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.2122extern crate alloc;2324use alloc::string::ToString;25use core::{26 char::{REPLACEMENT_CHARACTER, decode_utf16},27 convert::TryInto,28};29use evm_coder::{abi::AbiType, AbiCoder, ToLog, generate_stubgen, solidity_interface, types::*};30use frame_support::BoundedVec;31use up_data_structs::{32 TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,33 CollectionPropertiesVec,34};35use pallet_evm_coder_substrate::{36 dispatch_to_evm, frontier_contract,37 execution::{Result, PreDispatch, Error},38};39use sp_std::{vec::Vec, vec};40use pallet_common::{41 CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,42 erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},43 eth::{self, TokenUri},44 CommonWeightInfo,45};46use pallet_evm::{account::CrossAccountId, PrecompileHandle};47use pallet_evm_coder_substrate::call;48use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};49use sp_core::{U256, Get};5051use crate::{52 AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,53 TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,54};5556/// Nft events.57#[derive(ToLog)]58pub enum ERC721TokenEvent {59 /// The token has been changed.60 TokenChanged {61 /// Token ID.62 #[indexed]63 token_id: U256,64 },65}6667/// Token minting parameters68#[derive(AbiCoder, Default, Debug)]69pub struct MintTokenData {70 /// Minted token owner71 pub owner: eth::CrossAddress,72 /// Minted token properties73 pub properties: Vec<eth::Property>,74}7576frontier_contract! {77 macro_rules! NonfungibleHandle_result {...}78 impl<T: Config> Contract for NonfungibleHandle<T> {...}79}8081/// @title A contract that allows to set and delete token properties and change token property permissions.82#[solidity_interface(name = TokenProperties, events(ERC721TokenEvent), enum(derive(PreDispatch)), enum_attr(weight))]83impl<T: Config> NonfungibleHandle<T> {84 /// @notice Set permissions for token property.85 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.86 /// @param key Property key.87 /// @param isMutable Permission to mutate property.88 /// @param collectionAdmin Permission to mutate property by collection admin if property is mutable.89 /// @param tokenOwner Permission to mutate property by token owner if property is mutable.90 #[solidity(hide)]91 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(1))]92 fn set_token_property_permission(93 &mut self,94 caller: Caller,95 key: String,96 is_mutable: bool,97 collection_admin: bool,98 token_owner: bool,99 ) -> Result<()> {100 let caller = T::CrossAccountId::from_eth(caller);101 <Pallet<T>>::set_token_property_permissions(102 self,103 &caller,104 vec![PropertyKeyPermission {105 key: <Vec<u8>>::from(key)106 .try_into()107 .map_err(|_| "too long key")?,108 permission: PropertyPermission {109 mutable: is_mutable,110 collection_admin,111 token_owner,112 },113 }],114 )115 .map_err(dispatch_to_evm::<T>)116 }117118 /// @notice Set permissions for token property.119 /// @dev Throws error if `msg.sender` is not admin or owner of the collection.120 /// @param permissions Permissions for keys.121 #[weight(<SelfWeightOf<T>>::set_token_property_permissions(permissions.len() as u32))]122 fn set_token_property_permissions(123 &mut self,124 caller: Caller,125 permissions: Vec<eth::TokenPropertyPermission>,126 ) -> Result<()> {127 let caller = T::CrossAccountId::from_eth(caller);128 let perms = eth::TokenPropertyPermission::into_property_key_permissions(permissions)?;129130 <Pallet<T>>::set_token_property_permissions(self, &caller, perms)131 .map_err(dispatch_to_evm::<T>)132 }133134 /// @notice Get permissions for token properties.135 fn token_property_permissions(&self) -> Result<Vec<eth::TokenPropertyPermission>> {136 let perms = <Pallet<T>>::token_property_permission(self.id);137 Ok(perms138 .into_iter()139 .map(eth::TokenPropertyPermission::from)140 .collect())141 }142143 /// @notice Set token property value.144 /// @dev Throws error if `msg.sender` has no permission to edit the property.145 /// @param tokenId ID of the token.146 /// @param key Property key.147 /// @param value Property value.148 #[solidity(hide)]149 #[weight(<SelfWeightOf<T>>::set_token_properties(1))]150 fn set_property(151 &mut self,152 caller: Caller,153 token_id: U256,154 key: String,155 value: Bytes,156 ) -> Result<()> {157 let caller = T::CrossAccountId::from_eth(caller);158 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;159 let key = <Vec<u8>>::from(key)160 .try_into()161 .map_err(|_| "key too long")?;162 let value = value.0.try_into().map_err(|_| "value too long")?;163164 let nesting_budget = self165 .recorder166 .weight_calls_budget(<StructureWeight<T>>::find_parent());167168 <Pallet<T>>::set_token_property(169 self,170 &caller,171 TokenId(token_id),172 Property { key, value },173 &nesting_budget,174 )175 .map_err(dispatch_to_evm::<T>)176 }177178 /// @notice Set token properties value.179 /// @dev Throws error if `msg.sender` has no permission to edit the property.180 /// @param tokenId ID of the token.181 /// @param properties settable properties182 #[weight(<SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]183 fn set_properties(184 &mut self,185 caller: Caller,186 token_id: U256,187 properties: Vec<eth::Property>,188 ) -> Result<()> {189 let caller = T::CrossAccountId::from_eth(caller);190 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;191192 let nesting_budget = self193 .recorder194 .weight_calls_budget(<StructureWeight<T>>::find_parent());195196 let properties = properties197 .into_iter()198 .map(eth::Property::try_into)199 .collect::<Result<Vec<_>>>()?;200201 <Pallet<T>>::set_token_properties(202 self,203 &caller,204 TokenId(token_id),205 properties.into_iter(),206 &nesting_budget,207 )208 .map_err(dispatch_to_evm::<T>)209 }210211 /// @notice Delete token property value.212 /// @dev Throws error if `msg.sender` has no permission to edit the property.213 /// @param tokenId ID of the token.214 /// @param key Property key.215 #[solidity(hide)]216 #[weight(<SelfWeightOf<T>>::delete_token_properties(1))]217 fn delete_property(&mut self, token_id: U256, caller: Caller, key: String) -> Result<()> {218 let caller = T::CrossAccountId::from_eth(caller);219 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;220 let key = <Vec<u8>>::from(key)221 .try_into()222 .map_err(|_| "key too long")?;223224 let nesting_budget = self225 .recorder226 .weight_calls_budget(<StructureWeight<T>>::find_parent());227228 <Pallet<T>>::delete_token_property(self, &caller, TokenId(token_id), key, &nesting_budget)229 .map_err(dispatch_to_evm::<T>)230 }231232 /// @notice Delete token properties value.233 /// @dev Throws error if `msg.sender` has no permission to edit the property.234 /// @param tokenId ID of the token.235 /// @param keys Properties key.236 #[weight(<SelfWeightOf<T>>::delete_token_properties(keys.len() as u32))]237 fn delete_properties(238 &mut self,239 token_id: U256,240 caller: Caller,241 keys: Vec<String>,242 ) -> Result<()> {243 let caller = T::CrossAccountId::from_eth(caller);244 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;245 let keys = keys246 .into_iter()247 .map(|k| Ok(<Vec<u8>>::from(k).try_into().map_err(|_| "key too long")?))248 .collect::<Result<Vec<_>>>()?;249250 let nesting_budget = self251 .recorder252 .weight_calls_budget(<StructureWeight<T>>::find_parent());253254 <Pallet<T>>::delete_token_properties(255 self,256 &caller,257 TokenId(token_id),258 keys.into_iter(),259 &nesting_budget,260 )261 .map_err(dispatch_to_evm::<T>)262 }263264 /// @notice Get token property value.265 /// @dev Throws error if key not found266 /// @param tokenId ID of the token.267 /// @param key Property key.268 /// @return Property value bytes269 fn property(&self, token_id: U256, key: String) -> Result<Bytes> {270 let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;271 let key = <Vec<u8>>::from(key)272 .try_into()273 .map_err(|_| "key too long")?;274275 let props = <TokenProperties<T>>::get((self.id, token_id));276 let prop = props.get(&key).ok_or("key not found")?;277278 Ok(prop.to_vec().into())279 }280}281282#[derive(ToLog)]283pub enum ERC721Events {284 /// @dev This emits when ownership of any NFT changes by any mechanism.285 /// This event emits when NFTs are created (`from` == 0) and destroyed286 /// (`to` == 0). Exception: during contract creation, any number of NFTs287 /// may be created and assigned without emitting Transfer. At the time of288 /// any transfer, the approved address for that NFT (if any) is reset to none.289 Transfer {290 #[indexed]291 from: Address,292 #[indexed]293 to: Address,294 #[indexed]295 token_id: U256,296 },297 /// @dev This emits when the approved address for an NFT is changed or298 /// reaffirmed. The zero address indicates there is no approved address.299 /// When a Transfer event emits, this also indicates that the approved300 /// address for that NFT (if any) is reset to none.301 Approval {302 #[indexed]303 owner: Address,304 #[indexed]305 approved: Address,306 #[indexed]307 token_id: U256,308 },309 /// @dev This emits when an operator is enabled or disabled for an owner.310 /// The operator can manage all NFTs of the owner.311 #[allow(dead_code)]312 ApprovalForAll {313 #[indexed]314 owner: Address,315 #[indexed]316 operator: Address,317 approved: bool,318 },319}320321/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension322/// @dev See https://eips.ethereum.org/EIPS/eip-721323#[solidity_interface(name = ERC721Metadata, expect_selector = 0x5b5e139f, enum(derive(PreDispatch)), enum_attr(weight))]324impl<T: Config> NonfungibleHandle<T>325where326 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,327{328 /// @notice A descriptive name for a collection of NFTs in this contract329 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`330 #[solidity(hide, rename_selector = "name")]331 fn name_proxy(&self) -> String {332 self.name()333 }334335 /// @notice An abbreviated name for NFTs in this contract336 /// @dev real implementation of this function lies in `ERC721UniqueExtensions`337 #[solidity(hide, rename_selector = "symbol")]338 fn symbol_proxy(&self) -> String {339 self.symbol()340 }341342 /// @notice A distinct Uniform Resource Identifier (URI) for a given asset.343 ///344 /// @dev If the token has a `url` property and it is not empty, it is returned.345 /// Else If the collection does not have a property with key `schemaName` or its value is not equal to `ERC721Metadata`, it return an error `tokenURI not set`.346 /// If the collection property `baseURI` is empty or absent, return "" (empty string)347 /// otherwise, if token property `suffix` present and is non-empty, return concatenation of baseURI and suffix348 /// otherwise, return concatenation of `baseURI` and stringified token id (decimal stringifying, without paddings).349 ///350 /// @return token's const_metadata351 #[solidity(rename_selector = "tokenURI")]352 fn token_uri(&self, token_id: U256) -> Result<String> {353 let token_id_u32: u32 = token_id.try_into().map_err(|_| "token id overflow")?;354355 match get_token_property(self, token_id_u32, &key::url()).as_deref() {356 Err(_) | Ok("") => (),357 Ok(url) => {358 return Ok(url.into());359 }360 };361362 let base_uri =363 pallet_common::Pallet::<T>::get_collection_property(self.id, &key::base_uri())364 .map(BoundedVec::into_inner)365 .map(String::from_utf8)366 .transpose()367 .map_err(|e| {368 Error::Revert(alloc::format!(369 "Can not convert value \"baseURI\" to string with error \"{e}\""370 ))371 })?;372373 let base_uri = match base_uri.as_deref() {374 None | Some("") => {375 return Ok("".into());376 }377 Some(base_uri) => base_uri.into(),378 };379380 Ok(381 match get_token_property(self, token_id_u32, &key::suffix()).as_deref() {382 Err(_) | Ok("") => base_uri,383 Ok(suffix) => base_uri + suffix,384 },385 )386 }387}388389/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension390/// @dev See https://eips.ethereum.org/EIPS/eip-721391#[solidity_interface(name = ERC721Enumerable, expect_selector = 0x780e9d63, enum(derive(PreDispatch)), enum_attr(weight))]392impl<T: Config> NonfungibleHandle<T> {393 /// @notice Enumerate valid NFTs394 /// @param index A counter less than `totalSupply()`395 /// @return The token identifier for the `index`th NFT,396 /// (sort order not specified)397 fn token_by_index(&self, index: U256) -> U256 {398 index399 }400401 /// @dev Not implemented402 fn token_of_owner_by_index(&self, _owner: Address, _index: U256) -> Result<U256> {403 // TODO: Not implemetable404 Err("not implemented".into())405 }406407 /// @notice Count NFTs tracked by this contract408 /// @return A count of valid NFTs tracked by this contract, where each one of409 /// them has an assigned and queryable owner not equal to the zero address410 fn total_supply(&self) -> Result<U256> {411 self.consume_store_reads(1)?;412 Ok(<Pallet<T>>::total_supply(self).into())413 }414}415416/// @title ERC-721 Non-Fungible Token Standard417/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md418#[solidity_interface(name = ERC721, events(ERC721Events), enum(derive(PreDispatch)), enum_attr(weight), expect_selector = 0x80ac58cd)]419impl<T: Config> NonfungibleHandle<T> {420 /// @notice Count all NFTs assigned to an owner421 /// @dev NFTs assigned to the zero address are considered invalid, and this422 /// function throws for queries about the zero address.423 /// @param owner An address for whom to query the balance424 /// @return The number of NFTs owned by `owner`, possibly zero425 fn balance_of(&self, owner: Address) -> Result<U256> {426 self.consume_store_reads(1)?;427 let owner = T::CrossAccountId::from_eth(owner);428 let balance = <AccountBalance<T>>::get((self.id, owner));429 Ok(balance.into())430 }431 /// @notice Find the owner of an NFT432 /// @dev NFTs assigned to zero address are considered invalid, and queries433 /// about them do throw.434 /// @param tokenId The identifier for an NFT435 /// @return The address of the owner of the NFT436 fn owner_of(&self, token_id: U256) -> Result<Address> {437 self.consume_store_reads(1)?;438 let token: TokenId = token_id.try_into()?;439 Ok(*<TokenData<T>>::get((self.id, token))440 .ok_or("token not found")?441 .owner442 .as_eth())443 }444 /// @dev Not implemented445 #[solidity(rename_selector = "safeTransferFrom")]446 fn safe_transfer_from_with_data(447 &mut self,448 _from: Address,449 _to: Address,450 _token_id: U256,451 _data: Bytes,452 ) -> Result<()> {453 // TODO: Not implemetable454 Err("not implemented".into())455 }456 /// @dev Not implemented457 fn safe_transfer_from(&mut self, _from: Address, _to: Address, _token_id: U256) -> Result<()> {458 // TODO: Not implemetable459 Err("not implemented".into())460 }461462 /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE463 /// TO CONFIRM THAT `to` IS CAPABLE OF RECEIVING NFTS OR ELSE464 /// THEY MAY BE PERMANENTLY LOST465 /// @dev Throws unless `msg.sender` is the current owner or an authorized466 /// operator for this NFT. Throws if `from` is not the current owner. Throws467 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.468 /// @param from The current owner of the NFT469 /// @param to The new owner470 /// @param tokenId The NFT to transfer471 #[weight(<CommonWeights<T>>::transfer_from())]472 fn transfer_from(473 &mut self,474 caller: Caller,475 from: Address,476 to: Address,477 token_id: U256,478 ) -> Result<()> {479 let caller = T::CrossAccountId::from_eth(caller);480 let from = T::CrossAccountId::from_eth(from);481 let to = T::CrossAccountId::from_eth(to);482 let token = token_id.try_into()?;483 let budget = self484 .recorder485 .weight_calls_budget(<StructureWeight<T>>::find_parent());486487 <Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)488 .map_err(|e| dispatch_to_evm::<T>(e.error))?;489 Ok(())490 }491492 /// @notice Set or reaffirm the approved address for an NFT493 /// @dev The zero address indicates there is no approved address.494 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized495 /// operator of the current owner.496 /// @param approved The new approved NFT controller497 /// @param tokenId The NFT to approve498 #[weight(<SelfWeightOf<T>>::approve())]499 fn approve(&mut self, caller: Caller, approved: Address, token_id: U256) -> Result<()> {500 let caller = T::CrossAccountId::from_eth(caller);501 let approved = T::CrossAccountId::from_eth(approved);502 let token = token_id.try_into()?;503504 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))505 .map_err(dispatch_to_evm::<T>)?;506 Ok(())507 }508509 /// @notice Sets or unsets the approval of a given operator.510 /// The `operator` is allowed to transfer all tokens of the `caller` on their behalf.511 /// @param operator Operator512 /// @param approved Should operator status be granted or revoked?513 #[weight(<SelfWeightOf<T>>::set_allowance_for_all())]514 fn set_approval_for_all(515 &mut self,516 caller: Caller,517 operator: Address,518 approved: bool,519 ) -> Result<()> {520 let caller = T::CrossAccountId::from_eth(caller);521 let operator = T::CrossAccountId::from_eth(operator);522523 <Pallet<T>>::set_allowance_for_all(self, &caller, &operator, approved)524 .map_err(dispatch_to_evm::<T>)?;525 Ok(())526 }527528 /// @notice Get the approved address for a single NFT529 /// @dev Throws if `tokenId` is not a valid NFT530 /// @param tokenId The NFT to find the approved address for531 /// @return The approved address for this NFT, or the zero address if there is none532 fn get_approved(&self, token_id: U256) -> Result<Address> {533 let token_id = token_id.try_into()?;534 let operator = <Pallet<T>>::get_allowance(self, token_id).map_err(dispatch_to_evm::<T>)?;535 Ok(if let Some(operator) = operator {536 *operator.as_eth()537 } else {538 Address::zero()539 })540 }541542 /// @notice Tells whether the given `owner` approves the `operator`.543 #[weight(<SelfWeightOf<T>>::allowance_for_all())]544 fn is_approved_for_all(&self, owner: Address, operator: Address) -> Result<bool> {545 let owner = T::CrossAccountId::from_eth(owner);546 let operator = T::CrossAccountId::from_eth(operator);547548 Ok(<Pallet<T>>::allowance_for_all(self, &owner, &operator))549 }550}551552/// @title ERC721 Token that can be irreversibly burned (destroyed).553#[solidity_interface(name = ERC721Burnable, enum(derive(PreDispatch)), enum_attr(weight))]554impl<T: Config> NonfungibleHandle<T> {555 /// @notice Burns a specific ERC721 token.556 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized557 /// operator of the current owner.558 /// @param tokenId The NFT to approve559 #[weight(<SelfWeightOf<T>>::burn_item())]560 fn burn(&mut self, caller: Caller, token_id: U256) -> Result<()> {561 let caller = T::CrossAccountId::from_eth(caller);562 let token = token_id.try_into()?;563564 <Pallet<T>>::burn(self, &caller, token).map_err(dispatch_to_evm::<T>)?;565 Ok(())566 }567}568569/// @title ERC721 minting logic.570#[solidity_interface(name = ERC721UniqueMintable, enum(derive(PreDispatch)), enum_attr(weight))]571impl<T: Config> NonfungibleHandle<T> {572 /// @notice Function to mint a token.573 /// @param to The new owner574 /// @return uint256 The id of the newly minted token575 #[weight(<SelfWeightOf<T>>::create_item())]576 fn mint(&mut self, caller: Caller, to: Address) -> Result<U256> {577 let token_id: U256 = <TokensMinted<T>>::get(self.id)578 .checked_add(1)579 .ok_or("item id overflow")?580 .into();581 self.mint_check_id(caller, to, token_id)?;582 Ok(token_id)583 }584585 /// @notice Function to mint a token.586 /// @dev `tokenId` should be obtained with `nextTokenId` method,587 /// unlike standard, you can't specify it manually588 /// @param to The new owner589 /// @param tokenId ID of the minted NFT590 #[solidity(hide, rename_selector = "mint")]591 #[weight(<SelfWeightOf<T>>::create_item())]592 fn mint_check_id(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<bool> {593 let caller = T::CrossAccountId::from_eth(caller);594 let to = T::CrossAccountId::from_eth(to);595 let token_id: u32 = token_id.try_into()?;596 let budget = self597 .recorder598 .weight_calls_budget(<StructureWeight<T>>::find_parent());599600 if <TokensMinted<T>>::get(self.id)601 .checked_add(1)602 .ok_or("item id overflow")?603 != token_id604 {605 return Err("item id should be next".into());606 }607608 <Pallet<T>>::create_item(609 self,610 &caller,611 CreateItemData::<T> {612 properties: BoundedVec::default(),613 owner: to,614 },615 &budget,616 )617 .map_err(dispatch_to_evm::<T>)?;618619 Ok(true)620 }621622 /// @notice Function to mint token with the given tokenUri.623 /// @param to The new owner624 /// @param tokenUri Token URI that would be stored in the NFT properties625 /// @return uint256 The id of the newly minted token626 #[solidity(rename_selector = "mintWithTokenURI")]627 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]628 fn mint_with_token_uri(629 &mut self,630 caller: Caller,631 to: Address,632 token_uri: String,633 ) -> Result<U256> {634 let token_id: U256 = <TokensMinted<T>>::get(self.id)635 .checked_add(1)636 .ok_or("item id overflow")?637 .into();638 self.mint_with_token_uri_check_id(caller, to, token_id, token_uri)?;639 Ok(token_id)640 }641642 /// @notice Function to mint token with the given tokenUri.643 /// @dev `tokenId` should be obtained with `nextTokenId` method,644 /// unlike standard, you can't specify it manually645 /// @param to The new owner646 /// @param tokenId ID of the minted NFT647 /// @param tokenUri Token URI that would be stored in the NFT properties648 #[solidity(hide, rename_selector = "mintWithTokenURI")]649 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(1))]650 fn mint_with_token_uri_check_id(651 &mut self,652 caller: Caller,653 to: Address,654 token_id: U256,655 token_uri: String,656 ) -> Result<bool> {657 let key = key::url();658 let permission = get_token_permission::<T>(self.id, &key)?;659 if !permission.collection_admin {660 return Err("Operation is not allowed".into());661 }662663 let caller = T::CrossAccountId::from_eth(caller);664 let to = T::CrossAccountId::from_eth(to);665 let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;666 let budget = self667 .recorder668 .weight_calls_budget(<StructureWeight<T>>::find_parent());669670 if <TokensMinted<T>>::get(self.id)671 .checked_add(1)672 .ok_or("item id overflow")?673 != token_id674 {675 return Err("item id should be next".into());676 }677678 let mut properties = CollectionPropertiesVec::default();679 properties680 .try_push(Property {681 key,682 value: token_uri683 .into_bytes()684 .try_into()685 .map_err(|_| "token uri is too long")?,686 })687 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;688689 <Pallet<T>>::create_item(690 self,691 &caller,692 CreateItemData::<T> {693 properties,694 owner: to,695 },696 &budget,697 )698 .map_err(dispatch_to_evm::<T>)?;699 Ok(true)700 }701}702703fn get_token_property<T: Config>(704 collection: &CollectionHandle<T>,705 token_id: u32,706 key: &up_data_structs::PropertyKey,707) -> Result<String> {708 collection.consume_store_reads(1)?;709 let properties = <TokenProperties<T>>::try_get((collection.id, token_id))710 .map_err(|_| Error::Revert("Token properties not found".into()))?;711 if let Some(property) = properties.get(key) {712 return Ok(String::from_utf8_lossy(property).into());713 }714715 Err("Property tokenURI not found".into())716}717718fn get_token_permission<T: Config>(719 collection_id: CollectionId,720 key: &PropertyKey,721) -> Result<PropertyPermission> {722 let token_property_permissions = CollectionPropertyPermissions::<T>::try_get(collection_id)723 .map_err(|_| Error::Revert("No permissions for collection".into()))?;724 let a = token_property_permissions725 .get(key)726 .map(Clone::clone)727 .ok_or_else(|| {728 let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();729 Error::Revert(alloc::format!("No permission for key {key}"))730 })?;731 Ok(a)732}733734/// @title Unique extensions for ERC721.735#[solidity_interface(name = ERC721UniqueExtensions, enum(derive(PreDispatch)), enum_attr(weight))]736impl<T: Config> NonfungibleHandle<T>737where738 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,739{740 /// @notice A descriptive name for a collection of NFTs in this contract741 fn name(&self) -> String {742 decode_utf16(self.name.iter().copied())743 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))744 .collect::<String>()745 }746747 /// @notice An abbreviated name for NFTs in this contract748 fn symbol(&self) -> String {749 String::from_utf8_lossy(&self.token_prefix).into()750 }751752 /// @notice A description for the collection.753 fn description(&self) -> String {754 decode_utf16(self.description.iter().copied())755 .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))756 .collect::<String>()757 }758759 /// Returns the owner (in cross format) of the token.760 ///761 /// @param tokenId Id for the token.762 #[solidity(hide)]763 fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {764 Self::owner_of_cross(self, token_id)765 }766767 /// Returns the owner (in cross format) of the token.768 ///769 /// @param tokenId Id for the token.770 fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {771 Self::token_owner(self, token_id.try_into()?)772 .map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))773 .map_err(|_| Error::Revert("token not found".into()))774 }775776 /// @notice Count all NFTs assigned to an owner777 /// @param owner An cross address for whom to query the balance778 /// @return The number of NFTs owned by `owner`, possibly zero779 fn balance_of_cross(&self, owner: eth::CrossAddress) -> Result<U256> {780 self.consume_store_reads(1)?;781 let balance = <AccountBalance<T>>::get((self.id, owner.into_sub_cross_account::<T>()?));782 Ok(balance.into())783 }784785 /// Returns the token properties.786 ///787 /// @param tokenId Id for the token.788 /// @param keys Properties keys. Empty keys for all propertyes.789 /// @return Vector of properties key/value pairs.790 fn properties(&self, token_id: U256, keys: Vec<String>) -> Result<Vec<eth::Property>> {791 let keys = keys792 .into_iter()793 .map(|key| {794 <Vec<u8>>::from(key)795 .try_into()796 .map_err(|_| Error::Revert("key too large".into()))797 })798 .collect::<Result<Vec<_>>>()?;799800 <Self as CommonCollectionOperations<T>>::token_properties(801 self,802 token_id.try_into()?,803 if keys.is_empty() { None } else { Some(keys) },804 )805 .into_iter()806 .map(eth::Property::try_from)807 .collect::<Result<Vec<_>>>()808 }809810 /// @notice Set or reaffirm the approved address for an NFT811 /// @dev The zero address indicates there is no approved address.812 /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized813 /// operator of the current owner.814 /// @param approved The new substrate address approved NFT controller815 /// @param tokenId The NFT to approve816 #[weight(<SelfWeightOf<T>>::approve())]817 fn approve_cross(818 &mut self,819 caller: Caller,820 approved: eth::CrossAddress,821 token_id: U256,822 ) -> Result<()> {823 let caller = T::CrossAccountId::from_eth(caller);824 let approved = approved.into_sub_cross_account::<T>()?;825 let token = token_id.try_into()?;826827 <Pallet<T>>::set_allowance(self, &caller, token, Some(&approved))828 .map_err(dispatch_to_evm::<T>)?;829 Ok(())830 }831832 /// @notice Transfer ownership of an NFT833 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`834 /// is the zero address. Throws if `tokenId` is not a valid NFT.835 /// @param to The new owner836 /// @param tokenId The NFT to transfer837 #[weight(<CommonWeights<T>>::transfer())]838 fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {839 let caller = T::CrossAccountId::from_eth(caller);840 let to = T::CrossAccountId::from_eth(to);841 let token = token_id.try_into()?;842 let budget = self843 .recorder844 .weight_calls_budget(<StructureWeight<T>>::find_parent());845846 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)847 .map_err(|e| dispatch_to_evm::<T>(e.error))?;848 Ok(())849 }850851 /// @notice Transfer ownership of an NFT852 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`853 /// is the zero address. Throws if `tokenId` is not a valid NFT.854 /// @param to The new owner855 /// @param tokenId The NFT to transfer856 #[weight(<CommonWeights<T>>::transfer())]857 fn transfer_cross(858 &mut self,859 caller: Caller,860 to: eth::CrossAddress,861 token_id: U256,862 ) -> Result<()> {863 let caller = T::CrossAccountId::from_eth(caller);864 let to = to.into_sub_cross_account::<T>()?;865 let token = token_id.try_into()?;866 let budget = self867 .recorder868 .weight_calls_budget(<StructureWeight<T>>::find_parent());869870 <Pallet<T>>::transfer(self, &caller, &to, token, &budget)871 .map_err(|e| dispatch_to_evm::<T>(e.error))?;872 Ok(())873 }874875 /// @notice Transfer ownership of an NFT from cross account address to cross account address876 /// @dev Throws unless `msg.sender` is the current owner. Throws if `to`877 /// is the zero address. Throws if `tokenId` is not a valid NFT.878 /// @param from Cross acccount address of current owner879 /// @param to Cross acccount address of new owner880 /// @param tokenId The NFT to transfer881 #[weight(<CommonWeights<T>>::transfer_from())]882 fn transfer_from_cross(883 &mut self,884 caller: Caller,885 from: eth::CrossAddress,886 to: eth::CrossAddress,887 token_id: U256,888 ) -> Result<()> {889 let caller = T::CrossAccountId::from_eth(caller);890 let from = from.into_sub_cross_account::<T>()?;891 let to = to.into_sub_cross_account::<T>()?;892 let token_id = token_id.try_into()?;893 let budget = self894 .recorder895 .weight_calls_budget(<StructureWeight<T>>::find_parent());896 Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)897 .map_err(|e| dispatch_to_evm::<T>(e.error))?;898 Ok(())899 }900901 /// @notice Burns a specific ERC721 token.902 /// @dev Throws unless `msg.sender` is the current owner or an authorized903 /// operator for this NFT. Throws if `from` is not the current owner. Throws904 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.905 /// @param from The current owner of the NFT906 /// @param tokenId The NFT to transfer907 #[solidity(hide)]908 #[weight(<SelfWeightOf<T>>::burn_from())]909 fn burn_from(&mut self, caller: Caller, from: Address, token_id: U256) -> Result<()> {910 let caller = T::CrossAccountId::from_eth(caller);911 let from = T::CrossAccountId::from_eth(from);912 let token = token_id.try_into()?;913 let budget = self914 .recorder915 .weight_calls_budget(<StructureWeight<T>>::find_parent());916917 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)918 .map_err(dispatch_to_evm::<T>)?;919 Ok(())920 }921922 /// @notice Burns a specific ERC721 token.923 /// @dev Throws unless `msg.sender` is the current owner or an authorized924 /// operator for this NFT. Throws if `from` is not the current owner. Throws925 /// if `to` is the zero address. Throws if `tokenId` is not a valid NFT.926 /// @param from The current owner of the NFT927 /// @param tokenId The NFT to transfer928 #[weight(<SelfWeightOf<T>>::burn_from())]929 fn burn_from_cross(930 &mut self,931 caller: Caller,932 from: eth::CrossAddress,933 token_id: U256,934 ) -> Result<()> {935 let caller = T::CrossAccountId::from_eth(caller);936 let from = from.into_sub_cross_account::<T>()?;937 let token = token_id.try_into()?;938 let budget = self939 .recorder940 .weight_calls_budget(<StructureWeight<T>>::find_parent());941942 <Pallet<T>>::burn_from(self, &caller, &from, token, &budget)943 .map_err(dispatch_to_evm::<T>)?;944 Ok(())945 }946947 /// @notice Returns next free NFT ID.948 fn next_token_id(&self) -> Result<U256> {949 self.consume_store_reads(1)?;950 Ok(<Pallet<T>>::next_token_id(self)951 .map_err(dispatch_to_evm::<T>)?952 .into())953 }954955 /// @notice Function to mint multiple tokens.956 /// @dev `tokenIds` should be an array of consecutive numbers and first number957 /// should be obtained with `nextTokenId` method958 /// @param to The new owner959 /// @param tokenIds IDs of the minted NFTs960 #[solidity(hide)]961 #[weight(<SelfWeightOf<T>>::create_multiple_items(token_ids.len() as u32))]962 fn mint_bulk(&mut self, caller: Caller, to: Address, token_ids: Vec<U256>) -> Result<bool> {963 let caller = T::CrossAccountId::from_eth(caller);964 let to = T::CrossAccountId::from_eth(to);965 let mut expected_index = <TokensMinted<T>>::get(self.id)966 .checked_add(1)967 .ok_or("item id overflow")?;968 let budget = self969 .recorder970 .weight_calls_budget(<StructureWeight<T>>::find_parent());971972 let total_tokens = token_ids.len();973 for id in token_ids.into_iter() {974 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;975 if id != expected_index {976 return Err("item id should be next".into());977 }978 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;979 }980 let data = (0..total_tokens)981 .map(|_| CreateItemData::<T> {982 properties: BoundedVec::default(),983 owner: to.clone(),984 })985 .collect();986987 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)988 .map_err(dispatch_to_evm::<T>)?;989 Ok(true)990 }991992 /// @notice Function to mint a token.993 /// @param data Array of pairs of token owner and token's properties for minted token994 #[weight(<SelfWeightOf<T>>::create_multiple_items(data.len() as u32) + <SelfWeightOf<T>>::set_token_properties(data.len() as u32))]995 fn mint_bulk_cross(&mut self, caller: Caller, data: Vec<MintTokenData>) -> Result<bool> {996 let caller = T::CrossAccountId::from_eth(caller);997 let budget = self998 .recorder999 .weight_calls_budget(<StructureWeight<T>>::find_parent());10001001 let mut create_nft_data = Vec::with_capacity(data.len());1002 for MintTokenData { owner, properties } in data {1003 let owner = owner.into_sub_cross_account::<T>()?;1004 create_nft_data.push(CreateItemData::<T> {1005 properties: properties1006 .into_iter()1007 .map(|property| property.try_into())1008 .collect::<Result<Vec<_>>>()?1009 .try_into()1010 .map_err(|_| "too many properties")?,1011 owner,1012 });1013 }10141015 <Pallet<T>>::create_multiple_items(self, &caller, create_nft_data, &budget)1016 .map_err(dispatch_to_evm::<T>)?;1017 Ok(true)1018 }10191020 /// @notice Function to mint multiple tokens with the given tokenUris.1021 /// @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive1022 /// numbers and first number should be obtained with `nextTokenId` method1023 /// @param to The new owner1024 /// @param tokens array of pairs of token ID and token URI for minted tokens1025 #[solidity(hide, rename_selector = "mintBulkWithTokenURI")]1026 #[weight(<SelfWeightOf<T>>::create_multiple_items(tokens.len() as u32) + <SelfWeightOf<T>>::set_token_properties(tokens.len() as u32))]1027 fn mint_bulk_with_token_uri(1028 &mut self,1029 caller: Caller,1030 to: Address,1031 tokens: Vec<TokenUri>,1032 ) -> Result<bool> {1033 let key = key::url();1034 let caller = T::CrossAccountId::from_eth(caller);1035 let to = T::CrossAccountId::from_eth(to);1036 let mut expected_index = <TokensMinted<T>>::get(self.id)1037 .checked_add(1)1038 .ok_or("item id overflow")?;1039 let budget = self1040 .recorder1041 .weight_calls_budget(<StructureWeight<T>>::find_parent());10421043 let mut data = Vec::with_capacity(tokens.len());1044 for TokenUri { id, uri } in tokens {1045 let id: u32 = id.try_into().map_err(|_| "token id overflow")?;1046 if id != expected_index {1047 return Err("item id should be next".into());1048 }1049 expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;10501051 let mut properties = CollectionPropertiesVec::default();1052 properties1053 .try_push(Property {1054 key: key.clone(),1055 value: uri1056 .into_bytes()1057 .try_into()1058 .map_err(|_| "token uri is too long")?,1059 })1060 .map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;10611062 data.push(CreateItemData::<T> {1063 properties,1064 owner: to.clone(),1065 });1066 }10671068 <Pallet<T>>::create_multiple_items(self, &caller, data, &budget)1069 .map_err(dispatch_to_evm::<T>)?;1070 Ok(true)1071 }10721073 /// @notice Function to mint a token.1074 /// @param to The new owner crossAccountId1075 /// @param properties Properties of minted token1076 /// @return uint256 The id of the newly minted token1077 #[weight(<SelfWeightOf<T>>::create_item() + <SelfWeightOf<T>>::set_token_properties(properties.len() as u32))]1078 fn mint_cross(1079 &mut self,1080 caller: Caller,1081 to: eth::CrossAddress,1082 properties: Vec<eth::Property>,1083 ) -> Result<U256> {1084 let token_id = <TokensMinted<T>>::get(self.id)1085 .checked_add(1)1086 .ok_or("item id overflow")?;10871088 let to = to.into_sub_cross_account::<T>()?;10891090 let properties = properties1091 .into_iter()1092 .map(eth::Property::try_into)1093 .collect::<Result<Vec<_>>>()?1094 .try_into()1095 .map_err(|_| Error::Revert("too many properties".to_string()))?;10961097 let caller = T::CrossAccountId::from_eth(caller);10981099 let budget = self1100 .recorder1101 .weight_calls_budget(<StructureWeight<T>>::find_parent());11021103 <Pallet<T>>::create_item(1104 self,1105 &caller,1106 CreateItemData::<T> {1107 properties,1108 owner: to,1109 },1110 &budget,1111 )1112 .map_err(dispatch_to_evm::<T>)?;11131114 Ok(token_id.into())1115 }11161117 /// @notice Returns collection helper contract address1118 fn collection_helper_address(&self) -> Address {1119 T::ContractAddress::get()1120 }1121}11221123#[solidity_interface(1124 name = UniqueNFT,1125 is(1126 ERC721,1127 ERC721Enumerable,1128 ERC721UniqueExtensions,1129 ERC721UniqueMintable,1130 ERC721Burnable,1131 ERC721Metadata(if(this.flags.erc721metadata)),1132 Collection(via(common_mut returns CollectionHandle<T>)),1133 TokenProperties,1134 ),1135 enum(derive(PreDispatch)),1136)]1137impl<T: Config> NonfungibleHandle<T> where T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]> {}11381139// Not a tests, but code generators1140generate_stubgen!(gen_impl, UniqueNFTCall<()>, true);1141generate_stubgen!(gen_iface, UniqueNFTCall<()>, false);11421143impl<T: Config> CommonEvmHandler for NonfungibleHandle<T>1144where1145 T::AccountId: From<[u8; 32]> + AsRef<[u8; 32]>,1146{1147 const CODE: &'static [u8] = include_bytes!("./stubs/UniqueNFT.raw");11481149 fn call(self, handle: &mut impl PrecompileHandle) -> Option<PrecompileResult> {1150 call::<T, UniqueNFTCall<T>, _, _>(handle, self)1151 }1152}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -109,7 +109,7 @@
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
- weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info, SetPropertyMode,
+ weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -598,58 +598,16 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let mut is_token_owner = pallet_common::LazyValue::new(|| {
- if let SetPropertyMode::NewToken {
- mint_target_is_sender,
- } = mode
- {
- return Ok(mint_target_is_sender);
- }
-
- let is_owned = <PalletStructure<T>>::check_indirectly_owned(
- sender.clone(),
- collection.id,
- token_id,
- None,
- nesting_budget,
- )?;
-
- Ok(is_owned)
- });
-
- let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });
-
- let mut is_token_exist = pallet_common::LazyValue::new(|| {
- if is_new_token {
- debug_assert!(Self::token_exists(collection, token_id));
- true
- } else {
- Self::token_exists(collection, token_id)
- }
- });
-
- let stored_properties = if is_new_token {
- debug_assert!(!<TokenProperties<T>>::contains_key((
- collection.id,
- token_id
- )));
- TokenPropertiesT::new()
- } else {
- <TokenProperties<T>>::get((collection.id, token_id))
- };
+ let mut property_writer =
+ pallet_common::property_writer_for_existing_token(collection, sender);
- <PalletCommon<T>>::modify_token_properties(
- collection,
+ property_writer.write_token_properties(
sender,
token_id,
- &mut is_token_exist,
properties_updates,
- stored_properties,
- &mut is_token_owner,
- |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ nesting_budget,
erc::ERC721TokenEvent::TokenChanged {
token_id: token_id.into(),
}
@@ -680,7 +638,6 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties: impl Iterator<Item = Property>,
- mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::modify_token_properties(
@@ -688,7 +645,6 @@
sender,
token_id,
properties.map(|p| (p.key, Some(p.value))),
- mode,
nesting_budget,
)
}
@@ -710,7 +666,6 @@
sender,
token_id,
[property].into_iter(),
- SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -732,7 +687,6 @@
sender,
token_id,
property_keys.into_iter().map(|key| (key, None)),
- SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -994,6 +948,8 @@
// =========
+ let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);
+
with_transaction(|| {
for (i, data) in data.iter().enumerate() {
let token = first_token + i as u32 + 1;
@@ -1006,21 +962,22 @@
},
);
+ let token = TokenId(token);
+
<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
&data.owner,
collection.id,
- TokenId(token),
+ token,
);
- if let Err(e) = Self::set_token_properties(
- collection,
- sender,
- TokenId(token),
+ if let Err(e) = property_writer.write_token_properties(
+ sender.conv_eq(&data.owner),
+ token,
data.properties.clone().into_iter(),
- SetPropertyMode::NewToken {
- mint_target_is_sender: sender.conv_eq(&data.owner),
- },
- nesting_budget,
+ erc::ERC721TokenEvent::TokenChanged {
+ token_id: token.into(),
+ }
+ .to_log(T::ContractAddress::get()),
) {
return TransactionOutcome::Rollback(Err(e));
}
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -22,7 +22,9 @@
use frame_benchmarking::{benchmarks, account};
use pallet_common::{
bench_init,
- benchmarking::{create_collection_raw, property_key, property_value},
+ benchmarking::{
+ create_collection_raw, property_key, property_value, load_is_admin_and_property_permissions,
+ },
};
use sp_std::prelude::*;
use up_data_structs::{
@@ -255,14 +257,15 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?}
+ }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?}
- reset_token_properties {
+ init_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub;
};
+
let perms = (0..b).map(|k| PropertyKeyPermission {
key: property_key(k as usize),
permission: PropertyPermission {
@@ -277,8 +280,26 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- }: {<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::NewToken { mint_target_is_sender: true }, &Unlimited)?}
+ let (is_collection_admin, property_permissions) = load_is_admin_and_property_permissions(&collection, &owner);
+ }: {
+ let mut property_writer = pallet_common::collection_info_loaded_property_writer(
+ &collection,
+ is_collection_admin,
+ property_permissions,
+ );
+
+ property_writer.write_token_properties(
+ true,
+ item,
+ props.into_iter(),
+ crate::erc::ERC721TokenEvent::TokenChanged {
+ token_id: item.into(),
+ }
+ .to_log(T::ContractAddress::get()),
+ )?
+ }
+
delete_token_properties {
let b in 0..MAX_PROPERTIES_PER_ITEM;
bench_init!{
@@ -299,7 +320,7 @@
value: property_value(),
}).collect::<Vec<_>>();
let item = create_max_item(&collection, &owner, [(owner.clone(), 200)])?;
- <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), SetPropertyMode::ExistingToken, &Unlimited)?;
+ <Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), &Unlimited)?;
let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -20,20 +20,20 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{
CollectionId, TokenId, CreateItemExData, budget::Budget, Property, PropertyKey, PropertyValue,
- PropertyKeyPermission, CollectionPropertiesVec, CreateRefungibleExMultipleOwners,
- CreateRefungibleExSingleOwner, TokenOwnerError,
+ PropertyKeyPermission, CreateRefungibleExMultipleOwners, CreateRefungibleExSingleOwner,
+ TokenOwnerError,
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _,
+ weights::WeightInfo as _, init_token_properties_delta,
};
-use pallet_structure::Error as StructureError;
+use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use sp_runtime::{DispatchError};
use sp_std::{vec::Vec, vec};
use crate::{
AccountBalance, Allowance, Balance, Config, Error, Owned, Pallet, RefungibleHandle,
- SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData,
+ SelfWeightOf, weights::WeightInfo, TokensMinted, TotalSupply, CreateItemData, TokenProperties,
};
macro_rules! max_weight_of {
@@ -45,26 +45,19 @@
};
}
-fn properties_weight<T: Config>(properties: &CollectionPropertiesVec) -> Weight {
- if properties.len() > 0 {
- <SelfWeightOf<T>>::reset_token_properties(properties.len() as u32)
- } else {
- Weight::zero()
- }
-}
-
pub struct CommonWeights<T: Config>(PhantomData<T>);
impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {
fn create_multiple_items(data: &[up_data_structs::CreateItemData]) -> Weight {
<SelfWeightOf<T>>::create_multiple_items(data.len() as u32).saturating_add(
- data.iter()
- .map(|data| match data {
+ init_token_properties_delta::<T, _>(
+ data.iter().map(|data| match data {
up_data_structs::CreateItemData::ReFungible(rft_data) => {
- properties_weight::<T>(&rft_data.properties)
+ rft_data.properties.len() as u32
}
- _ => Weight::zero(),
- })
- .fold(Weight::zero(), |a, b| a.saturating_add(b)),
+ _ => 0,
+ }),
+ <SelfWeightOf<T>>::init_token_properties,
+ ),
)
}
@@ -72,15 +65,17 @@
match call {
CreateItemExData::RefungibleMultipleOwners(i) => {
<SelfWeightOf<T>>::create_multiple_items_ex_multiple_owners(i.users.len() as u32)
- .saturating_add(properties_weight::<T>(&i.properties))
+ .saturating_add(init_token_properties_delta::<T, _>(
+ [i.properties.len() as u32].into_iter(),
+ <SelfWeightOf<T>>::init_token_properties,
+ ))
}
CreateItemExData::RefungibleMultipleItems(i) => {
<SelfWeightOf<T>>::create_multiple_items_ex_multiple_items(i.len() as u32)
- .saturating_add(
- i.iter()
- .map(|d| properties_weight::<T>(&d.properties))
- .fold(Weight::zero(), |a, b| a.saturating_add(b)),
- )
+ .saturating_add(init_token_properties_delta::<T, _>(
+ i.iter().map(|d| d.properties.len() as u32),
+ <SelfWeightOf<T>>::init_token_properties,
+ ))
}
_ => Weight::zero(),
}
@@ -399,7 +394,6 @@
&sender,
token_id,
properties.into_iter(),
- pallet_common::SetPropertyMode::ExistingToken,
nesting_budget,
),
weight,
@@ -441,6 +435,18 @@
)
}
+ fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ <TokenProperties<T>>::get((self.id, token_id))
+ }
+
+ fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::set((self.id, token_id), map)
+ }
+
+ fn properties_exist(&self, token: TokenId) -> bool {
+ <TokenProperties<T>>::contains_key((self.id, token))
+ }
+
fn check_nesting(
&self,
_sender: <T>::CrossAccountId,
@@ -479,6 +485,29 @@
<Pallet<T>>::token_owner(self.id, token)
}
+ fn check_token_indirect_owner(
+ &self,
+ token: TokenId,
+ maybe_owner: &T::CrossAccountId,
+ nesting_budget: &dyn Budget,
+ ) -> Result<bool, DispatchError> {
+ let balance = self.balance(maybe_owner.clone(), token);
+ let total_pieces: u128 = <Pallet<T>>::total_pieces(self.id, token).unwrap_or(u128::MAX);
+ if balance != total_pieces {
+ return Ok(false);
+ }
+
+ let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
+ maybe_owner.clone(),
+ self.id,
+ token,
+ None,
+ nesting_budget,
+ )?;
+
+ Ok(is_bundle_owner)
+ }
+
/// Returns 10 token in no particular order.
fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId> {
<Pallet<T>>::token_owners(self.id, token).unwrap_or_default()
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -214,7 +214,6 @@
&caller,
TokenId(token_id),
properties.into_iter(),
- pallet_common::SetPropertyMode::ExistingToken,
&nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -96,8 +96,8 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
- CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
- Event as CommonEvent, Pallet as PalletCommon, SetPropertyMode,
+ Error as CommonError, eth::collection_id_to_address, Event as CommonEvent,
+ Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
use sp_core::{Get, H160};
@@ -533,66 +533,16 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,
- mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let mut is_token_owner =
- pallet_common::LazyValue::new(|| -> Result<bool, DispatchError> {
- if let SetPropertyMode::NewToken {
- mint_target_is_sender,
- } = mode
- {
- return Ok(mint_target_is_sender);
- }
-
- let balance = collection.balance(sender.clone(), token_id);
- let total_pieces: u128 =
- Self::total_pieces(collection.id, token_id).unwrap_or(u128::MAX);
- if balance != total_pieces {
- return Ok(false);
- }
-
- let is_bundle_owner = <PalletStructure<T>>::check_indirectly_owned(
- sender.clone(),
- collection.id,
- token_id,
- None,
- nesting_budget,
- )?;
-
- Ok(is_bundle_owner)
- });
-
- let is_new_token = matches!(mode, SetPropertyMode::NewToken { .. });
-
- let mut is_token_exist = pallet_common::LazyValue::new(|| {
- if is_new_token {
- debug_assert!(Self::token_exists(collection, token_id));
- true
- } else {
- Self::token_exists(collection, token_id)
- }
- });
-
- let stored_properties = if is_new_token {
- debug_assert!(!<TokenProperties<T>>::contains_key((
- collection.id,
- token_id
- )));
- TokenPropertiesT::new()
- } else {
- <TokenProperties<T>>::get((collection.id, token_id))
- };
+ let mut property_writer =
+ pallet_common::property_writer_for_existing_token(collection, sender);
- <PalletCommon<T>>::modify_token_properties(
- collection,
+ property_writer.write_token_properties(
sender,
token_id,
- &mut is_token_exist,
properties_updates,
- stored_properties,
- &mut is_token_owner,
- |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ nesting_budget,
erc::ERC721TokenEvent::TokenChanged {
token_id: token_id.into(),
}
@@ -618,7 +568,6 @@
sender: &T::CrossAccountId,
token_id: TokenId,
properties: impl Iterator<Item = Property>,
- mode: SetPropertyMode,
nesting_budget: &dyn Budget,
) -> DispatchResult {
Self::modify_token_properties(
@@ -626,7 +575,6 @@
sender,
token_id,
properties.map(|p| (p.key, Some(p.value))),
- mode,
nesting_budget,
)
}
@@ -643,7 +591,6 @@
sender,
token_id,
[property].into_iter(),
- SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -660,7 +607,6 @@
sender,
token_id,
property_keys.into_iter().map(|key| (key, None)),
- SetPropertyMode::ExistingToken,
nesting_budget,
)
}
@@ -941,11 +887,15 @@
// =========
+ let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);
+
with_transaction(|| {
for (i, data) in data.iter().enumerate() {
let token_id = first_token_id + i as u32 + 1;
<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);
+ let token = TokenId(token_id);
+
let mut mint_target_is_sender = true;
for (user, amount) in data.users.iter() {
if *amount == 0 {
@@ -955,23 +905,22 @@
mint_target_is_sender = mint_target_is_sender && sender.conv_eq(user);
<Balance<T>>::insert((collection.id, token_id, &user), amount);
- <Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);
+ <Owned<T>>::insert((collection.id, &user, token), true);
<PalletStructure<T>>::nest_if_sent_to_token_unchecked(
user,
collection.id,
- TokenId(token_id),
+ token,
);
}
- if let Err(e) = Self::set_token_properties(
- collection,
- sender,
- TokenId(token_id),
+ if let Err(e) = property_writer.write_token_properties(
+ mint_target_is_sender,
+ token,
data.properties.clone().into_iter(),
- SetPropertyMode::NewToken {
- mint_target_is_sender,
- },
- nesting_budget,
+ erc::ERC721TokenEvent::TokenChanged {
+ token_id: token.into(),
+ }
+ .to_log(T::ContractAddress::get()),
) {
return TransactionOutcome::Rollback(Err(e));
}