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.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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{68 Get,69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 },72 dispatch::Pays,73 transactional, fail,74};75use up_data_structs::{76 AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,77 CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,78 TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,79 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,80 CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,81 SponsoringRateLimit, budget::Budget, PhantomType, Property,82 CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,83 PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,84 PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,85};86use up_pov_estimate_rpc::PovInfo;8788pub use pallet::*;89use sp_core::H160;90use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9192#[cfg(feature = "runtime-benchmarks")]93pub mod benchmarking;94pub mod dispatch;95pub mod erc;96pub mod eth;97pub mod helpers;98#[allow(missing_docs)]99pub mod weights;100/// Weight info.101pub type SelfWeightOf<T> = <T as Config>::WeightInfo;102103/// Collection handle contains information about collection data and id.104/// Also provides functionality to count consumed gas.105///106/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).107/// It allows to perform common operations and queries on any collection type,108/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].109#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]110pub struct CollectionHandle<T: Config> {111 /// Collection id112 pub id: CollectionId,113 collection: Collection<T::AccountId>,114 /// Substrate recorder for counting consumed gas115 pub recorder: SubstrateRecorder<T>,116}117118impl<T: Config> WithRecorder<T> for CollectionHandle<T> {119 fn recorder(&self) -> &SubstrateRecorder<T> {120 &self.recorder121 }122 fn into_recorder(self) -> SubstrateRecorder<T> {123 self.recorder124 }125}126127impl<T: Config> CollectionHandle<T> {128 /// Same as [CollectionHandle::new] but with an explicit gas limit.129 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {130 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))131 }132133 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].134 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {135 <CollectionById<T>>::get(id).map(|collection| Self {136 id,137 collection,138 recorder,139 })140 }141142 /// Retrives collection data from storage and creates collection handle with default parameters.143 /// If collection not found return `None`144 pub fn new(id: CollectionId) -> Option<Self> {145 Self::new_with_gas_limit(id, u64::MAX)146 }147148 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.149 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {150 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)151 }152153 /// Consume gas for reading.154 pub fn consume_store_reads(155 &self,156 reads: u64,157 ) -> pallet_evm_coder_substrate::execution::Result<()> {158 self.recorder().consume_store_reads(reads)159 }160161 /// Consume gas for writing.162 pub fn consume_store_writes(163 &self,164 writes: u64,165 ) -> pallet_evm_coder_substrate::execution::Result<()> {166 self.recorder().consume_store_writes(writes)167 }168169 /// Consume gas for reading and writing.170 pub fn consume_store_reads_and_writes(171 &self,172 reads: u64,173 writes: u64,174 ) -> pallet_evm_coder_substrate::execution::Result<()> {175 self.recorder()176 .consume_store_reads_and_writes(reads, writes)177 }178179 /// Save collection to storage.180 pub fn save(&self) -> DispatchResult {181 <CollectionById<T>>::insert(self.id, &self.collection);182 Ok(())183 }184185 /// Set collection sponsor.186 ///187 /// Unique collections allows sponsoring for certain actions.188 /// This method allows you to set the sponsor of the collection.189 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].190 pub fn set_sponsor(191 &mut self,192 sender: &T::CrossAccountId,193 sponsor: T::AccountId,194 ) -> DispatchResult {195 self.check_is_internal()?;196 self.check_is_owner_or_admin(sender)?;197198 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());199200 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));201 <PalletEvm<T>>::deposit_log(202 erc::CollectionHelpersEvents::CollectionChanged {203 collection_id: eth::collection_id_to_address(self.id),204 }205 .to_log(T::ContractAddress::get()),206 );207208 self.save()209 }210211 /// Force set `sponsor`.212 ///213 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation214 /// from the `sponsor` is not required.215 ///216 /// # Arguments217 ///218 /// * `sponsor`: ID of the account of the sponsor-to-be.219 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {220 self.check_is_internal()?;221222 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());223224 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));225 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));226 <PalletEvm<T>>::deposit_log(227 erc::CollectionHelpersEvents::CollectionChanged {228 collection_id: eth::collection_id_to_address(self.id),229 }230 .to_log(T::ContractAddress::get()),231 );232233 self.save()234 }235236 /// Confirm sponsorship237 ///238 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.239 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].240 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {241 self.check_is_internal()?;242 ensure!(243 self.collection.sponsorship.pending_sponsor() == Some(sender),244 Error::<T>::ConfirmSponsorshipFail245 );246247 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());248249 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));250 <PalletEvm<T>>::deposit_log(251 erc::CollectionHelpersEvents::CollectionChanged {252 collection_id: eth::collection_id_to_address(self.id),253 }254 .to_log(T::ContractAddress::get()),255 );256257 self.save()258 }259260 /// Remove collection sponsor.261 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {262 self.check_is_internal()?;263 self.check_is_owner_or_admin(sender)?;264265 self.collection.sponsorship = SponsorshipState::Disabled;266267 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));268 <PalletEvm<T>>::deposit_log(269 erc::CollectionHelpersEvents::CollectionChanged {270 collection_id: eth::collection_id_to_address(self.id),271 }272 .to_log(T::ContractAddress::get()),273 );274 self.save()275 }276277 /// Force remove `sponsor`.278 ///279 /// Differs from `remove_sponsor` in that280 /// it doesn't require consent from the `owner` of the collection.281 pub fn force_remove_sponsor(&mut self) -> DispatchResult {282 self.check_is_internal()?;283284 self.collection.sponsorship = SponsorshipState::Disabled;285286 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));287 <PalletEvm<T>>::deposit_log(288 erc::CollectionHelpersEvents::CollectionChanged {289 collection_id: eth::collection_id_to_address(self.id),290 }291 .to_log(T::ContractAddress::get()),292 );293 self.save()294 }295296 /// Checks that the collection was created with, and must be operated upon through **Unique API**.297 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.298 pub fn check_is_internal(&self) -> DispatchResult {299 if self.flags.external {300 return Err(<Error<T>>::CollectionIsExternal)?;301 }302303 Ok(())304 }305306 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.307 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.308 pub fn check_is_external(&self) -> DispatchResult {309 if !self.flags.external {310 return Err(<Error<T>>::CollectionIsInternal)?;311 }312313 Ok(())314 }315}316317impl<T: Config> Deref for CollectionHandle<T> {318 type Target = Collection<T::AccountId>;319320 fn deref(&self) -> &Self::Target {321 &self.collection322 }323}324325impl<T: Config> DerefMut for CollectionHandle<T> {326 fn deref_mut(&mut self) -> &mut Self::Target {327 &mut self.collection328 }329}330331impl<T: Config> CollectionHandle<T> {332 /// Checks if the `user` is the owner of the collection.333 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {334 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);335 Ok(())336 }337338 /// Returns **true** if the `user` is the owner or administrator of the collection.339 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {340 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))341 }342343 /// Checks if the `user` is the owner or administrator of the collection.344 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {345 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);346 Ok(())347 }348349 /// Returns **true** if350 /// * the `user`is a collection owner or admin351 /// * the collection limits allow the owner/admins to transfer/burn any collection token352 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {353 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)354 }355356 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.357 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {358 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)359 }360361 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.362 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {363 ensure!(364 <Allowlist<T>>::get((self.id, user)),365 <Error<T>>::AddressNotInAllowlist366 );367 Ok(())368 }369370 /// Changes collection owner to another account371 /// #### Store read/writes372 /// 1 writes373 pub fn change_owner(374 &mut self,375 caller: T::CrossAccountId,376 new_owner: T::CrossAccountId,377 ) -> DispatchResult {378 self.check_is_internal()?;379 self.check_is_owner(&caller)?;380 self.collection.owner = new_owner.as_sub().clone();381382 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(383 self.id,384 new_owner.as_sub().clone(),385 ));386 <PalletEvm<T>>::deposit_log(387 erc::CollectionHelpersEvents::CollectionChanged {388 collection_id: eth::collection_id_to_address(self.id),389 }390 .to_log(T::ContractAddress::get()),391 );392393 self.save()394 }395}396397#[frame_support::pallet]398pub mod pallet {399400 use super::*;401 use dispatch::CollectionDispatch;402 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};403 use up_data_structs::{TokenId, mapping::TokenAddressMapping};404 use scale_info::TypeInfo;405 use weights::WeightInfo;406407 #[pallet::config]408 pub trait Config:409 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo410 {411 /// Weight information for functions of this pallet.412 type WeightInfo: WeightInfo;413414 /// Events compatible with [`frame_system::Config::Event`].415 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;416417 /// Handler of accounts and payment.418 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;419420 /// Set price to create a collection.421 #[pallet::constant]422 type CollectionCreationPrice: Get<423 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,424 >;425426 /// Dispatcher of operations on collections.427 type CollectionDispatch: CollectionDispatch<Self>;428429 /// Account which holds the chain's treasury.430 type TreasuryAccountId: Get<Self::AccountId>;431432 /// Address under which the CollectionHelper contract would be available.433 #[pallet::constant]434 type ContractAddress: Get<H160>;435436 /// Mapper for token addresses to Ethereum addresses.437 type EvmTokenAddressMapping: TokenAddressMapping<H160>;438439 /// Mapper for token addresses to [`CrossAccountId`].440 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;441 }442443 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);444 /// Collection id for native fungible collction.445 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);446447 #[pallet::pallet]448 #[pallet::storage_version(STORAGE_VERSION)]449 pub struct Pallet<T>(_);450451 #[pallet::extra_constants]452 impl<T: Config> Pallet<T> {453 /// Maximum admins per collection.454 pub fn collection_admins_limit() -> u32 {455 COLLECTION_ADMINS_LIMIT456 }457 }458459 #[pallet::genesis_config]460 pub struct GenesisConfig<T>(PhantomData<T>);461462 #[cfg(feature = "std")]463 impl<T: Config> Default for GenesisConfig<T> {464 fn default() -> Self {465 Self(Default::default())466 }467 }468469 #[pallet::genesis_build]470 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {471 fn build(&self) {472 StorageVersion::new(1).put::<Pallet<T>>();473 }474 }475476 impl<T: Config> Pallet<T> {477 /// Helper function that handles deposit events478 pub fn deposit_event(event: Event<T>) {479 let event = <T as Config>::RuntimeEvent::from(event);480 let event = event.into();481 <frame_system::Pallet<T>>::deposit_event(event)482 }483 }484485 #[pallet::event]486 pub enum Event<T: Config> {487 /// New collection was created488 CollectionCreated(489 /// Globally unique identifier of newly created collection.490 CollectionId,491 /// [`CollectionMode`] converted into _u8_.492 u8,493 /// Collection owner.494 T::AccountId,495 ),496497 /// New collection was destroyed498 CollectionDestroyed(499 /// Globally unique identifier of collection.500 CollectionId,501 ),502503 /// New item was created.504 ItemCreated(505 /// Id of the collection where item was created.506 CollectionId,507 /// Id of an item. Unique within the collection.508 TokenId,509 /// Owner of newly created item510 T::CrossAccountId,511 /// Always 1 for NFT512 u128,513 ),514515 /// Collection item was burned.516 ItemDestroyed(517 /// Id of the collection where item was destroyed.518 CollectionId,519 /// Identifier of burned NFT.520 TokenId,521 /// Which user has destroyed its tokens.522 T::CrossAccountId,523 /// Amount of token pieces destroed. Always 1 for NFT.524 u128,525 ),526527 /// Item was transferred528 Transfer(529 /// Id of collection to which item is belong.530 CollectionId,531 /// Id of an item.532 TokenId,533 /// Original owner of item.534 T::CrossAccountId,535 /// New owner of item.536 T::CrossAccountId,537 /// Amount of token pieces transfered. Always 1 for NFT.538 u128,539 ),540541 /// Amount pieces of token owned by `sender` was approved for `spender`.542 Approved(543 /// Id of collection to which item is belong.544 CollectionId,545 /// Id of an item.546 TokenId,547 /// Original owner of item.548 T::CrossAccountId,549 /// Id for which the approval was granted.550 T::CrossAccountId,551 /// Amount of token pieces transfered. Always 1 for NFT.552 u128,553 ),554555 /// A `sender` approves operations on all owned tokens for `spender`.556 ApprovedForAll(557 /// Id of collection to which item is belong.558 CollectionId,559 /// Owner of a wallet.560 T::CrossAccountId,561 /// Id for which operator status was granted or rewoked.562 T::CrossAccountId,563 /// Is operator status granted or revoked?564 bool,565 ),566567 /// The colletion property has been added or edited.568 CollectionPropertySet(569 /// Id of collection to which property has been set.570 CollectionId,571 /// The property that was set.572 PropertyKey,573 ),574575 /// The property has been deleted.576 CollectionPropertyDeleted(577 /// Id of collection to which property has been deleted.578 CollectionId,579 /// The property that was deleted.580 PropertyKey,581 ),582583 /// The token property has been added or edited.584 TokenPropertySet(585 /// Identifier of the collection whose token has the property set.586 CollectionId,587 /// The token for which the property was set.588 TokenId,589 /// The property that was set.590 PropertyKey,591 ),592593 /// The token property has been deleted.594 TokenPropertyDeleted(595 /// Identifier of the collection whose token has the property deleted.596 CollectionId,597 /// The token for which the property was deleted.598 TokenId,599 /// The property that was deleted.600 PropertyKey,601 ),602603 /// The token property permission of a collection has been set.604 PropertyPermissionSet(605 /// ID of collection to which property permission has been set.606 CollectionId,607 /// The property permission that was set.608 PropertyKey,609 ),610611 /// Address was added to the allow list.612 AllowListAddressAdded(613 /// ID of the affected collection.614 CollectionId,615 /// Address of the added account.616 T::CrossAccountId,617 ),618619 /// Address was removed from the allow list.620 AllowListAddressRemoved(621 /// ID of the affected collection.622 CollectionId,623 /// Address of the removed account.624 T::CrossAccountId,625 ),626627 /// Collection admin was added.628 CollectionAdminAdded(629 /// ID of the affected collection.630 CollectionId,631 /// Admin address.632 T::CrossAccountId,633 ),634635 /// Collection admin was removed.636 CollectionAdminRemoved(637 /// ID of the affected collection.638 CollectionId,639 /// Removed admin address.640 T::CrossAccountId,641 ),642643 /// Collection limits were set.644 CollectionLimitSet(645 /// ID of the affected collection.646 CollectionId,647 ),648649 /// Collection owned was changed.650 CollectionOwnerChanged(651 /// ID of the affected collection.652 CollectionId,653 /// New owner address.654 T::AccountId,655 ),656657 /// Collection permissions were set.658 CollectionPermissionSet(659 /// ID of the affected collection.660 CollectionId,661 ),662663 /// Collection sponsor was set.664 CollectionSponsorSet(665 /// ID of the affected collection.666 CollectionId,667 /// New sponsor address.668 T::AccountId,669 ),670671 /// New sponsor was confirm.672 SponsorshipConfirmed(673 /// ID of the affected collection.674 CollectionId,675 /// New sponsor address.676 T::AccountId,677 ),678679 /// Collection sponsor was removed.680 CollectionSponsorRemoved(681 /// ID of the affected collection.682 CollectionId,683 ),684 }685686 #[pallet::error]687 pub enum Error<T> {688 /// This collection does not exist.689 CollectionNotFound,690 /// Sender parameter and item owner must be equal.691 MustBeTokenOwner,692 /// No permission to perform action693 NoPermission,694 /// Destroying only empty collections is allowed695 CantDestroyNotEmptyCollection,696 /// Collection is not in mint mode.697 PublicMintingNotAllowed,698 /// Address is not in allow list.699 AddressNotInAllowlist,700701 /// Collection name can not be longer than 63 char.702 CollectionNameLimitExceeded,703 /// Collection description can not be longer than 255 char.704 CollectionDescriptionLimitExceeded,705 /// Token prefix can not be longer than 15 char.706 CollectionTokenPrefixLimitExceeded,707 /// Total collections bound exceeded.708 TotalCollectionsLimitExceeded,709 /// Exceeded max admin count710 CollectionAdminCountExceeded,711 /// Collection limit bounds per collection exceeded712 CollectionLimitBoundsExceeded,713 /// Tried to enable permissions which are only permitted to be disabled714 OwnerPermissionsCantBeReverted,715 /// Collection settings not allowing items transferring716 TransferNotAllowed,717 /// Account token limit exceeded per collection718 AccountTokenLimitExceeded,719 /// Collection token limit exceeded720 CollectionTokenLimitExceeded,721 /// Metadata flag frozen722 MetadataFlagFrozen,723724 /// Item does not exist725 TokenNotFound,726 /// Item is balance not enough727 TokenValueTooLow,728 /// Requested value is more than the approved729 ApprovedValueTooLow,730 /// Tried to approve more than owned731 CantApproveMoreThanOwned,732 /// Only spending from eth mirror could be approved733 AddressIsNotEthMirror,734735 /// Can't transfer tokens to ethereum zero address736 AddressIsZero,737738 /// The operation is not supported739 UnsupportedOperation,740741 /// Insufficient funds to perform an action742 NotSufficientFounds,743744 /// User does not satisfy the nesting rule745 UserIsNotAllowedToNest,746 /// Only tokens from specific collections may nest tokens under this one747 SourceCollectionIsNotAllowedToNest,748749 /// Tried to store more data than allowed in collection field750 CollectionFieldSizeExceeded,751752 /// Tried to store more property data than allowed753 NoSpaceForProperty,754755 /// Tried to store more property keys than allowed756 PropertyLimitReached,757758 /// Property key is too long759 PropertyKeyIsTooLong,760761 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed762 InvalidCharacterInPropertyKey,763764 /// Empty property keys are forbidden765 EmptyPropertyKey,766767 /// Tried to access an external collection with an internal API768 CollectionIsExternal,769770 /// Tried to access an internal collection with an external API771 CollectionIsInternal,772773 /// This address is not set as sponsor, use setCollectionSponsor first.774 ConfirmSponsorshipFail,775776 /// The user is not an administrator.777 UserIsNotCollectionAdmin,778 }779780 /// Storage of the count of created collections. Essentially contains the last collection ID.781 #[pallet::storage]782 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;783784 /// Storage of the count of deleted collections.785 #[pallet::storage]786 pub type DestroyedCollectionCount<T> =787 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;788789 /// Storage of collection info.790 #[pallet::storage]791 pub type CollectionById<T> = StorageMap<792 Hasher = Blake2_128Concat,793 Key = CollectionId,794 Value = Collection<<T as frame_system::Config>::AccountId>,795 QueryKind = OptionQuery,796 >;797798 /// Storage of collection properties.799 #[pallet::storage]800 #[pallet::getter(fn collection_properties)]801 pub type CollectionProperties<T> = StorageMap<802 Hasher = Blake2_128Concat,803 Key = CollectionId,804 Value = CollectionPropertiesT,805 QueryKind = ValueQuery,806 >;807808 /// Storage of token property permissions of a collection.809 #[pallet::storage]810 #[pallet::getter(fn property_permissions)]811 pub type CollectionPropertyPermissions<T> = StorageMap<812 Hasher = Blake2_128Concat,813 Key = CollectionId,814 Value = PropertiesPermissionMap,815 QueryKind = ValueQuery,816 >;817818 /// Storage of the amount of collection admins.819 #[pallet::storage]820 pub type AdminAmount<T> = StorageMap<821 Hasher = Blake2_128Concat,822 Key = CollectionId,823 Value = u32,824 QueryKind = ValueQuery,825 >;826827 /// List of collection admins.828 #[pallet::storage]829 pub type IsAdmin<T: Config> = StorageNMap<830 Key = (831 Key<Blake2_128Concat, CollectionId>,832 Key<Blake2_128Concat, T::CrossAccountId>,833 ),834 Value = bool,835 QueryKind = ValueQuery,836 >;837838 /// Allowlisted collection users.839 #[pallet::storage]840 pub type Allowlist<T: Config> = StorageNMap<841 Key = (842 Key<Blake2_128Concat, CollectionId>,843 Key<Blake2_128Concat, T::CrossAccountId>,844 ),845 Value = bool,846 QueryKind = ValueQuery,847 >;848849 /// Not used by code, exists only to provide some types to metadata.850 #[pallet::storage]851 pub type DummyStorageValue<T: Config> = StorageValue<852 Value = (853 CollectionStats,854 CollectionId,855 TokenId,856 TokenChild,857 PhantomType<(858 TokenData<T::CrossAccountId>,859 RpcCollection<T::AccountId>,860 // PoV Estimate Info861 PovInfo,862 )>,863 ),864 QueryKind = OptionQuery,865 >;866}867868/// Represents the change mode for the token property.869pub enum SetPropertyMode {870 /// The token already exists.871 ExistingToken,872873 /// New token.874 NewToken {875 /// The creator of the token is the recipient.876 mint_target_is_sender: bool,877 },878}879880/// Value representation with delayed initialization time.881pub struct LazyValue<T, F: FnOnce() -> T> {882 value: Option<T>,883 f: Option<F>,884}885886impl<T, F: FnOnce() -> T> LazyValue<T, F> {887 /// Create a new LazyValue.888 pub fn new(f: F) -> Self {889 Self {890 value: None,891 f: Some(f),892 }893 }894895 /// Get the value. If it call furst time the value will be initialized.896 pub fn value(&mut self) -> &T {897 if self.value.is_none() {898 self.value = Some(self.f.take().unwrap()())899 }900901 self.value.as_ref().unwrap()902 }903904 /// Is value initialized.905 pub fn has_value(&self) -> bool {906 self.value.is_some()907 }908}909910fn check_token_permissions<T, FCA, FTO, FTE>(911 collection_admin_permitted: bool,912 token_owner_permitted: bool,913 is_collection_admin: &mut LazyValue<bool, FCA>,914 is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,915 is_token_exist: &mut LazyValue<bool, FTE>,916) -> DispatchResult917where918 T: Config,919 FCA: FnOnce() -> bool,920 FTO: FnOnce() -> Result<bool, DispatchError>,921 FTE: FnOnce() -> bool,922{923 if !(collection_admin_permitted && *is_collection_admin.value()924 || token_owner_permitted && (*is_token_owner.value())?)925 {926 fail!(<Error<T>>::NoPermission);927 }928929 let token_certainly_exist = is_token_owner.has_value() && (*is_token_owner.value())?;930 if !token_certainly_exist && !is_token_exist.value() {931 fail!(<Error<T>>::TokenNotFound);932 }933 Ok(())934}935936impl<T: Config> Pallet<T> {937 /// Enshure that receiver address is correct.938 ///939 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.940 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {941 ensure!(942 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,943 <Error<T>>::AddressIsZero944 );945 Ok(())946 }947948 /// Get a vector of collection admins.949 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {950 <IsAdmin<T>>::iter_prefix((collection,))951 .map(|(a, _)| a)952 .collect()953 }954955 /// Get a vector of users allowed to mint tokens.956 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {957 <Allowlist<T>>::iter_prefix((collection,))958 .map(|(a, _)| a)959 .collect()960 }961962 /// Is `user` allowed to mint token in `collection`.963 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {964 <Allowlist<T>>::get((collection, user))965 }966967 /// Get statistics of collections.968 pub fn collection_stats() -> CollectionStats {969 let created = <CreatedCollectionCount<T>>::get();970 let destroyed = <DestroyedCollectionCount<T>>::get();971 CollectionStats {972 created: created.0,973 destroyed: destroyed.0,974 alive: created.0 - destroyed.0,975 }976 }977978 /// Get the effective limits for the collection.979 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {980 let collection = <CollectionById<T>>::get(collection)?;981 let limits = collection.limits;982 let effective_limits = CollectionLimits {983 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),984 sponsored_data_size: Some(limits.sponsored_data_size()),985 sponsored_data_rate_limit: Some(986 limits987 .sponsored_data_rate_limit988 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),989 ),990 token_limit: Some(limits.token_limit()),991 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(992 match collection.mode {993 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,994 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,995 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,996 },997 )),998 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),999 owner_can_transfer: Some(limits.owner_can_transfer()),1000 owner_can_destroy: Some(limits.owner_can_destroy()),1001 transfers_enabled: Some(limits.transfers_enabled()),1002 };10031004 Some(effective_limits)1005 }10061007 /// Returns information about the `collection` adapted for rpc.1008 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1009 let Collection {1010 name,1011 description,1012 owner,1013 mode,1014 token_prefix,1015 sponsorship,1016 limits,1017 permissions,1018 flags,1019 } = <CollectionById<T>>::get(collection)?;10201021 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1022 .into_iter()1023 .map(|(key, permission)| PropertyKeyPermission { key, permission })1024 .collect();10251026 let properties = <CollectionProperties<T>>::get(collection)1027 .into_iter()1028 .map(|(key, value)| Property { key, value })1029 .collect();10301031 let permissions = CollectionPermissions {1032 access: Some(permissions.access()),1033 mint_mode: Some(permissions.mint_mode()),1034 nesting: Some(permissions.nesting().clone()),1035 };10361037 Some(RpcCollection {1038 name: name.into_inner(),1039 description: description.into_inner(),1040 owner,1041 mode,1042 token_prefix: token_prefix.into_inner(),1043 sponsorship,1044 limits,1045 permissions,1046 token_property_permissions,1047 properties,1048 read_only: flags.external,10491050 flags: RpcCollectionFlags {1051 foreign: flags.foreign,1052 erc721metadata: flags.erc721metadata,1053 },1054 })1055 }1056}10571058macro_rules! limit_default {1059 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1060 $(1061 if let Some($new) = $new.$field {1062 let $old = $old.$field($($arg)?);1063 let _ = $new;1064 let _ = $old;1065 $check1066 } else {1067 $new.$field = $old.$field1068 }1069 )*1070 }};1071}1072macro_rules! limit_default_clone {1073 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1074 $(1075 if let Some($new) = $new.$field.clone() {1076 let $old = $old.$field($($arg)?);1077 let _ = $new;1078 let _ = $old;1079 $check1080 } else {1081 $new.$field = $old.$field.clone()1082 }1083 )*1084 }};1085}10861087impl<T: Config> Pallet<T> {1088 /// Create new collection.1089 ///1090 /// * `owner` - The owner of the collection.1091 /// * `data` - Description of the created collection.1092 /// * `flags` - Extra flags to store.1093 pub fn init_collection(1094 owner: T::CrossAccountId,1095 payer: T::CrossAccountId,1096 data: CreateCollectionData<T::CrossAccountId>,1097 ) -> Result<CollectionId, DispatchError> {1098 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1099 Self::init_collection_internal(owner, payer, data)1100 }11011102 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1103 pub fn init_foreign_collection(1104 owner: T::CrossAccountId,1105 payer: T::CrossAccountId,1106 mut data: CreateCollectionData<T::CrossAccountId>,1107 ) -> Result<CollectionId, DispatchError> {1108 data.flags.foreign = true;1109 let id = Self::init_collection_internal(owner, payer, data)?;1110 Ok(id)1111 }11121113 fn init_collection_internal(1114 owner: T::CrossAccountId,1115 payer: T::CrossAccountId,1116 data: CreateCollectionData<T::CrossAccountId>,1117 ) -> Result<CollectionId, DispatchError> {1118 {1119 ensure!(1120 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1121 Error::<T>::CollectionTokenPrefixLimitExceeded1122 );1123 }11241125 let created_count = <CreatedCollectionCount<T>>::get()1126 .01127 .checked_add(1)1128 .ok_or(ArithmeticError::Overflow)?;1129 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1130 let id = CollectionId(created_count);11311132 // bound Total number of collections1133 ensure!(1134 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1135 <Error<T>>::TotalCollectionsLimitExceeded1136 );11371138 // =========11391140 let collection = Collection {1141 owner: owner.as_sub().clone(),1142 name: data.name,1143 mode: data.mode.clone(),1144 description: data.description,1145 token_prefix: data.token_prefix,1146 sponsorship: data1147 .pending_sponsor1148 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1149 .unwrap_or_default(),1150 limits: data1151 .limits1152 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1153 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1154 permissions: data1155 .permissions1156 .map(|permissions| {1157 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1158 })1159 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1160 flags: data.flags,1161 };11621163 let mut collection_properties = CollectionPropertiesT::new();1164 collection_properties1165 .try_set_from_iter(data.properties.into_iter())1166 .map_err(<Error<T>>::from)?;11671168 CollectionProperties::<T>::insert(id, collection_properties);11691170 let mut token_props_permissions = PropertiesPermissionMap::new();1171 token_props_permissions1172 .try_set_from_iter(data.token_property_permissions.into_iter())1173 .map_err(<Error<T>>::from)?;11741175 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11761177 let mut admin_amount = 0u32;1178 for admin in data.admin_list.iter() {1179 if !<IsAdmin<T>>::get((id, admin)) {1180 <IsAdmin<T>>::insert((id, admin), true);1181 admin_amount = admin_amount1182 .checked_add(1)1183 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1184 }1185 }1186 ensure!(1187 admin_amount <= Self::collection_admins_limit(),1188 <Error<T>>::CollectionAdminCountExceeded,1189 );1190 <AdminAmount<T>>::insert(id, admin_amount);11911192 // Take a (non-refundable) deposit of collection creation1193 {1194 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1195 imbalance.subsume(<T as Config>::Currency::deposit(1196 &T::TreasuryAccountId::get(),1197 T::CollectionCreationPrice::get(),1198 Precision::Exact,1199 )?);1200 let credit =1201 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1202 .map_err(|_| Error::<T>::NotSufficientFounds)?;12031204 debug_assert!(credit.peek().is_zero())1205 }12061207 <CreatedCollectionCount<T>>::put(created_count);1208 <Pallet<T>>::deposit_event(Event::CollectionCreated(1209 id,1210 data.mode.id(),1211 owner.as_sub().clone(),1212 ));1213 <PalletEvm<T>>::deposit_log(1214 erc::CollectionHelpersEvents::CollectionCreated {1215 owner: *owner.as_eth(),1216 collection_id: eth::collection_id_to_address(id),1217 }1218 .to_log(T::ContractAddress::get()),1219 );1220 <CollectionById<T>>::insert(id, collection);1221 Ok(id)1222 }12231224 /// Destroy collection.1225 ///1226 /// * `collection` - Collection handler.1227 /// * `sender` - The owner or administrator of the collection.1228 pub fn destroy_collection(1229 collection: CollectionHandle<T>,1230 sender: &T::CrossAccountId,1231 ) -> DispatchResult {1232 ensure!(1233 collection.limits.owner_can_destroy(),1234 <Error<T>>::NoPermission,1235 );1236 collection.check_is_owner(sender)?;12371238 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1239 .01240 .checked_add(1)1241 .ok_or(ArithmeticError::Overflow)?;12421243 // =========12441245 <DestroyedCollectionCount<T>>::put(destroyed_collections);1246 <CollectionById<T>>::remove(collection.id);1247 <AdminAmount<T>>::remove(collection.id);1248 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1249 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1250 <CollectionProperties<T>>::remove(collection.id);12511252 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12531254 <PalletEvm<T>>::deposit_log(1255 erc::CollectionHelpersEvents::CollectionDestroyed {1256 collection_id: eth::collection_id_to_address(collection.id),1257 }1258 .to_log(T::ContractAddress::get()),1259 );1260 Ok(())1261 }12621263 /// This function sets or removes a collection properties according to1264 /// `properties_updates` contents:1265 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1266 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1267 ///1268 /// This function fires an event for each property change.1269 /// In case of an error, all the changes (including the events) will be reverted1270 /// since the function is transactional.1271 #[transactional]1272 fn modify_collection_properties(1273 collection: &CollectionHandle<T>,1274 sender: &T::CrossAccountId,1275 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1276 ) -> DispatchResult {1277 collection.check_is_owner_or_admin(sender)?;12781279 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12801281 for (key, value) in properties_updates {1282 match value {1283 Some(value) => {1284 stored_properties1285 .try_set(key.clone(), value)1286 .map_err(<Error<T>>::from)?;12871288 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1289 <PalletEvm<T>>::deposit_log(1290 erc::CollectionHelpersEvents::CollectionChanged {1291 collection_id: eth::collection_id_to_address(collection.id),1292 }1293 .to_log(T::ContractAddress::get()),1294 );1295 }1296 None => {1297 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12981299 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1300 <PalletEvm<T>>::deposit_log(1301 erc::CollectionHelpersEvents::CollectionChanged {1302 collection_id: eth::collection_id_to_address(collection.id),1303 }1304 .to_log(T::ContractAddress::get()),1305 );1306 }1307 }1308 }13091310 <CollectionProperties<T>>::set(collection.id, stored_properties);13111312 Ok(())1313 }13141315 /// A batch operation to add, edit or remove properties for a token.1316 /// It sets or removes a token's properties according to1317 /// `properties_updates` contents:1318 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1319 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1320 ///1321 /// All affected properties should have `mutable` permission1322 /// to be **deleted** or to be **set more than once**,1323 /// and the sender should have permission to edit those properties.1324 ///1325 /// This function fires an event for each property change.1326 /// In case of an error, all the changes (including the events) will be reverted1327 /// since the function is transactional.1328 #[allow(clippy::too_many_arguments)]1329 pub fn modify_token_properties<FTO, FTE>(1330 collection: &CollectionHandle<T>,1331 sender: &T::CrossAccountId,1332 token_id: TokenId,1333 is_token_exist: &mut LazyValue<bool, FTE>,1334 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1335 mut stored_properties: TokenProperties,1336 is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,1337 set_token_properties: impl FnOnce(TokenProperties),1338 log: evm_coder::ethereum::Log,1339 ) -> DispatchResult1340 where1341 FTO: FnOnce() -> Result<bool, DispatchError>,1342 FTE: FnOnce() -> bool,1343 {1344 let mut is_collection_admin = LazyValue::new(|| collection.is_owner_or_admin(sender));1345 let mut permissions = LazyValue::new(|| Self::property_permissions(collection.id));13461347 let mut changed = false;1348 for (key, value) in properties_updates {1349 let permission = permissions1350 .value()1351 .get(&key)1352 .cloned()1353 .unwrap_or_else(PropertyPermission::none);13541355 let property_exists = stored_properties.get(&key).is_some();13561357 match permission {1358 PropertyPermission { mutable: false, .. } if property_exists => {1359 return Err(<Error<T>>::NoPermission.into());1360 }13611362 PropertyPermission {1363 collection_admin,1364 token_owner,1365 ..1366 } => check_token_permissions::<T, _, FTO, FTE>(1367 collection_admin,1368 token_owner,1369 &mut is_collection_admin,1370 is_token_owner,1371 is_token_exist,1372 )?,1373 }13741375 match value {1376 Some(value) => {1377 stored_properties1378 .try_set(key.clone(), value)1379 .map_err(<Error<T>>::from)?;13801381 Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1382 }1383 None => {1384 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13851386 Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1387 }1388 }13891390 changed = true;1391 }13921393 if changed {1394 <PalletEvm<T>>::deposit_log(log);1395 set_token_properties(stored_properties);1396 }13971398 Ok(())1399 }14001401 /// Sets or unsets the approval of a given operator.1402 ///1403 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1404 /// - `owner`: Token owner1405 /// - `operator`: Operator1406 /// - `approve`: Should operator status be granted or revoked?1407 pub fn set_allowance_for_all(1408 collection: &CollectionHandle<T>,1409 owner: &T::CrossAccountId,1410 operator: &T::CrossAccountId,1411 approve: bool,1412 set_allowance: impl FnOnce(),1413 log: evm_coder::ethereum::Log,1414 ) -> DispatchResult {1415 if collection.permissions.access() == AccessMode::AllowList {1416 collection.check_allowlist(owner)?;1417 collection.check_allowlist(operator)?;1418 }14191420 Self::ensure_correct_receiver(operator)?;14211422 set_allowance();14231424 <PalletEvm<T>>::deposit_log(log);1425 Self::deposit_event(Event::ApprovedForAll(1426 collection.id,1427 owner.clone(),1428 operator.clone(),1429 approve,1430 ));1431 Ok(())1432 }14331434 /// Set collection property.1435 ///1436 /// * `collection` - Collection handler.1437 /// * `sender` - The owner or administrator of the collection.1438 /// * `property` - The property to set.1439 pub fn set_collection_property(1440 collection: &CollectionHandle<T>,1441 sender: &T::CrossAccountId,1442 property: Property,1443 ) -> DispatchResult {1444 Self::set_collection_properties(collection, sender, [property].into_iter())1445 }14461447 /// Set a scoped collection property, where the scope is a special prefix1448 /// prohibiting a user access to change the property directly.1449 ///1450 /// * `collection_id` - ID of the collection for which the property is being set.1451 /// * `scope` - Property scope.1452 /// * `property` - The property to set.1453 pub fn set_scoped_collection_property(1454 collection_id: CollectionId,1455 scope: PropertyScope,1456 property: Property,1457 ) -> DispatchResult {1458 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1459 properties.try_scoped_set(scope, property.key, property.value)1460 })1461 .map_err(<Error<T>>::from)?;14621463 Ok(())1464 }14651466 /// Set scoped collection properties, where the scope is a special prefix1467 /// prohibiting a user access to change the properties directly.1468 ///1469 /// * `collection_id` - ID of the collection for which the properties is being set.1470 /// * `scope` - Property scope.1471 /// * `properties` - The properties to set.1472 pub fn set_scoped_collection_properties(1473 collection_id: CollectionId,1474 scope: PropertyScope,1475 properties: impl Iterator<Item = Property>,1476 ) -> DispatchResult {1477 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1478 stored_properties.try_scoped_set_from_iter(scope, properties)1479 })1480 .map_err(<Error<T>>::from)?;14811482 Ok(())1483 }14841485 /// Set collection properties.1486 ///1487 /// * `collection` - Collection handler.1488 /// * `sender` - The owner or administrator of the collection.1489 /// * `properties` - The properties to set.1490 pub fn set_collection_properties(1491 collection: &CollectionHandle<T>,1492 sender: &T::CrossAccountId,1493 properties: impl Iterator<Item = Property>,1494 ) -> DispatchResult {1495 Self::modify_collection_properties(1496 collection,1497 sender,1498 properties.map(|property| (property.key, Some(property.value))),1499 )1500 }15011502 /// Delete collection property.1503 ///1504 /// * `collection` - Collection handler.1505 /// * `sender` - The owner or administrator of the collection.1506 /// * `property` - The property to delete.1507 pub fn delete_collection_property(1508 collection: &CollectionHandle<T>,1509 sender: &T::CrossAccountId,1510 property_key: PropertyKey,1511 ) -> DispatchResult {1512 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1513 }15141515 /// Delete collection properties.1516 ///1517 /// * `collection` - Collection handler.1518 /// * `sender` - The owner or administrator of the collection.1519 /// * `properties` - The properties to delete.1520 pub fn delete_collection_properties(1521 collection: &CollectionHandle<T>,1522 sender: &T::CrossAccountId,1523 property_keys: impl Iterator<Item = PropertyKey>,1524 ) -> DispatchResult {1525 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1526 }15271528 /// Set collection propetry permission without any checks.1529 ///1530 /// Used for migrations.1531 ///1532 /// * `collection` - Collection handler.1533 /// * `property_permissions` - Property permissions.1534 pub fn set_property_permission_unchecked(1535 collection: CollectionId,1536 property_permission: PropertyKeyPermission,1537 ) -> DispatchResult {1538 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1539 permissions.try_set(property_permission.key, property_permission.permission)1540 })1541 .map_err(<Error<T>>::from)?;1542 Ok(())1543 }15441545 /// Set collection property permission.1546 ///1547 /// * `collection` - Collection handler.1548 /// * `sender` - The owner or administrator of the collection.1549 /// * `property_permission` - Property permission.1550 pub fn set_property_permission(1551 collection: &CollectionHandle<T>,1552 sender: &T::CrossAccountId,1553 property_permission: PropertyKeyPermission,1554 ) -> DispatchResult {1555 Self::set_scoped_property_permission(1556 collection,1557 sender,1558 PropertyScope::None,1559 property_permission,1560 )1561 }15621563 /// Set collection property permission with scope.1564 ///1565 /// * `collection` - Collection handler.1566 /// * `sender` - The owner or administrator of the collection.1567 /// * `scope` - Property scope.1568 /// * `property_permission` - Property permission.1569 pub fn set_scoped_property_permission(1570 collection: &CollectionHandle<T>,1571 sender: &T::CrossAccountId,1572 scope: PropertyScope,1573 property_permission: PropertyKeyPermission,1574 ) -> DispatchResult {1575 collection.check_is_owner_or_admin(sender)?;15761577 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1578 let current_permission = all_permissions.get(&property_permission.key);1579 if matches![1580 current_permission,1581 Some(PropertyPermission { mutable: false, .. })1582 ] {1583 return Err(<Error<T>>::NoPermission.into());1584 }15851586 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1587 let property_permission = property_permission.clone();1588 permissions.try_scoped_set(1589 scope,1590 property_permission.key,1591 property_permission.permission,1592 )1593 })1594 .map_err(<Error<T>>::from)?;15951596 Self::deposit_event(Event::PropertyPermissionSet(1597 collection.id,1598 property_permission.key,1599 ));1600 <PalletEvm<T>>::deposit_log(1601 erc::CollectionHelpersEvents::CollectionChanged {1602 collection_id: eth::collection_id_to_address(collection.id),1603 }1604 .to_log(T::ContractAddress::get()),1605 );16061607 Ok(())1608 }16091610 /// Set token property permission.1611 ///1612 /// * `collection` - Collection handler.1613 /// * `sender` - The owner or administrator of the collection.1614 /// * `property_permissions` - Property permissions.1615 #[transactional]1616 pub fn set_token_property_permissions(1617 collection: &CollectionHandle<T>,1618 sender: &T::CrossAccountId,1619 property_permissions: Vec<PropertyKeyPermission>,1620 ) -> DispatchResult {1621 Self::set_scoped_token_property_permissions(1622 collection,1623 sender,1624 PropertyScope::None,1625 property_permissions,1626 )1627 }16281629 /// Set token property permission with scope.1630 ///1631 /// * `collection` - Collection handler.1632 /// * `sender` - The owner or administrator of the collection.1633 /// * `scope` - Property scope.1634 /// * `property_permissions` - Property permissions.1635 #[transactional]1636 pub fn set_scoped_token_property_permissions(1637 collection: &CollectionHandle<T>,1638 sender: &T::CrossAccountId,1639 scope: PropertyScope,1640 property_permissions: Vec<PropertyKeyPermission>,1641 ) -> DispatchResult {1642 for prop_pemission in property_permissions {1643 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1644 }16451646 Ok(())1647 }16481649 /// Get collection property.1650 pub fn get_collection_property(1651 collection_id: CollectionId,1652 key: &PropertyKey,1653 ) -> Option<PropertyValue> {1654 Self::collection_properties(collection_id).get(key).cloned()1655 }16561657 /// Convert byte vector to property key vector.1658 pub fn bytes_keys_to_property_keys(1659 keys: Vec<Vec<u8>>,1660 ) -> Result<Vec<PropertyKey>, DispatchError> {1661 keys.into_iter()1662 .map(|key| -> Result<PropertyKey, DispatchError> {1663 key.try_into()1664 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1665 })1666 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1667 }16681669 /// Get properties according to given keys.1670 pub fn filter_collection_properties(1671 collection_id: CollectionId,1672 keys: Option<Vec<PropertyKey>>,1673 ) -> Result<Vec<Property>, DispatchError> {1674 let properties = Self::collection_properties(collection_id);16751676 let properties = keys1677 .map(|keys| {1678 keys.into_iter()1679 .filter_map(|key| {1680 properties.get(&key).map(|value| Property {1681 key,1682 value: value.clone(),1683 })1684 })1685 .collect()1686 })1687 .unwrap_or_else(|| {1688 properties1689 .into_iter()1690 .map(|(key, value)| Property { key, value })1691 .collect()1692 });16931694 Ok(properties)1695 }16961697 /// Get property permissions according to given keys.1698 pub fn filter_property_permissions(1699 collection_id: CollectionId,1700 keys: Option<Vec<PropertyKey>>,1701 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1702 let permissions = Self::property_permissions(collection_id);17031704 let key_permissions = keys1705 .map(|keys| {1706 keys.into_iter()1707 .filter_map(|key| {1708 permissions1709 .get(&key)1710 .map(|permission| PropertyKeyPermission {1711 key,1712 permission: permission.clone(),1713 })1714 })1715 .collect()1716 })1717 .unwrap_or_else(|| {1718 permissions1719 .into_iter()1720 .map(|(key, permission)| PropertyKeyPermission { key, permission })1721 .collect()1722 });17231724 Ok(key_permissions)1725 }17261727 /// Toggle `user` participation in the `collection`'s allow list.1728 /// #### Store read/writes1729 /// 1 writes1730 pub fn toggle_allowlist(1731 collection: &CollectionHandle<T>,1732 sender: &T::CrossAccountId,1733 user: &T::CrossAccountId,1734 allowed: bool,1735 ) -> DispatchResult {1736 collection.check_is_owner_or_admin(sender)?;17371738 // =========17391740 if allowed {1741 <Allowlist<T>>::insert((collection.id, user), true);1742 Self::deposit_event(Event::<T>::AllowListAddressAdded(1743 collection.id,1744 user.clone(),1745 ));1746 } else {1747 <Allowlist<T>>::remove((collection.id, user));1748 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1749 collection.id,1750 user.clone(),1751 ));1752 }17531754 <PalletEvm<T>>::deposit_log(1755 erc::CollectionHelpersEvents::CollectionChanged {1756 collection_id: eth::collection_id_to_address(collection.id),1757 }1758 .to_log(T::ContractAddress::get()),1759 );17601761 Ok(())1762 }17631764 /// Toggle `user` participation in the `collection`'s admin list.1765 /// #### Store read/writes1766 /// 2 reads, 2 writes1767 pub fn toggle_admin(1768 collection: &CollectionHandle<T>,1769 sender: &T::CrossAccountId,1770 user: &T::CrossAccountId,1771 admin: bool,1772 ) -> DispatchResult {1773 collection.check_is_internal()?;1774 collection.check_is_owner(sender)?;17751776 let is_admin = <IsAdmin<T>>::get((collection.id, user));1777 if is_admin == admin {1778 if admin {1779 return Ok(());1780 } else {1781 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1782 }1783 }1784 let amount = <AdminAmount<T>>::get(collection.id);17851786 // =========17871788 if admin {1789 let amount = amount1790 .checked_add(1)1791 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1792 ensure!(1793 amount <= Self::collection_admins_limit(),1794 <Error<T>>::CollectionAdminCountExceeded,1795 );17961797 <AdminAmount<T>>::insert(collection.id, amount);1798 <IsAdmin<T>>::insert((collection.id, user), true);17991800 Self::deposit_event(Event::<T>::CollectionAdminAdded(1801 collection.id,1802 user.clone(),1803 ));1804 } else {1805 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1806 <IsAdmin<T>>::remove((collection.id, user));18071808 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1809 collection.id,1810 user.clone(),1811 ));1812 }18131814 <PalletEvm<T>>::deposit_log(1815 erc::CollectionHelpersEvents::CollectionChanged {1816 collection_id: eth::collection_id_to_address(collection.id),1817 }1818 .to_log(T::ContractAddress::get()),1819 );18201821 Ok(())1822 }18231824 /// Update collection limits.1825 pub fn update_limits(1826 user: &T::CrossAccountId,1827 collection: &mut CollectionHandle<T>,1828 new_limit: CollectionLimits,1829 ) -> DispatchResult {1830 collection.check_is_internal()?;1831 collection.check_is_owner_or_admin(user)?;18321833 collection.limits =1834 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;18351836 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1837 <PalletEvm<T>>::deposit_log(1838 erc::CollectionHelpersEvents::CollectionChanged {1839 collection_id: eth::collection_id_to_address(collection.id),1840 }1841 .to_log(T::ContractAddress::get()),1842 );18431844 collection.save()1845 }18461847 /// Merge set fields from `new_limit` to `old_limit`.1848 fn clamp_limits(1849 mode: CollectionMode,1850 old_limit: &CollectionLimits,1851 mut new_limit: CollectionLimits,1852 ) -> Result<CollectionLimits, DispatchError> {1853 let limits = old_limit;1854 limit_default!(old_limit, new_limit,1855 account_token_ownership_limit => ensure!(1856 new_limit <= MAX_TOKEN_OWNERSHIP,1857 <Error<T>>::CollectionLimitBoundsExceeded,1858 ),1859 sponsored_data_size => ensure!(1860 new_limit <= CUSTOM_DATA_LIMIT,1861 <Error<T>>::CollectionLimitBoundsExceeded,1862 ),18631864 sponsored_data_rate_limit => {},1865 token_limit => ensure!(1866 old_limit >= new_limit && new_limit > 0,1867 <Error<T>>::CollectionTokenLimitExceeded1868 ),18691870 sponsor_transfer_timeout(match mode {1871 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1872 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1873 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1874 }) => ensure!(1875 new_limit <= MAX_SPONSOR_TIMEOUT,1876 <Error<T>>::CollectionLimitBoundsExceeded,1877 ),1878 sponsor_approve_timeout => {},1879 owner_can_transfer => ensure!(1880 !limits.owner_can_transfer_instaled() ||1881 old_limit || !new_limit,1882 <Error<T>>::OwnerPermissionsCantBeReverted,1883 ),1884 owner_can_destroy => ensure!(1885 old_limit || !new_limit,1886 <Error<T>>::OwnerPermissionsCantBeReverted,1887 ),1888 transfers_enabled => {},1889 );1890 Ok(new_limit)1891 }18921893 /// Update collection permissions.1894 pub fn update_permissions(1895 user: &T::CrossAccountId,1896 collection: &mut CollectionHandle<T>,1897 new_permission: CollectionPermissions,1898 ) -> DispatchResult {1899 collection.check_is_internal()?;1900 collection.check_is_owner_or_admin(user)?;1901 collection.permissions = Self::clamp_permissions(1902 collection.mode.clone(),1903 &collection.permissions,1904 new_permission,1905 )?;19061907 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1908 <PalletEvm<T>>::deposit_log(1909 erc::CollectionHelpersEvents::CollectionChanged {1910 collection_id: eth::collection_id_to_address(collection.id),1911 }1912 .to_log(T::ContractAddress::get()),1913 );19141915 collection.save()1916 }19171918 /// Merge set fields from `new_permission` to `old_permission`.1919 fn clamp_permissions(1920 _mode: CollectionMode,1921 old_permission: &CollectionPermissions,1922 mut new_permission: CollectionPermissions,1923 ) -> Result<CollectionPermissions, DispatchError> {1924 limit_default_clone!(old_permission, new_permission,1925 access => {},1926 mint_mode => {},1927 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1928 );1929 Ok(new_permission)1930 }19311932 /// Repair possibly broken properties of a collection.1933 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1934 CollectionProperties::<T>::mutate(collection_id, |properties| {1935 properties.recompute_consumed_space();1936 });19371938 Ok(())1939 }1940}19411942/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1943#[macro_export]1944macro_rules! unsupported {1945 ($runtime:path) => {1946 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1947 };1948}19491950/// Return weights for various worst-case operations.1951pub trait CommonWeightInfo<CrossAccountId> {1952 /// Weight of item creation.1953 fn create_item(data: &CreateItemData) -> Weight {1954 Self::create_multiple_items(from_ref(data))1955 }19561957 /// Weight of items creation.1958 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19591960 /// Weight of items creation.1961 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19621963 /// The weight of the burning item.1964 fn burn_item() -> Weight;19651966 /// Property setting weight.1967 ///1968 /// * `amount`- The number of properties to set.1969 fn set_collection_properties(amount: u32) -> Weight;19701971 /// Collection property deletion weight.1972 ///1973 /// * `amount`- The number of properties to set.1974 fn delete_collection_properties(amount: u32) -> Weight;19751976 /// Token property setting weight.1977 ///1978 /// * `amount`- The number of properties to set.1979 fn set_token_properties(amount: u32) -> Weight;19801981 /// Token property deletion weight.1982 ///1983 /// * `amount`- The number of properties to delete.1984 fn delete_token_properties(amount: u32) -> Weight;19851986 /// Token property permissions set weight.1987 ///1988 /// * `amount`- The number of property permissions to set.1989 fn set_token_property_permissions(amount: u32) -> Weight;19901991 /// Transfer price of the token or its parts.1992 fn transfer() -> Weight;19931994 /// The price of setting the permission of the operation from another user.1995 fn approve() -> Weight;19961997 /// The price of setting the permission of the operation from another user for eth mirror.1998 fn approve_from() -> Weight;19992000 /// Transfer price from another user.2001 fn transfer_from() -> Weight;20022003 /// The price of burning a token from another user.2004 fn burn_from() -> Weight;20052006 /// Differs from burn_item in case of Fungible and Refungible, as it should burn2007 /// whole users's balance.2008 ///2009 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead2010 fn burn_recursively_self_raw() -> Weight;20112012 /// Cost of iterating over `amount` children while burning, without counting child burning itself.2013 ///2014 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead2015 fn burn_recursively_breadth_raw(amount: u32) -> Weight;20162017 /// The price of recursive burning a token.2018 ///2019 /// `max_selfs` - The maximum burning weight of the token itself.2020 /// `max_breadth` - The maximum number of nested tokens to burn.2021 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {2022 Self::burn_recursively_self_raw()2023 .saturating_mul(max_selfs.max(1) as u64)2024 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))2025 }20262027 /// The price of retrieving token owner2028 fn token_owner() -> Weight;20292030 /// The price of setting approval for all2031 fn set_allowance_for_all() -> Weight;20322033 /// The price of repairing an item.2034 fn force_repair_item() -> Weight;2035}20362037/// Weight info extension trait for refungible pallet.2038pub trait RefungibleExtensionsWeightInfo {2039 /// Weight of token repartition.2040 fn repartition() -> Weight;2041}20422043/// Common collection operations.2044///2045/// It wraps methods in Fungible, Nonfungible and Refungible pallets2046/// and adds weight info.2047pub trait CommonCollectionOperations<T: Config> {2048 /// Create token.2049 ///2050 /// * `sender` - The user who mint the token and pays for the transaction.2051 /// * `to` - The user who will own the token.2052 /// * `data` - Token data.2053 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2054 fn create_item(2055 &self,2056 sender: T::CrossAccountId,2057 to: T::CrossAccountId,2058 data: CreateItemData,2059 nesting_budget: &dyn Budget,2060 ) -> DispatchResultWithPostInfo;20612062 /// Create multiple tokens.2063 ///2064 /// * `sender` - The user who mint the token and pays for the transaction.2065 /// * `to` - The user who will own the token.2066 /// * `data` - Token data.2067 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2068 fn create_multiple_items(2069 &self,2070 sender: T::CrossAccountId,2071 to: T::CrossAccountId,2072 data: Vec<CreateItemData>,2073 nesting_budget: &dyn Budget,2074 ) -> DispatchResultWithPostInfo;20752076 /// Create multiple tokens.2077 ///2078 /// * `sender` - The user who mint the token and pays for the transaction.2079 /// * `to` - The user who will own the token.2080 /// * `data` - Token data.2081 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2082 fn create_multiple_items_ex(2083 &self,2084 sender: T::CrossAccountId,2085 data: CreateItemExData<T::CrossAccountId>,2086 nesting_budget: &dyn Budget,2087 ) -> DispatchResultWithPostInfo;20882089 /// Burn token.2090 ///2091 /// * `sender` - The user who owns the token.2092 /// * `token` - Token id that will burned.2093 /// * `amount` - The number of parts of the token that will be burned.2094 fn burn_item(2095 &self,2096 sender: T::CrossAccountId,2097 token: TokenId,2098 amount: u128,2099 ) -> DispatchResultWithPostInfo;21002101 /// Burn token and all nested tokens recursievly.2102 ///2103 /// * `sender` - The user who owns the token.2104 /// * `token` - Token id that will burned.2105 /// * `self_budget` - The budget that can be spent on burning tokens.2106 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2107 fn burn_item_recursively(2108 &self,2109 sender: T::CrossAccountId,2110 token: TokenId,2111 self_budget: &dyn Budget,2112 breadth_budget: &dyn Budget,2113 ) -> DispatchResultWithPostInfo;21142115 /// Set collection properties.2116 ///2117 /// * `sender` - Must be either the owner of the collection or its admin.2118 /// * `properties` - Properties to be set.2119 fn set_collection_properties(2120 &self,2121 sender: T::CrossAccountId,2122 properties: Vec<Property>,2123 ) -> DispatchResultWithPostInfo;21242125 /// Delete collection properties.2126 ///2127 /// * `sender` - Must be either the owner of the collection or its admin.2128 /// * `properties` - The properties to be removed.2129 fn delete_collection_properties(2130 &self,2131 sender: &T::CrossAccountId,2132 property_keys: Vec<PropertyKey>,2133 ) -> DispatchResultWithPostInfo;21342135 /// Set token properties.2136 ///2137 /// The appropriate [`PropertyPermission`] for the token property2138 /// must be set with [`Self::set_token_property_permissions`].2139 ///2140 /// * `sender` - Must be either the owner of the token or its admin.2141 /// * `token_id` - The token for which the properties are being set.2142 /// * `properties` - Properties to be set.2143 /// * `budget` - Budget for setting properties.2144 fn set_token_properties(2145 &self,2146 sender: T::CrossAccountId,2147 token_id: TokenId,2148 properties: Vec<Property>,2149 budget: &dyn Budget,2150 ) -> DispatchResultWithPostInfo;21512152 /// Remove token properties.2153 ///2154 /// The appropriate [`PropertyPermission`] for the token property2155 /// must be set with [`Self::set_token_property_permissions`].2156 ///2157 /// * `sender` - Must be either the owner of the token or its admin.2158 /// * `token_id` - The token for which the properties are being remove.2159 /// * `property_keys` - Keys to remove corresponding properties.2160 /// * `budget` - Budget for removing properties.2161 fn delete_token_properties(2162 &self,2163 sender: T::CrossAccountId,2164 token_id: TokenId,2165 property_keys: Vec<PropertyKey>,2166 budget: &dyn Budget,2167 ) -> DispatchResultWithPostInfo;21682169 /// Set token property permissions.2170 ///2171 /// * `sender` - Must be either the owner of the token or its admin.2172 /// * `token_id` - The token for which the properties are being set.2173 /// * `property_permissions` - Property permissions to be set.2174 /// * `budget` - Budget for setting properties.2175 fn set_token_property_permissions(2176 &self,2177 sender: &T::CrossAccountId,2178 property_permissions: Vec<PropertyKeyPermission>,2179 ) -> DispatchResultWithPostInfo;21802181 /// Transfer amount of token pieces.2182 ///2183 /// * `sender` - Donor user.2184 /// * `to` - Recepient user.2185 /// * `token` - The token of which parts are being sent.2186 /// * `amount` - The number of parts of the token that will be transferred.2187 /// * `budget` - The maximum budget that can be spent on the transfer.2188 fn transfer(2189 &self,2190 sender: T::CrossAccountId,2191 to: T::CrossAccountId,2192 token: TokenId,2193 amount: u128,2194 budget: &dyn Budget,2195 ) -> DispatchResultWithPostInfo;21962197 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2198 ///2199 /// * `sender` - The user who grants access to the token.2200 /// * `spender` - The user to whom the rights are granted.2201 /// * `token` - The token to which access is granted.2202 /// * `amount` - The amount of pieces that another user can dispose of.2203 fn approve(2204 &self,2205 sender: T::CrossAccountId,2206 spender: T::CrossAccountId,2207 token: TokenId,2208 amount: u128,2209 ) -> DispatchResultWithPostInfo;22102211 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2212 ///2213 /// * `sender` - The user who grants access to the token.2214 /// * `from` - Spender's eth mirror.2215 /// * `to` - The user to whom the rights are granted.2216 /// * `token` - The token to which access is granted.2217 /// * `amount` - The amount of pieces that another user can dispose of.2218 fn approve_from(2219 &self,2220 sender: T::CrossAccountId,2221 from: T::CrossAccountId,2222 to: T::CrossAccountId,2223 token: TokenId,2224 amount: u128,2225 ) -> DispatchResultWithPostInfo;22262227 /// Send parts of a token owned by another user.2228 ///2229 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2230 ///2231 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2232 /// * `from` - The user who owns the token.2233 /// * `to` - Recepient user.2234 /// * `token` - The token of which parts are being sent.2235 /// * `amount` - The number of parts of the token that will be transferred.2236 /// * `budget` - The maximum budget that can be spent on the transfer.2237 fn transfer_from(2238 &self,2239 sender: T::CrossAccountId,2240 from: T::CrossAccountId,2241 to: T::CrossAccountId,2242 token: TokenId,2243 amount: u128,2244 budget: &dyn Budget,2245 ) -> DispatchResultWithPostInfo;22462247 /// Burn parts of a token owned by another user.2248 ///2249 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2250 ///2251 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2252 /// * `from` - The user who owns the token.2253 /// * `token` - The token of which parts are being sent.2254 /// * `amount` - The number of parts of the token that will be transferred.2255 /// * `budget` - The maximum budget that can be spent on the burn.2256 fn burn_from(2257 &self,2258 sender: T::CrossAccountId,2259 from: T::CrossAccountId,2260 token: TokenId,2261 amount: u128,2262 budget: &dyn Budget,2263 ) -> DispatchResultWithPostInfo;22642265 /// Check permission to nest token.2266 ///2267 /// * `sender` - The user who initiated the check.2268 /// * `from` - The token that is checked for embedding.2269 /// * `under` - Token under which to check.2270 /// * `budget` - The maximum budget that can be spent on the check.2271 fn check_nesting(2272 &self,2273 sender: T::CrossAccountId,2274 from: (CollectionId, TokenId),2275 under: TokenId,2276 budget: &dyn Budget,2277 ) -> DispatchResult;22782279 /// Nest one token into another.2280 ///2281 /// * `under` - Token holder.2282 /// * `to_nest` - Nested token.2283 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22842285 /// Unnest token.2286 ///2287 /// * `under` - Token holder.2288 /// * `to_nest` - Token to unnest.2289 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22902291 /// Get all user tokens.2292 ///2293 /// * `account` - Account for which you need to get tokens.2294 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22952296 /// Get all the tokens in the collection.2297 fn collection_tokens(&self) -> Vec<TokenId>;22982299 /// Check if the token exists.2300 ///2301 /// * `token` - Id token to check.2302 fn token_exists(&self, token: TokenId) -> bool;23032304 /// Get the id of the last minted token.2305 fn last_token_id(&self) -> TokenId;23062307 /// Get the owner of the token.2308 ///2309 /// * `token` - The token for which you need to find out the owner.2310 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;23112312 /// Returns 10 tokens owners in no particular order.2313 ///2314 /// * `token` - The token for which you need to find out the owners.2315 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;23162317 /// Get the value of the token property by key.2318 ///2319 /// * `token` - Token with the property to get.2320 /// * `key` - Property name.2321 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;23222323 /// Get a set of token properties by key vector.2324 ///2325 /// * `token` - Token with the property to get.2326 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2327 /// then all properties are returned.2328 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;23292330 /// Amount of unique collection tokens2331 fn total_supply(&self) -> u32;23322333 /// Amount of different tokens account has.2334 ///2335 /// * `account` - The account for which need to get the balance.2336 fn account_balance(&self, account: T::CrossAccountId) -> u32;23372338 /// Amount of specific token account have.2339 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;23402341 /// Amount of token pieces2342 fn total_pieces(&self, token: TokenId) -> Option<u128>;23432344 /// Get the number of parts of the token that a trusted user can manage.2345 ///2346 /// * `sender` - Trusted user.2347 /// * `spender` - Owner of the token.2348 /// * `token` - The token for which to get the value.2349 fn allowance(2350 &self,2351 sender: T::CrossAccountId,2352 spender: T::CrossAccountId,2353 token: TokenId,2354 ) -> u128;23552356 /// Get extension for RFT collection.2357 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23582359 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2360 /// * `owner` - Token owner2361 /// * `operator` - Operator2362 /// * `approve` - Should operator status be granted or revoked?2363 fn set_allowance_for_all(2364 &self,2365 owner: T::CrossAccountId,2366 operator: T::CrossAccountId,2367 approve: bool,2368 ) -> DispatchResultWithPostInfo;23692370 /// Tells whether the given `owner` approves the `operator`.2371 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23722373 /// Repairs a possibly broken item.2374 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2375}23762377/// Extension for RFT collection.2378pub trait RefungibleExtensions<T>2379where2380 T: Config,2381{2382 /// Change the number of parts of the token.2383 ///2384 /// When the value changes down, this function is equivalent to burning parts of the token.2385 ///2386 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2387 /// * `token` - The token for which you want to change the number of parts.2388 /// * `amount` - The new value of the parts of the token.2389 fn repartition(2390 &self,2391 sender: &T::CrossAccountId,2392 token: TokenId,2393 amount: u128,2394 ) -> DispatchResultWithPostInfo;2395}23962397/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2398///2399/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2400pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2401 let post_info = PostDispatchInfo {2402 actual_weight: Some(weight),2403 pays_fee: Pays::Yes,2404 };2405 match res {2406 Ok(()) => Ok(post_info),2407 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2408 }2409}24102411impl<T: Config> From<PropertiesError> for Error<T> {2412 fn from(error: PropertiesError) -> Self {2413 match error {2414 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2415 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2416 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2417 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2418 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2419 }2420 }2421}24222423#[cfg(any(feature = "tests", test))]2424#[allow(missing_docs)]2425pub mod tests {2426 use crate::{DispatchResult, DispatchError, LazyValue, Config};24272428 const fn to_bool(u: u8) -> bool {2429 u != 02430 }24312432 #[derive(Debug)]2433 pub struct TestCase {2434 pub collection_admin: bool,2435 pub is_collection_admin: bool,2436 pub token_owner: bool,2437 pub is_token_owner: bool,2438 pub no_permission: bool,2439 }24402441 impl TestCase {2442 const fn new(2443 collection_admin: u8,2444 is_collection_admin: u8,2445 token_owner: u8,2446 is_token_owner: u8,2447 no_permission: u8,2448 ) -> Self {2449 Self {2450 collection_admin: to_bool(collection_admin),2451 is_collection_admin: to_bool(is_collection_admin),2452 token_owner: to_bool(token_owner),2453 is_token_owner: to_bool(is_token_owner),2454 no_permission: to_bool(no_permission),2455 }2456 }2457 }24582459 #[rustfmt::skip]2460 pub const TABLE: [TestCase; 16] = [2461 // ┌╴collection_admin2462 // │ ┌╴is_collection_admin2463 // │ │ ┌╴token_owner2464 // │ │ │ ┌╴is_token_ownership2465 // │ │ │ │ ┌╴no_permission2466 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2467 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2468 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2469 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2470 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2471 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2472 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2473 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2474 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2475 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2476 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2477 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2478 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2479 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2480 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2481 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2482 ];24832484 pub fn check_token_permissions<T, FCA, FTO, FTE>(2485 collection_admin_permitted: bool,2486 token_owner_permitted: bool,2487 is_collection_admin: &mut LazyValue<bool, FCA>,2488 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2489 check_token_existence: &mut LazyValue<bool, FTE>,2490 ) -> DispatchResult2491 where2492 T: Config,2493 FCA: FnOnce() -> bool,2494 FTO: FnOnce() -> Result<bool, DispatchError>,2495 FTE: FnOnce() -> bool,2496 {2497 crate::check_token_permissions::<T, FCA, FTO, FTE>(2498 collection_admin_permitted,2499 token_owner_permitted,2500 is_collection_admin,2501 check_token_ownership,2502 check_token_existence,2503 )2504 }2505}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//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59 marker::PhantomData,60};61use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};62use sp_std::vec::Vec;63use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};64use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},67 ensure,68 traits::{69 Get,70 fungible::{Balanced, Debt, Inspect},71 tokens::{Imbalance, Precision, Preservation},72 },73 dispatch::Pays,74 transactional, fail,75};76use up_data_structs::{77 AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, RpcCollectionFlags,78 CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH, COLLECTION_ADMINS_LIMIT, TokenId,79 TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP, CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT,80 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT,81 CUSTOM_DATA_LIMIT, CollectionLimits, CreateCollectionData, SponsorshipState, CreateItemExData,82 SponsoringRateLimit, budget::Budget, PhantomType, Property,83 CollectionProperties as CollectionPropertiesT, TokenProperties, PropertiesPermissionMap,84 PropertyKey, PropertyValue, PropertyPermission, PropertiesError, TokenOwnerError,85 PropertyKeyPermission, TokenData, TrySetProperty, PropertyScope, CollectionPermissions,86};87use up_pov_estimate_rpc::PovInfo;8889pub use pallet::*;90use sp_core::H160;91use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, traits::Zero};9293#[cfg(feature = "runtime-benchmarks")]94pub mod benchmarking;95pub mod dispatch;96pub mod erc;97pub mod eth;98pub mod helpers;99#[allow(missing_docs)]100pub mod weights;101102use weights::WeightInfo;103104/// Weight info.105pub type SelfWeightOf<T> = <T as Config>::WeightInfo;106107/// Collection handle contains information about collection data and id.108/// Also provides functionality to count consumed gas.109///110/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).111/// It allows to perform common operations and queries on any collection type,112/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].113#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]114pub struct CollectionHandle<T: Config> {115 /// Collection id116 pub id: CollectionId,117 collection: Collection<T::AccountId>,118 /// Substrate recorder for counting consumed gas119 pub recorder: SubstrateRecorder<T>,120}121122impl<T: Config> WithRecorder<T> for CollectionHandle<T> {123 fn recorder(&self) -> &SubstrateRecorder<T> {124 &self.recorder125 }126 fn into_recorder(self) -> SubstrateRecorder<T> {127 self.recorder128 }129}130131impl<T: Config> CollectionHandle<T> {132 /// Same as [CollectionHandle::new] but with an explicit gas limit.133 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {134 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))135 }136137 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].138 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {139 <CollectionById<T>>::get(id).map(|collection| Self {140 id,141 collection,142 recorder,143 })144 }145146 /// Retrives collection data from storage and creates collection handle with default parameters.147 /// If collection not found return `None`148 pub fn new(id: CollectionId) -> Option<Self> {149 Self::new_with_gas_limit(id, u64::MAX)150 }151152 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.153 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {154 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)155 }156157 /// Consume gas for reading.158 pub fn consume_store_reads(159 &self,160 reads: u64,161 ) -> pallet_evm_coder_substrate::execution::Result<()> {162 self.recorder().consume_store_reads(reads)163 }164165 /// Consume gas for writing.166 pub fn consume_store_writes(167 &self,168 writes: u64,169 ) -> pallet_evm_coder_substrate::execution::Result<()> {170 self.recorder().consume_store_writes(writes)171 }172173 /// Consume gas for reading and writing.174 pub fn consume_store_reads_and_writes(175 &self,176 reads: u64,177 writes: u64,178 ) -> pallet_evm_coder_substrate::execution::Result<()> {179 self.recorder()180 .consume_store_reads_and_writes(reads, writes)181 }182183 /// Save collection to storage.184 pub fn save(&self) -> DispatchResult {185 <CollectionById<T>>::insert(self.id, &self.collection);186 Ok(())187 }188189 /// Set collection sponsor.190 ///191 /// Unique collections allows sponsoring for certain actions.192 /// This method allows you to set the sponsor of the collection.193 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].194 pub fn set_sponsor(195 &mut self,196 sender: &T::CrossAccountId,197 sponsor: T::AccountId,198 ) -> DispatchResult {199 self.check_is_internal()?;200 self.check_is_owner_or_admin(sender)?;201202 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());203204 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));205 <PalletEvm<T>>::deposit_log(206 erc::CollectionHelpersEvents::CollectionChanged {207 collection_id: eth::collection_id_to_address(self.id),208 }209 .to_log(T::ContractAddress::get()),210 );211212 self.save()213 }214215 /// Force set `sponsor`.216 ///217 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation218 /// from the `sponsor` is not required.219 ///220 /// # Arguments221 ///222 /// * `sponsor`: ID of the account of the sponsor-to-be.223 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {224 self.check_is_internal()?;225226 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());227228 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));229 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));230 <PalletEvm<T>>::deposit_log(231 erc::CollectionHelpersEvents::CollectionChanged {232 collection_id: eth::collection_id_to_address(self.id),233 }234 .to_log(T::ContractAddress::get()),235 );236237 self.save()238 }239240 /// Confirm sponsorship241 ///242 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.243 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].244 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {245 self.check_is_internal()?;246 ensure!(247 self.collection.sponsorship.pending_sponsor() == Some(sender),248 Error::<T>::ConfirmSponsorshipFail249 );250251 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());252253 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));254 <PalletEvm<T>>::deposit_log(255 erc::CollectionHelpersEvents::CollectionChanged {256 collection_id: eth::collection_id_to_address(self.id),257 }258 .to_log(T::ContractAddress::get()),259 );260261 self.save()262 }263264 /// Remove collection sponsor.265 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {266 self.check_is_internal()?;267 self.check_is_owner_or_admin(sender)?;268269 self.collection.sponsorship = SponsorshipState::Disabled;270271 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));272 <PalletEvm<T>>::deposit_log(273 erc::CollectionHelpersEvents::CollectionChanged {274 collection_id: eth::collection_id_to_address(self.id),275 }276 .to_log(T::ContractAddress::get()),277 );278 self.save()279 }280281 /// Force remove `sponsor`.282 ///283 /// Differs from `remove_sponsor` in that284 /// it doesn't require consent from the `owner` of the collection.285 pub fn force_remove_sponsor(&mut self) -> DispatchResult {286 self.check_is_internal()?;287288 self.collection.sponsorship = SponsorshipState::Disabled;289290 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));291 <PalletEvm<T>>::deposit_log(292 erc::CollectionHelpersEvents::CollectionChanged {293 collection_id: eth::collection_id_to_address(self.id),294 }295 .to_log(T::ContractAddress::get()),296 );297 self.save()298 }299300 /// Checks that the collection was created with, and must be operated upon through **Unique API**.301 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.302 pub fn check_is_internal(&self) -> DispatchResult {303 if self.flags.external {304 return Err(<Error<T>>::CollectionIsExternal)?;305 }306307 Ok(())308 }309310 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.311 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.312 pub fn check_is_external(&self) -> DispatchResult {313 if !self.flags.external {314 return Err(<Error<T>>::CollectionIsInternal)?;315 }316317 Ok(())318 }319}320321impl<T: Config> Deref for CollectionHandle<T> {322 type Target = Collection<T::AccountId>;323324 fn deref(&self) -> &Self::Target {325 &self.collection326 }327}328329impl<T: Config> DerefMut for CollectionHandle<T> {330 fn deref_mut(&mut self) -> &mut Self::Target {331 &mut self.collection332 }333}334335impl<T: Config> CollectionHandle<T> {336 /// Checks if the `user` is the owner of the collection.337 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {338 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);339 Ok(())340 }341342 /// Returns **true** if the `user` is the owner or administrator of the collection.343 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {344 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))345 }346347 /// Checks if the `user` is the owner or administrator of the collection.348 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {349 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);350 Ok(())351 }352353 /// Returns **true** if354 /// * the `user`is a collection owner or admin355 /// * the collection limits allow the owner/admins to transfer/burn any collection token356 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {357 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)358 }359360 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.361 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {362 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)363 }364365 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.366 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {367 ensure!(368 <Allowlist<T>>::get((self.id, user)),369 <Error<T>>::AddressNotInAllowlist370 );371 Ok(())372 }373374 /// Changes collection owner to another account375 /// #### Store read/writes376 /// 1 writes377 pub fn change_owner(378 &mut self,379 caller: T::CrossAccountId,380 new_owner: T::CrossAccountId,381 ) -> DispatchResult {382 self.check_is_internal()?;383 self.check_is_owner(&caller)?;384 self.collection.owner = new_owner.as_sub().clone();385386 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(387 self.id,388 new_owner.as_sub().clone(),389 ));390 <PalletEvm<T>>::deposit_log(391 erc::CollectionHelpersEvents::CollectionChanged {392 collection_id: eth::collection_id_to_address(self.id),393 }394 .to_log(T::ContractAddress::get()),395 );396397 self.save()398 }399}400401#[frame_support::pallet]402pub mod pallet {403404 use super::*;405 use dispatch::CollectionDispatch;406 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};407 use up_data_structs::{TokenId, mapping::TokenAddressMapping};408 use scale_info::TypeInfo;409 use weights::WeightInfo;410411 #[pallet::config]412 pub trait Config:413 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo414 {415 /// Weight information for functions of this pallet.416 type WeightInfo: WeightInfo;417418 /// Events compatible with [`frame_system::Config::Event`].419 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;420421 /// Handler of accounts and payment.422 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;423424 /// Set price to create a collection.425 #[pallet::constant]426 type CollectionCreationPrice: Get<427 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,428 >;429430 /// Dispatcher of operations on collections.431 type CollectionDispatch: CollectionDispatch<Self>;432433 /// Account which holds the chain's treasury.434 type TreasuryAccountId: Get<Self::AccountId>;435436 /// Address under which the CollectionHelper contract would be available.437 #[pallet::constant]438 type ContractAddress: Get<H160>;439440 /// Mapper for token addresses to Ethereum addresses.441 type EvmTokenAddressMapping: TokenAddressMapping<H160>;442443 /// Mapper for token addresses to [`CrossAccountId`].444 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;445 }446447 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);448 /// Collection id for native fungible collction.449 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);450451 #[pallet::pallet]452 #[pallet::storage_version(STORAGE_VERSION)]453 pub struct Pallet<T>(_);454455 #[pallet::extra_constants]456 impl<T: Config> Pallet<T> {457 /// Maximum admins per collection.458 pub fn collection_admins_limit() -> u32 {459 COLLECTION_ADMINS_LIMIT460 }461 }462463 #[pallet::genesis_config]464 pub struct GenesisConfig<T>(PhantomData<T>);465466 #[cfg(feature = "std")]467 impl<T: Config> Default for GenesisConfig<T> {468 fn default() -> Self {469 Self(Default::default())470 }471 }472473 #[pallet::genesis_build]474 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {475 fn build(&self) {476 StorageVersion::new(1).put::<Pallet<T>>();477 }478 }479480 impl<T: Config> Pallet<T> {481 /// Helper function that handles deposit events482 pub fn deposit_event(event: Event<T>) {483 let event = <T as Config>::RuntimeEvent::from(event);484 let event = event.into();485 <frame_system::Pallet<T>>::deposit_event(event)486 }487 }488489 #[pallet::event]490 pub enum Event<T: Config> {491 /// New collection was created492 CollectionCreated(493 /// Globally unique identifier of newly created collection.494 CollectionId,495 /// [`CollectionMode`] converted into _u8_.496 u8,497 /// Collection owner.498 T::AccountId,499 ),500501 /// New collection was destroyed502 CollectionDestroyed(503 /// Globally unique identifier of collection.504 CollectionId,505 ),506507 /// New item was created.508 ItemCreated(509 /// Id of the collection where item was created.510 CollectionId,511 /// Id of an item. Unique within the collection.512 TokenId,513 /// Owner of newly created item514 T::CrossAccountId,515 /// Always 1 for NFT516 u128,517 ),518519 /// Collection item was burned.520 ItemDestroyed(521 /// Id of the collection where item was destroyed.522 CollectionId,523 /// Identifier of burned NFT.524 TokenId,525 /// Which user has destroyed its tokens.526 T::CrossAccountId,527 /// Amount of token pieces destroed. Always 1 for NFT.528 u128,529 ),530531 /// Item was transferred532 Transfer(533 /// Id of collection to which item is belong.534 CollectionId,535 /// Id of an item.536 TokenId,537 /// Original owner of item.538 T::CrossAccountId,539 /// New owner of item.540 T::CrossAccountId,541 /// Amount of token pieces transfered. Always 1 for NFT.542 u128,543 ),544545 /// Amount pieces of token owned by `sender` was approved for `spender`.546 Approved(547 /// Id of collection to which item is belong.548 CollectionId,549 /// Id of an item.550 TokenId,551 /// Original owner of item.552 T::CrossAccountId,553 /// Id for which the approval was granted.554 T::CrossAccountId,555 /// Amount of token pieces transfered. Always 1 for NFT.556 u128,557 ),558559 /// A `sender` approves operations on all owned tokens for `spender`.560 ApprovedForAll(561 /// Id of collection to which item is belong.562 CollectionId,563 /// Owner of a wallet.564 T::CrossAccountId,565 /// Id for which operator status was granted or rewoked.566 T::CrossAccountId,567 /// Is operator status granted or revoked?568 bool,569 ),570571 /// The colletion property has been added or edited.572 CollectionPropertySet(573 /// Id of collection to which property has been set.574 CollectionId,575 /// The property that was set.576 PropertyKey,577 ),578579 /// The property has been deleted.580 CollectionPropertyDeleted(581 /// Id of collection to which property has been deleted.582 CollectionId,583 /// The property that was deleted.584 PropertyKey,585 ),586587 /// The token property has been added or edited.588 TokenPropertySet(589 /// Identifier of the collection whose token has the property set.590 CollectionId,591 /// The token for which the property was set.592 TokenId,593 /// The property that was set.594 PropertyKey,595 ),596597 /// The token property has been deleted.598 TokenPropertyDeleted(599 /// Identifier of the collection whose token has the property deleted.600 CollectionId,601 /// The token for which the property was deleted.602 TokenId,603 /// The property that was deleted.604 PropertyKey,605 ),606607 /// The token property permission of a collection has been set.608 PropertyPermissionSet(609 /// ID of collection to which property permission has been set.610 CollectionId,611 /// The property permission that was set.612 PropertyKey,613 ),614615 /// Address was added to the allow list.616 AllowListAddressAdded(617 /// ID of the affected collection.618 CollectionId,619 /// Address of the added account.620 T::CrossAccountId,621 ),622623 /// Address was removed from the allow list.624 AllowListAddressRemoved(625 /// ID of the affected collection.626 CollectionId,627 /// Address of the removed account.628 T::CrossAccountId,629 ),630631 /// Collection admin was added.632 CollectionAdminAdded(633 /// ID of the affected collection.634 CollectionId,635 /// Admin address.636 T::CrossAccountId,637 ),638639 /// Collection admin was removed.640 CollectionAdminRemoved(641 /// ID of the affected collection.642 CollectionId,643 /// Removed admin address.644 T::CrossAccountId,645 ),646647 /// Collection limits were set.648 CollectionLimitSet(649 /// ID of the affected collection.650 CollectionId,651 ),652653 /// Collection owned was changed.654 CollectionOwnerChanged(655 /// ID of the affected collection.656 CollectionId,657 /// New owner address.658 T::AccountId,659 ),660661 /// Collection permissions were set.662 CollectionPermissionSet(663 /// ID of the affected collection.664 CollectionId,665 ),666667 /// Collection sponsor was set.668 CollectionSponsorSet(669 /// ID of the affected collection.670 CollectionId,671 /// New sponsor address.672 T::AccountId,673 ),674675 /// New sponsor was confirm.676 SponsorshipConfirmed(677 /// ID of the affected collection.678 CollectionId,679 /// New sponsor address.680 T::AccountId,681 ),682683 /// Collection sponsor was removed.684 CollectionSponsorRemoved(685 /// ID of the affected collection.686 CollectionId,687 ),688 }689690 #[pallet::error]691 pub enum Error<T> {692 /// This collection does not exist.693 CollectionNotFound,694 /// Sender parameter and item owner must be equal.695 MustBeTokenOwner,696 /// No permission to perform action697 NoPermission,698 /// Destroying only empty collections is allowed699 CantDestroyNotEmptyCollection,700 /// Collection is not in mint mode.701 PublicMintingNotAllowed,702 /// Address is not in allow list.703 AddressNotInAllowlist,704705 /// Collection name can not be longer than 63 char.706 CollectionNameLimitExceeded,707 /// Collection description can not be longer than 255 char.708 CollectionDescriptionLimitExceeded,709 /// Token prefix can not be longer than 15 char.710 CollectionTokenPrefixLimitExceeded,711 /// Total collections bound exceeded.712 TotalCollectionsLimitExceeded,713 /// Exceeded max admin count714 CollectionAdminCountExceeded,715 /// Collection limit bounds per collection exceeded716 CollectionLimitBoundsExceeded,717 /// Tried to enable permissions which are only permitted to be disabled718 OwnerPermissionsCantBeReverted,719 /// Collection settings not allowing items transferring720 TransferNotAllowed,721 /// Account token limit exceeded per collection722 AccountTokenLimitExceeded,723 /// Collection token limit exceeded724 CollectionTokenLimitExceeded,725 /// Metadata flag frozen726 MetadataFlagFrozen,727728 /// Item does not exist729 TokenNotFound,730 /// Item is balance not enough731 TokenValueTooLow,732 /// Requested value is more than the approved733 ApprovedValueTooLow,734 /// Tried to approve more than owned735 CantApproveMoreThanOwned,736 /// Only spending from eth mirror could be approved737 AddressIsNotEthMirror,738739 /// Can't transfer tokens to ethereum zero address740 AddressIsZero,741742 /// The operation is not supported743 UnsupportedOperation,744745 /// Insufficient funds to perform an action746 NotSufficientFounds,747748 /// User does not satisfy the nesting rule749 UserIsNotAllowedToNest,750 /// Only tokens from specific collections may nest tokens under this one751 SourceCollectionIsNotAllowedToNest,752753 /// Tried to store more data than allowed in collection field754 CollectionFieldSizeExceeded,755756 /// Tried to store more property data than allowed757 NoSpaceForProperty,758759 /// Tried to store more property keys than allowed760 PropertyLimitReached,761762 /// Property key is too long763 PropertyKeyIsTooLong,764765 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed766 InvalidCharacterInPropertyKey,767768 /// Empty property keys are forbidden769 EmptyPropertyKey,770771 /// Tried to access an external collection with an internal API772 CollectionIsExternal,773774 /// Tried to access an internal collection with an external API775 CollectionIsInternal,776777 /// This address is not set as sponsor, use setCollectionSponsor first.778 ConfirmSponsorshipFail,779780 /// The user is not an administrator.781 UserIsNotCollectionAdmin,782 }783784 /// Storage of the count of created collections. Essentially contains the last collection ID.785 #[pallet::storage]786 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;787788 /// Storage of the count of deleted collections.789 #[pallet::storage]790 pub type DestroyedCollectionCount<T> =791 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;792793 /// Storage of collection info.794 #[pallet::storage]795 pub type CollectionById<T> = StorageMap<796 Hasher = Blake2_128Concat,797 Key = CollectionId,798 Value = Collection<<T as frame_system::Config>::AccountId>,799 QueryKind = OptionQuery,800 >;801802 /// Storage of collection properties.803 #[pallet::storage]804 #[pallet::getter(fn collection_properties)]805 pub type CollectionProperties<T> = StorageMap<806 Hasher = Blake2_128Concat,807 Key = CollectionId,808 Value = CollectionPropertiesT,809 QueryKind = ValueQuery,810 >;811812 /// Storage of token property permissions of a collection.813 #[pallet::storage]814 #[pallet::getter(fn property_permissions)]815 pub type CollectionPropertyPermissions<T> = StorageMap<816 Hasher = Blake2_128Concat,817 Key = CollectionId,818 Value = PropertiesPermissionMap,819 QueryKind = ValueQuery,820 >;821822 /// Storage of the amount of collection admins.823 #[pallet::storage]824 pub type AdminAmount<T> = StorageMap<825 Hasher = Blake2_128Concat,826 Key = CollectionId,827 Value = u32,828 QueryKind = ValueQuery,829 >;830831 /// List of collection admins.832 #[pallet::storage]833 pub type IsAdmin<T: Config> = StorageNMap<834 Key = (835 Key<Blake2_128Concat, CollectionId>,836 Key<Blake2_128Concat, T::CrossAccountId>,837 ),838 Value = bool,839 QueryKind = ValueQuery,840 >;841842 /// Allowlisted collection users.843 #[pallet::storage]844 pub type Allowlist<T: Config> = StorageNMap<845 Key = (846 Key<Blake2_128Concat, CollectionId>,847 Key<Blake2_128Concat, T::CrossAccountId>,848 ),849 Value = bool,850 QueryKind = ValueQuery,851 >;852853 /// Not used by code, exists only to provide some types to metadata.854 #[pallet::storage]855 pub type DummyStorageValue<T: Config> = StorageValue<856 Value = (857 CollectionStats,858 CollectionId,859 TokenId,860 TokenChild,861 PhantomType<(862 TokenData<T::CrossAccountId>,863 RpcCollection<T::AccountId>,864 // PoV Estimate Info865 PovInfo,866 )>,867 ),868 QueryKind = OptionQuery,869 >;870}871872/// Value representation with delayed initialization time.873pub struct LazyValue<T, F: FnOnce() -> T> {874 value: Option<T>,875 f: Option<F>,876}877878impl<T, F: FnOnce() -> T> LazyValue<T, F> {879 /// Create a new LazyValue.880 pub fn new(f: F) -> Self {881 Self {882 value: None,883 f: Some(f),884 }885 }886887 /// Get the value. If it is called the first time, the value will be initialized.888 pub fn value(&mut self) -> &T {889 self.compute_value_if_not_already();890 self.value.as_ref().unwrap()891 }892893 /// Get the value. If it is called the first time, the value will be initialized.894 pub fn value_mut(&mut self) -> &mut T {895 self.compute_value_if_not_already();896 self.value.as_mut().unwrap()897 }898899 fn into_inner(mut self) -> T {900 self.compute_value_if_not_already();901 self.value.unwrap()902 }903904 /// Is value initialized?905 pub fn has_value(&self) -> bool {906 self.value.is_some()907 }908909 fn compute_value_if_not_already(&mut self) {910 if self.value.is_none() {911 self.value = Some(self.f.take().unwrap()())912 }913 }914}915916fn check_token_permissions<T, FCA, FTO, FTE>(917 collection_admin_permitted: bool,918 token_owner_permitted: bool,919 is_collection_admin: &mut LazyValue<bool, FCA>,920 is_token_owner: &mut LazyValue<Result<bool, DispatchError>, FTO>,921 is_token_exist: &mut LazyValue<bool, FTE>,922) -> DispatchResult923where924 T: Config,925 FCA: FnOnce() -> bool,926 FTO: FnOnce() -> Result<bool, DispatchError>,927 FTE: FnOnce() -> bool,928{929 if !(collection_admin_permitted && *is_collection_admin.value()930 || token_owner_permitted && (*is_token_owner.value())?)931 {932 fail!(<Error<T>>::NoPermission);933 }934935 let token_exist_due_to_owner_check_success =936 is_token_owner.has_value() && (*is_token_owner.value())?;937938 // If the token owner check has occurred and succeeded,939 // we know the token exists (otherwise, the owner check must fail).940 if !token_exist_due_to_owner_check_success {941 // If the token owner check didn't occur,942 // we must check the token's existence ourselves.943 if !is_token_exist.value() {944 fail!(<Error<T>>::TokenNotFound);945 }946 }947948 Ok(())949}950951impl<T: Config> Pallet<T> {952 /// Enshure that receiver address is correct.953 ///954 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.955 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {956 ensure!(957 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,958 <Error<T>>::AddressIsZero959 );960 Ok(())961 }962963 /// Get a vector of collection admins.964 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {965 <IsAdmin<T>>::iter_prefix((collection,))966 .map(|(a, _)| a)967 .collect()968 }969970 /// Get a vector of users allowed to mint tokens.971 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {972 <Allowlist<T>>::iter_prefix((collection,))973 .map(|(a, _)| a)974 .collect()975 }976977 /// Is `user` allowed to mint token in `collection`.978 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {979 <Allowlist<T>>::get((collection, user))980 }981982 /// Get statistics of collections.983 pub fn collection_stats() -> CollectionStats {984 let created = <CreatedCollectionCount<T>>::get();985 let destroyed = <DestroyedCollectionCount<T>>::get();986 CollectionStats {987 created: created.0,988 destroyed: destroyed.0,989 alive: created.0 - destroyed.0,990 }991 }992993 /// Get the effective limits for the collection.994 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {995 let collection = <CollectionById<T>>::get(collection)?;996 let limits = collection.limits;997 let effective_limits = CollectionLimits {998 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),999 sponsored_data_size: Some(limits.sponsored_data_size()),1000 sponsored_data_rate_limit: Some(1001 limits1002 .sponsored_data_rate_limit1003 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1004 ),1005 token_limit: Some(limits.token_limit()),1006 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1007 match collection.mode {1008 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1009 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1010 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1011 },1012 )),1013 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1014 owner_can_transfer: Some(limits.owner_can_transfer()),1015 owner_can_destroy: Some(limits.owner_can_destroy()),1016 transfers_enabled: Some(limits.transfers_enabled()),1017 };10181019 Some(effective_limits)1020 }10211022 /// Returns information about the `collection` adapted for rpc.1023 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1024 let Collection {1025 name,1026 description,1027 owner,1028 mode,1029 token_prefix,1030 sponsorship,1031 limits,1032 permissions,1033 flags,1034 } = <CollectionById<T>>::get(collection)?;10351036 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1037 .into_iter()1038 .map(|(key, permission)| PropertyKeyPermission { key, permission })1039 .collect();10401041 let properties = <CollectionProperties<T>>::get(collection)1042 .into_iter()1043 .map(|(key, value)| Property { key, value })1044 .collect();10451046 let permissions = CollectionPermissions {1047 access: Some(permissions.access()),1048 mint_mode: Some(permissions.mint_mode()),1049 nesting: Some(permissions.nesting().clone()),1050 };10511052 Some(RpcCollection {1053 name: name.into_inner(),1054 description: description.into_inner(),1055 owner,1056 mode,1057 token_prefix: token_prefix.into_inner(),1058 sponsorship,1059 limits,1060 permissions,1061 token_property_permissions,1062 properties,1063 read_only: flags.external,10641065 flags: RpcCollectionFlags {1066 foreign: flags.foreign,1067 erc721metadata: flags.erc721metadata,1068 },1069 })1070 }1071}10721073macro_rules! limit_default {1074 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1075 $(1076 if let Some($new) = $new.$field {1077 let $old = $old.$field($($arg)?);1078 let _ = $new;1079 let _ = $old;1080 $check1081 } else {1082 $new.$field = $old.$field1083 }1084 )*1085 }};1086}1087macro_rules! limit_default_clone {1088 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1089 $(1090 if let Some($new) = $new.$field.clone() {1091 let $old = $old.$field($($arg)?);1092 let _ = $new;1093 let _ = $old;1094 $check1095 } else {1096 $new.$field = $old.$field.clone()1097 }1098 )*1099 }};1100}11011102impl<T: Config> Pallet<T> {1103 /// Create new collection.1104 ///1105 /// * `owner` - The owner of the collection.1106 /// * `data` - Description of the created collection.1107 /// * `flags` - Extra flags to store.1108 pub fn init_collection(1109 owner: T::CrossAccountId,1110 payer: T::CrossAccountId,1111 data: CreateCollectionData<T::CrossAccountId>,1112 ) -> Result<CollectionId, DispatchError> {1113 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1114 Self::init_collection_internal(owner, payer, data)1115 }11161117 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.1118 pub fn init_foreign_collection(1119 owner: T::CrossAccountId,1120 payer: T::CrossAccountId,1121 mut data: CreateCollectionData<T::CrossAccountId>,1122 ) -> Result<CollectionId, DispatchError> {1123 data.flags.foreign = true;1124 let id = Self::init_collection_internal(owner, payer, data)?;1125 Ok(id)1126 }11271128 fn init_collection_internal(1129 owner: T::CrossAccountId,1130 payer: T::CrossAccountId,1131 data: CreateCollectionData<T::CrossAccountId>,1132 ) -> Result<CollectionId, DispatchError> {1133 {1134 ensure!(1135 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1136 Error::<T>::CollectionTokenPrefixLimitExceeded1137 );1138 }11391140 let created_count = <CreatedCollectionCount<T>>::get()1141 .01142 .checked_add(1)1143 .ok_or(ArithmeticError::Overflow)?;1144 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1145 let id = CollectionId(created_count);11461147 // bound Total number of collections1148 ensure!(1149 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1150 <Error<T>>::TotalCollectionsLimitExceeded1151 );11521153 // =========11541155 let collection = Collection {1156 owner: owner.as_sub().clone(),1157 name: data.name,1158 mode: data.mode.clone(),1159 description: data.description,1160 token_prefix: data.token_prefix,1161 sponsorship: data1162 .pending_sponsor1163 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1164 .unwrap_or_default(),1165 limits: data1166 .limits1167 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1168 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1169 permissions: data1170 .permissions1171 .map(|permissions| {1172 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1173 })1174 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1175 flags: data.flags,1176 };11771178 let mut collection_properties = CollectionPropertiesT::new();1179 collection_properties1180 .try_set_from_iter(data.properties.into_iter())1181 .map_err(<Error<T>>::from)?;11821183 CollectionProperties::<T>::insert(id, collection_properties);11841185 let mut token_props_permissions = PropertiesPermissionMap::new();1186 token_props_permissions1187 .try_set_from_iter(data.token_property_permissions.into_iter())1188 .map_err(<Error<T>>::from)?;11891190 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11911192 let mut admin_amount = 0u32;1193 for admin in data.admin_list.iter() {1194 if !<IsAdmin<T>>::get((id, admin)) {1195 <IsAdmin<T>>::insert((id, admin), true);1196 admin_amount = admin_amount1197 .checked_add(1)1198 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1199 }1200 }1201 ensure!(1202 admin_amount <= Self::collection_admins_limit(),1203 <Error<T>>::CollectionAdminCountExceeded,1204 );1205 <AdminAmount<T>>::insert(id, admin_amount);12061207 // Take a (non-refundable) deposit of collection creation1208 {1209 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1210 imbalance.subsume(<T as Config>::Currency::deposit(1211 &T::TreasuryAccountId::get(),1212 T::CollectionCreationPrice::get(),1213 Precision::Exact,1214 )?);1215 let credit =1216 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1217 .map_err(|_| Error::<T>::NotSufficientFounds)?;12181219 debug_assert!(credit.peek().is_zero())1220 }12211222 <CreatedCollectionCount<T>>::put(created_count);1223 <Pallet<T>>::deposit_event(Event::CollectionCreated(1224 id,1225 data.mode.id(),1226 owner.as_sub().clone(),1227 ));1228 <PalletEvm<T>>::deposit_log(1229 erc::CollectionHelpersEvents::CollectionCreated {1230 owner: *owner.as_eth(),1231 collection_id: eth::collection_id_to_address(id),1232 }1233 .to_log(T::ContractAddress::get()),1234 );1235 <CollectionById<T>>::insert(id, collection);1236 Ok(id)1237 }12381239 /// Destroy collection.1240 ///1241 /// * `collection` - Collection handler.1242 /// * `sender` - The owner or administrator of the collection.1243 pub fn destroy_collection(1244 collection: CollectionHandle<T>,1245 sender: &T::CrossAccountId,1246 ) -> DispatchResult {1247 ensure!(1248 collection.limits.owner_can_destroy(),1249 <Error<T>>::NoPermission,1250 );1251 collection.check_is_owner(sender)?;12521253 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1254 .01255 .checked_add(1)1256 .ok_or(ArithmeticError::Overflow)?;12571258 // =========12591260 <DestroyedCollectionCount<T>>::put(destroyed_collections);1261 <CollectionById<T>>::remove(collection.id);1262 <AdminAmount<T>>::remove(collection.id);1263 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1264 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1265 <CollectionProperties<T>>::remove(collection.id);12661267 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12681269 <PalletEvm<T>>::deposit_log(1270 erc::CollectionHelpersEvents::CollectionDestroyed {1271 collection_id: eth::collection_id_to_address(collection.id),1272 }1273 .to_log(T::ContractAddress::get()),1274 );1275 Ok(())1276 }12771278 /// This function sets or removes a collection properties according to1279 /// `properties_updates` contents:1280 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1281 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1282 ///1283 /// This function fires an event for each property change.1284 /// In case of an error, all the changes (including the events) will be reverted1285 /// since the function is transactional.1286 #[transactional]1287 fn modify_collection_properties(1288 collection: &CollectionHandle<T>,1289 sender: &T::CrossAccountId,1290 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1291 ) -> DispatchResult {1292 collection.check_is_owner_or_admin(sender)?;12931294 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12951296 for (key, value) in properties_updates {1297 match value {1298 Some(value) => {1299 stored_properties1300 .try_set(key.clone(), value)1301 .map_err(<Error<T>>::from)?;13021303 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1304 <PalletEvm<T>>::deposit_log(1305 erc::CollectionHelpersEvents::CollectionChanged {1306 collection_id: eth::collection_id_to_address(collection.id),1307 }1308 .to_log(T::ContractAddress::get()),1309 );1310 }1311 None => {1312 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13131314 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1315 <PalletEvm<T>>::deposit_log(1316 erc::CollectionHelpersEvents::CollectionChanged {1317 collection_id: eth::collection_id_to_address(collection.id),1318 }1319 .to_log(T::ContractAddress::get()),1320 );1321 }1322 }1323 }13241325 <CollectionProperties<T>>::set(collection.id, stored_properties);13261327 Ok(())1328 }13291330 /// Sets or unsets the approval of a given operator.1331 ///1332 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1333 /// - `owner`: Token owner1334 /// - `operator`: Operator1335 /// - `approve`: Should operator status be granted or revoked?1336 pub fn set_allowance_for_all(1337 collection: &CollectionHandle<T>,1338 owner: &T::CrossAccountId,1339 operator: &T::CrossAccountId,1340 approve: bool,1341 set_allowance: impl FnOnce(),1342 log: evm_coder::ethereum::Log,1343 ) -> DispatchResult {1344 if collection.permissions.access() == AccessMode::AllowList {1345 collection.check_allowlist(owner)?;1346 collection.check_allowlist(operator)?;1347 }13481349 Self::ensure_correct_receiver(operator)?;13501351 set_allowance();13521353 <PalletEvm<T>>::deposit_log(log);1354 Self::deposit_event(Event::ApprovedForAll(1355 collection.id,1356 owner.clone(),1357 operator.clone(),1358 approve,1359 ));1360 Ok(())1361 }13621363 /// Set collection property.1364 ///1365 /// * `collection` - Collection handler.1366 /// * `sender` - The owner or administrator of the collection.1367 /// * `property` - The property to set.1368 pub fn set_collection_property(1369 collection: &CollectionHandle<T>,1370 sender: &T::CrossAccountId,1371 property: Property,1372 ) -> DispatchResult {1373 Self::set_collection_properties(collection, sender, [property].into_iter())1374 }13751376 /// Set a scoped collection property, where the scope is a special prefix1377 /// prohibiting a user access to change the property directly.1378 ///1379 /// * `collection_id` - ID of the collection for which the property is being set.1380 /// * `scope` - Property scope.1381 /// * `property` - The property to set.1382 pub fn set_scoped_collection_property(1383 collection_id: CollectionId,1384 scope: PropertyScope,1385 property: Property,1386 ) -> DispatchResult {1387 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1388 properties.try_scoped_set(scope, property.key, property.value)1389 })1390 .map_err(<Error<T>>::from)?;13911392 Ok(())1393 }13941395 /// Set scoped collection properties, where the scope is a special prefix1396 /// prohibiting a user access to change the properties directly.1397 ///1398 /// * `collection_id` - ID of the collection for which the properties is being set.1399 /// * `scope` - Property scope.1400 /// * `properties` - The properties to set.1401 pub fn set_scoped_collection_properties(1402 collection_id: CollectionId,1403 scope: PropertyScope,1404 properties: impl Iterator<Item = Property>,1405 ) -> DispatchResult {1406 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1407 stored_properties.try_scoped_set_from_iter(scope, properties)1408 })1409 .map_err(<Error<T>>::from)?;14101411 Ok(())1412 }14131414 /// Set collection properties.1415 ///1416 /// * `collection` - Collection handler.1417 /// * `sender` - The owner or administrator of the collection.1418 /// * `properties` - The properties to set.1419 pub fn set_collection_properties(1420 collection: &CollectionHandle<T>,1421 sender: &T::CrossAccountId,1422 properties: impl Iterator<Item = Property>,1423 ) -> DispatchResult {1424 Self::modify_collection_properties(1425 collection,1426 sender,1427 properties.map(|property| (property.key, Some(property.value))),1428 )1429 }14301431 /// Delete collection property.1432 ///1433 /// * `collection` - Collection handler.1434 /// * `sender` - The owner or administrator of the collection.1435 /// * `property` - The property to delete.1436 pub fn delete_collection_property(1437 collection: &CollectionHandle<T>,1438 sender: &T::CrossAccountId,1439 property_key: PropertyKey,1440 ) -> DispatchResult {1441 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1442 }14431444 /// Delete collection properties.1445 ///1446 /// * `collection` - Collection handler.1447 /// * `sender` - The owner or administrator of the collection.1448 /// * `properties` - The properties to delete.1449 pub fn delete_collection_properties(1450 collection: &CollectionHandle<T>,1451 sender: &T::CrossAccountId,1452 property_keys: impl Iterator<Item = PropertyKey>,1453 ) -> DispatchResult {1454 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1455 }14561457 /// Set collection propetry permission without any checks.1458 ///1459 /// Used for migrations.1460 ///1461 /// * `collection` - Collection handler.1462 /// * `property_permissions` - Property permissions.1463 pub fn set_property_permission_unchecked(1464 collection: CollectionId,1465 property_permission: PropertyKeyPermission,1466 ) -> DispatchResult {1467 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1468 permissions.try_set(property_permission.key, property_permission.permission)1469 })1470 .map_err(<Error<T>>::from)?;1471 Ok(())1472 }14731474 /// Set collection property permission.1475 ///1476 /// * `collection` - Collection handler.1477 /// * `sender` - The owner or administrator of the collection.1478 /// * `property_permission` - Property permission.1479 pub fn set_property_permission(1480 collection: &CollectionHandle<T>,1481 sender: &T::CrossAccountId,1482 property_permission: PropertyKeyPermission,1483 ) -> DispatchResult {1484 Self::set_scoped_property_permission(1485 collection,1486 sender,1487 PropertyScope::None,1488 property_permission,1489 )1490 }14911492 /// Set collection property permission with scope.1493 ///1494 /// * `collection` - Collection handler.1495 /// * `sender` - The owner or administrator of the collection.1496 /// * `scope` - Property scope.1497 /// * `property_permission` - Property permission.1498 pub fn set_scoped_property_permission(1499 collection: &CollectionHandle<T>,1500 sender: &T::CrossAccountId,1501 scope: PropertyScope,1502 property_permission: PropertyKeyPermission,1503 ) -> DispatchResult {1504 collection.check_is_owner_or_admin(sender)?;15051506 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1507 let current_permission = all_permissions.get(&property_permission.key);1508 if matches![1509 current_permission,1510 Some(PropertyPermission { mutable: false, .. })1511 ] {1512 return Err(<Error<T>>::NoPermission.into());1513 }15141515 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1516 let property_permission = property_permission.clone();1517 permissions.try_scoped_set(1518 scope,1519 property_permission.key,1520 property_permission.permission,1521 )1522 })1523 .map_err(<Error<T>>::from)?;15241525 Self::deposit_event(Event::PropertyPermissionSet(1526 collection.id,1527 property_permission.key,1528 ));1529 <PalletEvm<T>>::deposit_log(1530 erc::CollectionHelpersEvents::CollectionChanged {1531 collection_id: eth::collection_id_to_address(collection.id),1532 }1533 .to_log(T::ContractAddress::get()),1534 );15351536 Ok(())1537 }15381539 /// Set token property permission.1540 ///1541 /// * `collection` - Collection handler.1542 /// * `sender` - The owner or administrator of the collection.1543 /// * `property_permissions` - Property permissions.1544 #[transactional]1545 pub fn set_token_property_permissions(1546 collection: &CollectionHandle<T>,1547 sender: &T::CrossAccountId,1548 property_permissions: Vec<PropertyKeyPermission>,1549 ) -> DispatchResult {1550 Self::set_scoped_token_property_permissions(1551 collection,1552 sender,1553 PropertyScope::None,1554 property_permissions,1555 )1556 }15571558 /// Set token property permission with scope.1559 ///1560 /// * `collection` - Collection handler.1561 /// * `sender` - The owner or administrator of the collection.1562 /// * `scope` - Property scope.1563 /// * `property_permissions` - Property permissions.1564 #[transactional]1565 pub fn set_scoped_token_property_permissions(1566 collection: &CollectionHandle<T>,1567 sender: &T::CrossAccountId,1568 scope: PropertyScope,1569 property_permissions: Vec<PropertyKeyPermission>,1570 ) -> DispatchResult {1571 for prop_pemission in property_permissions {1572 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1573 }15741575 Ok(())1576 }15771578 /// Get collection property.1579 pub fn get_collection_property(1580 collection_id: CollectionId,1581 key: &PropertyKey,1582 ) -> Option<PropertyValue> {1583 Self::collection_properties(collection_id).get(key).cloned()1584 }15851586 /// Convert byte vector to property key vector.1587 pub fn bytes_keys_to_property_keys(1588 keys: Vec<Vec<u8>>,1589 ) -> Result<Vec<PropertyKey>, DispatchError> {1590 keys.into_iter()1591 .map(|key| -> Result<PropertyKey, DispatchError> {1592 key.try_into()1593 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1594 })1595 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1596 }15971598 /// Get properties according to given keys.1599 pub fn filter_collection_properties(1600 collection_id: CollectionId,1601 keys: Option<Vec<PropertyKey>>,1602 ) -> Result<Vec<Property>, DispatchError> {1603 let properties = Self::collection_properties(collection_id);16041605 let properties = keys1606 .map(|keys| {1607 keys.into_iter()1608 .filter_map(|key| {1609 properties.get(&key).map(|value| Property {1610 key,1611 value: value.clone(),1612 })1613 })1614 .collect()1615 })1616 .unwrap_or_else(|| {1617 properties1618 .into_iter()1619 .map(|(key, value)| Property { key, value })1620 .collect()1621 });16221623 Ok(properties)1624 }16251626 /// Get property permissions according to given keys.1627 pub fn filter_property_permissions(1628 collection_id: CollectionId,1629 keys: Option<Vec<PropertyKey>>,1630 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1631 let permissions = Self::property_permissions(collection_id);16321633 let key_permissions = keys1634 .map(|keys| {1635 keys.into_iter()1636 .filter_map(|key| {1637 permissions1638 .get(&key)1639 .map(|permission| PropertyKeyPermission {1640 key,1641 permission: permission.clone(),1642 })1643 })1644 .collect()1645 })1646 .unwrap_or_else(|| {1647 permissions1648 .into_iter()1649 .map(|(key, permission)| PropertyKeyPermission { key, permission })1650 .collect()1651 });16521653 Ok(key_permissions)1654 }16551656 /// Toggle `user` participation in the `collection`'s allow list.1657 /// #### Store read/writes1658 /// 1 writes1659 pub fn toggle_allowlist(1660 collection: &CollectionHandle<T>,1661 sender: &T::CrossAccountId,1662 user: &T::CrossAccountId,1663 allowed: bool,1664 ) -> DispatchResult {1665 collection.check_is_owner_or_admin(sender)?;16661667 // =========16681669 if allowed {1670 <Allowlist<T>>::insert((collection.id, user), true);1671 Self::deposit_event(Event::<T>::AllowListAddressAdded(1672 collection.id,1673 user.clone(),1674 ));1675 } else {1676 <Allowlist<T>>::remove((collection.id, user));1677 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1678 collection.id,1679 user.clone(),1680 ));1681 }16821683 <PalletEvm<T>>::deposit_log(1684 erc::CollectionHelpersEvents::CollectionChanged {1685 collection_id: eth::collection_id_to_address(collection.id),1686 }1687 .to_log(T::ContractAddress::get()),1688 );16891690 Ok(())1691 }16921693 /// Toggle `user` participation in the `collection`'s admin list.1694 /// #### Store read/writes1695 /// 2 reads, 2 writes1696 pub fn toggle_admin(1697 collection: &CollectionHandle<T>,1698 sender: &T::CrossAccountId,1699 user: &T::CrossAccountId,1700 admin: bool,1701 ) -> DispatchResult {1702 collection.check_is_internal()?;1703 collection.check_is_owner(sender)?;17041705 let is_admin = <IsAdmin<T>>::get((collection.id, user));1706 if is_admin == admin {1707 if admin {1708 return Ok(());1709 } else {1710 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1711 }1712 }1713 let amount = <AdminAmount<T>>::get(collection.id);17141715 // =========17161717 if admin {1718 let amount = amount1719 .checked_add(1)1720 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1721 ensure!(1722 amount <= Self::collection_admins_limit(),1723 <Error<T>>::CollectionAdminCountExceeded,1724 );17251726 <AdminAmount<T>>::insert(collection.id, amount);1727 <IsAdmin<T>>::insert((collection.id, user), true);17281729 Self::deposit_event(Event::<T>::CollectionAdminAdded(1730 collection.id,1731 user.clone(),1732 ));1733 } else {1734 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1735 <IsAdmin<T>>::remove((collection.id, user));17361737 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1738 collection.id,1739 user.clone(),1740 ));1741 }17421743 <PalletEvm<T>>::deposit_log(1744 erc::CollectionHelpersEvents::CollectionChanged {1745 collection_id: eth::collection_id_to_address(collection.id),1746 }1747 .to_log(T::ContractAddress::get()),1748 );17491750 Ok(())1751 }17521753 /// Update collection limits.1754 pub fn update_limits(1755 user: &T::CrossAccountId,1756 collection: &mut CollectionHandle<T>,1757 new_limit: CollectionLimits,1758 ) -> DispatchResult {1759 collection.check_is_internal()?;1760 collection.check_is_owner_or_admin(user)?;17611762 collection.limits =1763 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17641765 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1766 <PalletEvm<T>>::deposit_log(1767 erc::CollectionHelpersEvents::CollectionChanged {1768 collection_id: eth::collection_id_to_address(collection.id),1769 }1770 .to_log(T::ContractAddress::get()),1771 );17721773 collection.save()1774 }17751776 /// Merge set fields from `new_limit` to `old_limit`.1777 fn clamp_limits(1778 mode: CollectionMode,1779 old_limit: &CollectionLimits,1780 mut new_limit: CollectionLimits,1781 ) -> Result<CollectionLimits, DispatchError> {1782 let limits = old_limit;1783 limit_default!(old_limit, new_limit,1784 account_token_ownership_limit => ensure!(1785 new_limit <= MAX_TOKEN_OWNERSHIP,1786 <Error<T>>::CollectionLimitBoundsExceeded,1787 ),1788 sponsored_data_size => ensure!(1789 new_limit <= CUSTOM_DATA_LIMIT,1790 <Error<T>>::CollectionLimitBoundsExceeded,1791 ),17921793 sponsored_data_rate_limit => {},1794 token_limit => ensure!(1795 old_limit >= new_limit && new_limit > 0,1796 <Error<T>>::CollectionTokenLimitExceeded1797 ),17981799 sponsor_transfer_timeout(match mode {1800 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1801 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1802 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1803 }) => ensure!(1804 new_limit <= MAX_SPONSOR_TIMEOUT,1805 <Error<T>>::CollectionLimitBoundsExceeded,1806 ),1807 sponsor_approve_timeout => {},1808 owner_can_transfer => ensure!(1809 !limits.owner_can_transfer_instaled() ||1810 old_limit || !new_limit,1811 <Error<T>>::OwnerPermissionsCantBeReverted,1812 ),1813 owner_can_destroy => ensure!(1814 old_limit || !new_limit,1815 <Error<T>>::OwnerPermissionsCantBeReverted,1816 ),1817 transfers_enabled => {},1818 );1819 Ok(new_limit)1820 }18211822 /// Update collection permissions.1823 pub fn update_permissions(1824 user: &T::CrossAccountId,1825 collection: &mut CollectionHandle<T>,1826 new_permission: CollectionPermissions,1827 ) -> DispatchResult {1828 collection.check_is_internal()?;1829 collection.check_is_owner_or_admin(user)?;1830 collection.permissions = Self::clamp_permissions(1831 collection.mode.clone(),1832 &collection.permissions,1833 new_permission,1834 )?;18351836 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1837 <PalletEvm<T>>::deposit_log(1838 erc::CollectionHelpersEvents::CollectionChanged {1839 collection_id: eth::collection_id_to_address(collection.id),1840 }1841 .to_log(T::ContractAddress::get()),1842 );18431844 collection.save()1845 }18461847 /// Merge set fields from `new_permission` to `old_permission`.1848 fn clamp_permissions(1849 _mode: CollectionMode,1850 old_permission: &CollectionPermissions,1851 mut new_permission: CollectionPermissions,1852 ) -> Result<CollectionPermissions, DispatchError> {1853 limit_default_clone!(old_permission, new_permission,1854 access => {},1855 mint_mode => {},1856 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1857 );1858 Ok(new_permission)1859 }18601861 /// Repair possibly broken properties of a collection.1862 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1863 CollectionProperties::<T>::mutate(collection_id, |properties| {1864 properties.recompute_consumed_space();1865 });18661867 Ok(())1868 }1869}18701871/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1872#[macro_export]1873macro_rules! unsupported {1874 ($runtime:path) => {1875 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1876 };1877}18781879/// Return weights for various worst-case operations.1880pub trait CommonWeightInfo<CrossAccountId> {1881 /// Weight of item creation.1882 fn create_item(data: &CreateItemData) -> Weight {1883 Self::create_multiple_items(from_ref(data))1884 }18851886 /// Weight of items creation.1887 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18881889 /// Weight of items creation.1890 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18911892 /// The weight of the burning item.1893 fn burn_item() -> Weight;18941895 /// Property setting weight.1896 ///1897 /// * `amount`- The number of properties to set.1898 fn set_collection_properties(amount: u32) -> Weight;18991900 /// Collection property deletion weight.1901 ///1902 /// * `amount`- The number of properties to set.1903 fn delete_collection_properties(amount: u32) -> Weight;19041905 /// Token property setting weight.1906 ///1907 /// * `amount`- The number of properties to set.1908 fn set_token_properties(amount: u32) -> Weight;19091910 /// Token property deletion weight.1911 ///1912 /// * `amount`- The number of properties to delete.1913 fn delete_token_properties(amount: u32) -> Weight;19141915 /// Token property permissions set weight.1916 ///1917 /// * `amount`- The number of property permissions to set.1918 fn set_token_property_permissions(amount: u32) -> Weight;19191920 /// Transfer price of the token or its parts.1921 fn transfer() -> Weight;19221923 /// The price of setting the permission of the operation from another user.1924 fn approve() -> Weight;19251926 /// The price of setting the permission of the operation from another user for eth mirror.1927 fn approve_from() -> Weight;19281929 /// Transfer price from another user.1930 fn transfer_from() -> Weight;19311932 /// The price of burning a token from another user.1933 fn burn_from() -> Weight;19341935 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1936 /// whole users's balance.1937 ///1938 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1939 fn burn_recursively_self_raw() -> Weight;19401941 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1942 ///1943 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1944 fn burn_recursively_breadth_raw(amount: u32) -> Weight;19451946 /// The price of recursive burning a token.1947 ///1948 /// `max_selfs` - The maximum burning weight of the token itself.1949 /// `max_breadth` - The maximum number of nested tokens to burn.1950 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1951 Self::burn_recursively_self_raw()1952 .saturating_mul(max_selfs.max(1) as u64)1953 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1954 }19551956 /// The price of retrieving token owner1957 fn token_owner() -> Weight;19581959 /// The price of setting approval for all1960 fn set_allowance_for_all() -> Weight;19611962 /// The price of repairing an item.1963 fn force_repair_item() -> Weight;1964}19651966/// Weight info extension trait for refungible pallet.1967pub trait RefungibleExtensionsWeightInfo {1968 /// Weight of token repartition.1969 fn repartition() -> Weight;1970}19711972/// Common collection operations.1973///1974/// It wraps methods in Fungible, Nonfungible and Refungible pallets1975/// and adds weight info.1976pub trait CommonCollectionOperations<T: Config> {1977 /// Create token.1978 ///1979 /// * `sender` - The user who mint the token and pays for the transaction.1980 /// * `to` - The user who will own the token.1981 /// * `data` - Token data.1982 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1983 fn create_item(1984 &self,1985 sender: T::CrossAccountId,1986 to: T::CrossAccountId,1987 data: CreateItemData,1988 nesting_budget: &dyn Budget,1989 ) -> DispatchResultWithPostInfo;19901991 /// Create multiple tokens.1992 ///1993 /// * `sender` - The user who mint the token and pays for the transaction.1994 /// * `to` - The user who will own the token.1995 /// * `data` - Token data.1996 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1997 fn create_multiple_items(1998 &self,1999 sender: T::CrossAccountId,2000 to: T::CrossAccountId,2001 data: Vec<CreateItemData>,2002 nesting_budget: &dyn Budget,2003 ) -> DispatchResultWithPostInfo;20042005 /// Create multiple tokens.2006 ///2007 /// * `sender` - The user who mint the token and pays for the transaction.2008 /// * `to` - The user who will own the token.2009 /// * `data` - Token data.2010 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2011 fn create_multiple_items_ex(2012 &self,2013 sender: T::CrossAccountId,2014 data: CreateItemExData<T::CrossAccountId>,2015 nesting_budget: &dyn Budget,2016 ) -> DispatchResultWithPostInfo;20172018 /// Burn token.2019 ///2020 /// * `sender` - The user who owns the token.2021 /// * `token` - Token id that will burned.2022 /// * `amount` - The number of parts of the token that will be burned.2023 fn burn_item(2024 &self,2025 sender: T::CrossAccountId,2026 token: TokenId,2027 amount: u128,2028 ) -> DispatchResultWithPostInfo;20292030 /// Burn token and all nested tokens recursievly.2031 ///2032 /// * `sender` - The user who owns the token.2033 /// * `token` - Token id that will burned.2034 /// * `self_budget` - The budget that can be spent on burning tokens.2035 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2036 fn burn_item_recursively(2037 &self,2038 sender: T::CrossAccountId,2039 token: TokenId,2040 self_budget: &dyn Budget,2041 breadth_budget: &dyn Budget,2042 ) -> DispatchResultWithPostInfo;20432044 /// Set collection properties.2045 ///2046 /// * `sender` - Must be either the owner of the collection or its admin.2047 /// * `properties` - Properties to be set.2048 fn set_collection_properties(2049 &self,2050 sender: T::CrossAccountId,2051 properties: Vec<Property>,2052 ) -> DispatchResultWithPostInfo;20532054 /// Delete collection properties.2055 ///2056 /// * `sender` - Must be either the owner of the collection or its admin.2057 /// * `properties` - The properties to be removed.2058 fn delete_collection_properties(2059 &self,2060 sender: &T::CrossAccountId,2061 property_keys: Vec<PropertyKey>,2062 ) -> DispatchResultWithPostInfo;20632064 /// Set token properties.2065 ///2066 /// The appropriate [`PropertyPermission`] for the token property2067 /// must be set with [`Self::set_token_property_permissions`].2068 ///2069 /// * `sender` - Must be either the owner of the token or its admin.2070 /// * `token_id` - The token for which the properties are being set.2071 /// * `properties` - Properties to be set.2072 /// * `budget` - Budget for setting properties.2073 fn set_token_properties(2074 &self,2075 sender: T::CrossAccountId,2076 token_id: TokenId,2077 properties: Vec<Property>,2078 budget: &dyn Budget,2079 ) -> DispatchResultWithPostInfo;20802081 /// Remove token properties.2082 ///2083 /// The appropriate [`PropertyPermission`] for the token property2084 /// must be set with [`Self::set_token_property_permissions`].2085 ///2086 /// * `sender` - Must be either the owner of the token or its admin.2087 /// * `token_id` - The token for which the properties are being remove.2088 /// * `property_keys` - Keys to remove corresponding properties.2089 /// * `budget` - Budget for removing properties.2090 fn delete_token_properties(2091 &self,2092 sender: T::CrossAccountId,2093 token_id: TokenId,2094 property_keys: Vec<PropertyKey>,2095 budget: &dyn Budget,2096 ) -> DispatchResultWithPostInfo;20972098 /// Get token properties raw map.2099 ///2100 /// * `token_id` - The token which properties are needed.2101 fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;21022103 /// Set token properties raw map.2104 ///2105 /// * `token_id` - The token for which the properties are being set.2106 /// * `map` - The raw map containing the token's properties.2107 fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);21082109 /// Whether the given token has properties.2110 ///2111 /// * `token_id` - The token in question.2112 fn properties_exist(&self, token: TokenId) -> bool;21132114 /// Set token property permissions.2115 ///2116 /// * `sender` - Must be either the owner of the token or its admin.2117 /// * `token_id` - The token for which the properties are being set.2118 /// * `property_permissions` - Property permissions to be set.2119 /// * `budget` - Budget for setting properties.2120 fn set_token_property_permissions(2121 &self,2122 sender: &T::CrossAccountId,2123 property_permissions: Vec<PropertyKeyPermission>,2124 ) -> DispatchResultWithPostInfo;21252126 /// Transfer amount of token pieces.2127 ///2128 /// * `sender` - Donor user.2129 /// * `to` - Recepient user.2130 /// * `token` - The token of which parts are being sent.2131 /// * `amount` - The number of parts of the token that will be transferred.2132 /// * `budget` - The maximum budget that can be spent on the transfer.2133 fn transfer(2134 &self,2135 sender: T::CrossAccountId,2136 to: T::CrossAccountId,2137 token: TokenId,2138 amount: u128,2139 budget: &dyn Budget,2140 ) -> DispatchResultWithPostInfo;21412142 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2143 ///2144 /// * `sender` - The user who grants access to the token.2145 /// * `spender` - The user to whom the rights are granted.2146 /// * `token` - The token to which access is granted.2147 /// * `amount` - The amount of pieces that another user can dispose of.2148 fn approve(2149 &self,2150 sender: T::CrossAccountId,2151 spender: T::CrossAccountId,2152 token: TokenId,2153 amount: u128,2154 ) -> DispatchResultWithPostInfo;21552156 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2157 ///2158 /// * `sender` - The user who grants access to the token.2159 /// * `from` - Spender's eth mirror.2160 /// * `to` - The user to whom the rights are granted.2161 /// * `token` - The token to which access is granted.2162 /// * `amount` - The amount of pieces that another user can dispose of.2163 fn approve_from(2164 &self,2165 sender: T::CrossAccountId,2166 from: T::CrossAccountId,2167 to: T::CrossAccountId,2168 token: TokenId,2169 amount: u128,2170 ) -> DispatchResultWithPostInfo;21712172 /// Send parts of a token owned by another user.2173 ///2174 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2175 ///2176 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2177 /// * `from` - The user who owns the token.2178 /// * `to` - Recepient user.2179 /// * `token` - The token of which parts are being sent.2180 /// * `amount` - The number of parts of the token that will be transferred.2181 /// * `budget` - The maximum budget that can be spent on the transfer.2182 fn transfer_from(2183 &self,2184 sender: T::CrossAccountId,2185 from: T::CrossAccountId,2186 to: T::CrossAccountId,2187 token: TokenId,2188 amount: u128,2189 budget: &dyn Budget,2190 ) -> DispatchResultWithPostInfo;21912192 /// Burn parts of a token owned by another user.2193 ///2194 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2195 ///2196 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2197 /// * `from` - The user who owns the token.2198 /// * `token` - The token of which parts are being sent.2199 /// * `amount` - The number of parts of the token that will be transferred.2200 /// * `budget` - The maximum budget that can be spent on the burn.2201 fn burn_from(2202 &self,2203 sender: T::CrossAccountId,2204 from: T::CrossAccountId,2205 token: TokenId,2206 amount: u128,2207 budget: &dyn Budget,2208 ) -> DispatchResultWithPostInfo;22092210 /// Check permission to nest token.2211 ///2212 /// * `sender` - The user who initiated the check.2213 /// * `from` - The token that is checked for embedding.2214 /// * `under` - Token under which to check.2215 /// * `budget` - The maximum budget that can be spent on the check.2216 fn check_nesting(2217 &self,2218 sender: T::CrossAccountId,2219 from: (CollectionId, TokenId),2220 under: TokenId,2221 budget: &dyn Budget,2222 ) -> DispatchResult;22232224 /// Nest one token into another.2225 ///2226 /// * `under` - Token holder.2227 /// * `to_nest` - Nested token.2228 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22292230 /// Unnest token.2231 ///2232 /// * `under` - Token holder.2233 /// * `to_nest` - Token to unnest.2234 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22352236 /// Get all user tokens.2237 ///2238 /// * `account` - Account for which you need to get tokens.2239 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22402241 /// Get all the tokens in the collection.2242 fn collection_tokens(&self) -> Vec<TokenId>;22432244 /// Check if the token exists.2245 ///2246 /// * `token` - Id token to check.2247 fn token_exists(&self, token: TokenId) -> bool;22482249 /// Get the id of the last minted token.2250 fn last_token_id(&self) -> TokenId;22512252 /// Get the owner of the token.2253 ///2254 /// * `token` - The token for which you need to find out the owner.2255 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22562257 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2258 ///2259 /// * `token` - Id token to check.2260 /// * `maybe_owner` - The account to check.2261 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2262 fn check_token_indirect_owner(2263 &self,2264 token: TokenId,2265 maybe_owner: &T::CrossAccountId,2266 nesting_budget: &dyn Budget,2267 ) -> Result<bool, DispatchError>;22682269 /// Returns 10 tokens owners in no particular order.2270 ///2271 /// * `token` - The token for which you need to find out the owners.2272 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22732274 /// Get the value of the token property by key.2275 ///2276 /// * `token` - Token with the property to get.2277 /// * `key` - Property name.2278 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22792280 /// Get a set of token properties by key vector.2281 ///2282 /// * `token` - Token with the property to get.2283 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2284 /// then all properties are returned.2285 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22862287 /// Amount of unique collection tokens2288 fn total_supply(&self) -> u32;22892290 /// Amount of different tokens account has.2291 ///2292 /// * `account` - The account for which need to get the balance.2293 fn account_balance(&self, account: T::CrossAccountId) -> u32;22942295 /// Amount of specific token account have.2296 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22972298 /// Amount of token pieces2299 fn total_pieces(&self, token: TokenId) -> Option<u128>;23002301 /// Get the number of parts of the token that a trusted user can manage.2302 ///2303 /// * `sender` - Trusted user.2304 /// * `spender` - Owner of the token.2305 /// * `token` - The token for which to get the value.2306 fn allowance(2307 &self,2308 sender: T::CrossAccountId,2309 spender: T::CrossAccountId,2310 token: TokenId,2311 ) -> u128;23122313 /// Get extension for RFT collection.2314 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23152316 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2317 /// * `owner` - Token owner2318 /// * `operator` - Operator2319 /// * `approve` - Should operator status be granted or revoked?2320 fn set_allowance_for_all(2321 &self,2322 owner: T::CrossAccountId,2323 operator: T::CrossAccountId,2324 approve: bool,2325 ) -> DispatchResultWithPostInfo;23262327 /// Tells whether the given `owner` approves the `operator`.2328 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23292330 /// Repairs a possibly broken item.2331 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2332}23332334/// Extension for RFT collection.2335pub trait RefungibleExtensions<T>2336where2337 T: Config,2338{2339 /// Change the number of parts of the token.2340 ///2341 /// When the value changes down, this function is equivalent to burning parts of the token.2342 ///2343 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2344 /// * `token` - The token for which you want to change the number of parts.2345 /// * `amount` - The new value of the parts of the token.2346 fn repartition(2347 &self,2348 sender: &T::CrossAccountId,2349 token: TokenId,2350 amount: u128,2351 ) -> DispatchResultWithPostInfo;2352}23532354/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2355///2356/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2357pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2358 let post_info = PostDispatchInfo {2359 actual_weight: Some(weight),2360 pays_fee: Pays::Yes,2361 };2362 match res {2363 Ok(()) => Ok(post_info),2364 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2365 }2366}23672368impl<T: Config> From<PropertiesError> for Error<T> {2369 fn from(error: PropertiesError) -> Self {2370 match error {2371 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2372 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2373 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2374 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2375 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2376 }2377 }2378}23792380/// A marker structure that enables the writer implementation2381/// to provide the interface to write properties to **newly created** tokens.2382pub struct NewTokenPropertyWriter;23832384/// A marker structure that enables the writer implementation2385/// to provide the interface to write properties to **already existing** tokens.2386pub struct ExistingTokenPropertyWriter;23872388/// The type-safe interface for writing properties (setting or deleting) to tokens.2389/// It has two distinct implementations for newly created tokens and existing ones.2390///2391/// This type utilizes the lazy evaluation to avoid repeating the computation2392/// of several performance-heavy or PoV-heavy tasks,2393/// such as checking the indirect ownership or reading the token property permissions.2394pub struct PropertyWriter<2395 'a,2396 T,2397 Handle,2398 WriterVariant,2399 FIsAdmin,2400 FPropertyPermissions,2401 FCheckTokenExist,2402 FGetProperties,2403> where2404 T: Config,2405 FIsAdmin: FnOnce() -> bool,2406 FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2407{2408 collection: &'a Handle,2409 is_collection_admin: LazyValue<bool, FIsAdmin>,2410 property_permissions: LazyValue<PropertiesPermissionMap, FPropertyPermissions>,2411 check_token_exist: FCheckTokenExist,2412 get_properties: FGetProperties,2413 _phantom: PhantomData<(T, WriterVariant)>,2414}24152416impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2417 PropertyWriter<2418 'a,2419 T,2420 Handle,2421 NewTokenPropertyWriter,2422 FIsAdmin,2423 FPropertyPermissions,2424 FCheckTokenExist,2425 FGetProperties,2426 > where2427 T: Config,2428 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2429 FIsAdmin: FnOnce() -> bool,2430 FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2431 FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2432 FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2433{2434 /// A function to write properties to a **newly created** token.2435 pub fn write_token_properties(2436 &mut self,2437 mint_target_is_sender: bool,2438 token_id: TokenId,2439 properties_updates: impl Iterator<Item = Property>,2440 log: evm_coder::ethereum::Log,2441 ) -> DispatchResult {2442 self.internal_write_token_properties(2443 token_id,2444 properties_updates.map(|p| (p.key, Some(p.value))),2445 |_| Ok(mint_target_is_sender),2446 log,2447 )2448 }2449}24502451impl<'a, T, Handle, FIsAdmin, FPropertyPermissions, FCheckTokenExist, FGetProperties>2452 PropertyWriter<2453 'a,2454 T,2455 Handle,2456 ExistingTokenPropertyWriter,2457 FIsAdmin,2458 FPropertyPermissions,2459 FCheckTokenExist,2460 FGetProperties,2461 > where2462 T: Config,2463 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2464 FIsAdmin: FnOnce() -> bool,2465 FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2466 FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2467 FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2468{2469 /// A function to write properties to an **already existing** token.2470 pub fn write_token_properties(2471 &mut self,2472 sender: &T::CrossAccountId,2473 token_id: TokenId,2474 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2475 nesting_budget: &dyn Budget,2476 log: evm_coder::ethereum::Log,2477 ) -> DispatchResult {2478 self.internal_write_token_properties(2479 token_id,2480 properties_updates,2481 |collection| collection.check_token_indirect_owner(token_id, sender, nesting_budget),2482 log,2483 )2484 }2485}24862487impl<2488 'a,2489 T,2490 Handle,2491 WriterVariant,2492 FIsAdmin,2493 FPropertyPermissions,2494 FCheckTokenExist,2495 FGetProperties,2496 >2497 PropertyWriter<2498 'a,2499 T,2500 Handle,2501 WriterVariant,2502 FIsAdmin,2503 FPropertyPermissions,2504 FCheckTokenExist,2505 FGetProperties,2506 > where2507 T: Config,2508 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2509 FIsAdmin: FnOnce() -> bool,2510 FPropertyPermissions: FnOnce() -> PropertiesPermissionMap,2511 FCheckTokenExist: Copy + FnOnce(TokenId) -> bool,2512 FGetProperties: Copy + FnOnce(TokenId) -> TokenProperties,2513{2514 fn internal_write_token_properties<FCheckTokenOwner>(2515 &mut self,2516 token_id: TokenId,2517 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2518 check_token_owner: FCheckTokenOwner,2519 log: evm_coder::ethereum::Log,2520 ) -> DispatchResult2521 where2522 FCheckTokenOwner: FnOnce(&Handle) -> Result<bool, DispatchError>,2523 {2524 let get_properties = self.get_properties;2525 let mut stored_properties = LazyValue::new(move || get_properties(token_id));25262527 let mut is_token_owner = LazyValue::new(|| check_token_owner(self.collection));25282529 let check_token_exist = self.check_token_exist;2530 let mut is_token_exist = LazyValue::new(move || check_token_exist(token_id));25312532 for (key, value) in properties_updates {2533 let permission = self2534 .property_permissions2535 .value()2536 .get(&key)2537 .cloned()2538 .unwrap_or_else(PropertyPermission::none);25392540 match permission {2541 PropertyPermission { mutable: false, .. }2542 if stored_properties.value().get(&key).is_some() =>2543 {2544 return Err(<Error<T>>::NoPermission.into());2545 }25462547 PropertyPermission {2548 collection_admin,2549 token_owner,2550 ..2551 } => check_token_permissions::<T, _, _, _>(2552 collection_admin,2553 token_owner,2554 &mut self.is_collection_admin,2555 &mut is_token_owner,2556 &mut is_token_exist,2557 )?,2558 }25592560 match value {2561 Some(value) => {2562 stored_properties2563 .value_mut()2564 .try_set(key.clone(), value)2565 .map_err(<Error<T>>::from)?;25662567 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2568 self.collection.id,2569 token_id,2570 key,2571 ));2572 }2573 None => {2574 stored_properties2575 .value_mut()2576 .remove(&key)2577 .map_err(<Error<T>>::from)?;25782579 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2580 self.collection.id,2581 token_id,2582 key,2583 ));2584 }2585 }2586 }25872588 let properties_changed = stored_properties.has_value();2589 if properties_changed {2590 <PalletEvm<T>>::deposit_log(log);25912592 self.collection2593 .set_token_properties_map(token_id, stored_properties.into_inner());2594 }25952596 Ok(())2597 }2598}25992600/// Create a [`PropertyWriter`] for newly created tokens.2601pub fn property_writer_for_new_token<'a, T, Handle>(2602 collection: &'a Handle,2603 sender: &'a T::CrossAccountId,2604) -> PropertyWriter<2605 'a,2606 T,2607 Handle,2608 NewTokenPropertyWriter,2609 impl FnOnce() -> bool + 'a,2610 impl FnOnce() -> PropertiesPermissionMap + 'a,2611 impl Copy + FnOnce(TokenId) -> bool + 'a,2612 impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2613>2614where2615 T: Config,2616 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2617{2618 PropertyWriter {2619 collection,2620 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2621 property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2622 check_token_exist: |token_id| {2623 debug_assert!(collection.token_exists(token_id));2624 true2625 },2626 get_properties: |token_id| {2627 debug_assert!(!collection.properties_exist(token_id));2628 TokenProperties::new()2629 },2630 _phantom: PhantomData,2631 }2632}26332634#[cfg(feature = "runtime-benchmarks")]2635/// Create a `PropertyWriter` with preloaded `is_collection_admin` and `property_permissions.2636/// Also:2637/// * it will return `true` for the token ownership check.2638/// * it will return empty stored properties without reading them from the storage.2639pub fn collection_info_loaded_property_writer<T, Handle>(2640 collection: &Handle,2641 is_collection_admin: bool,2642 property_permissions: PropertiesPermissionMap,2643) -> PropertyWriter<2644 T,2645 Handle,2646 NewTokenPropertyWriter,2647 impl FnOnce() -> bool,2648 impl FnOnce() -> PropertiesPermissionMap,2649 impl Copy + FnOnce(TokenId) -> bool,2650 impl Copy + FnOnce(TokenId) -> TokenProperties,2651>2652where2653 T: Config,2654 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2655{2656 PropertyWriter {2657 collection,2658 is_collection_admin: LazyValue::new(move || is_collection_admin),2659 property_permissions: LazyValue::new(move || property_permissions),2660 check_token_exist: |_token_id| true,2661 get_properties: |_token_id| TokenProperties::new(),2662 _phantom: PhantomData,2663 }2664}26652666/// Create a [`PropertyWriter`] for already existing tokens.2667pub fn property_writer_for_existing_token<'a, T, Handle>(2668 collection: &'a Handle,2669 sender: &'a T::CrossAccountId,2670) -> PropertyWriter<2671 'a,2672 T,2673 Handle,2674 ExistingTokenPropertyWriter,2675 impl FnOnce() -> bool + 'a,2676 impl FnOnce() -> PropertiesPermissionMap + 'a,2677 impl Copy + FnOnce(TokenId) -> bool + 'a,2678 impl Copy + FnOnce(TokenId) -> TokenProperties + 'a,2679>2680where2681 T: Config,2682 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2683{2684 PropertyWriter {2685 collection,2686 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2687 property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),2688 check_token_exist: |token_id| collection.token_exists(token_id),2689 get_properties: |token_id| collection.get_token_properties_map(token_id),2690 _phantom: PhantomData,2691 }2692}26932694/// Computes the weight delta for newly created tokens with properties.2695/// * `properties_nums` - The properties num of each created token.2696/// * `init_token_properties` - The function to obtain the weight from a token's properties num.2697pub fn init_token_properties_delta<T: Config, I: Fn(u32) -> Weight>(2698 properties_nums: impl Iterator<Item = u32>,2699 init_token_properties: I,2700) -> Weight {2701 let mut delta = properties_nums2702 .filter_map(|properties_num| {2703 if properties_num > 0 {2704 Some(init_token_properties(properties_num))2705 } else {2706 None2707 }2708 })2709 .fold(Weight::zero(), |a, b| a.saturating_add(b));27102711 // If at least once the `init_token_properties` was called,2712 // it means at least one newly created token has properties.2713 // Becuase of that, some common collection data also was loaded and we need to add this weight.2714 // However, these common data was loaded only once which is guaranteed by the `PropertyWriter`.2715 if !delta.is_zero() {2716 delta = delta.saturating_add(<SelfWeightOf<T>>::init_token_properties_common())2717 }27182719 delta2720}27212722#[cfg(any(feature = "tests", test))]2723#[allow(missing_docs)]2724pub mod tests {2725 use crate::{DispatchResult, DispatchError, LazyValue, Config};27262727 const fn to_bool(u: u8) -> bool {2728 u != 02729 }27302731 #[derive(Debug)]2732 pub struct TestCase {2733 pub collection_admin: bool,2734 pub is_collection_admin: bool,2735 pub token_owner: bool,2736 pub is_token_owner: bool,2737 pub no_permission: bool,2738 }27392740 impl TestCase {2741 const fn new(2742 collection_admin: u8,2743 is_collection_admin: u8,2744 token_owner: u8,2745 is_token_owner: u8,2746 no_permission: u8,2747 ) -> Self {2748 Self {2749 collection_admin: to_bool(collection_admin),2750 is_collection_admin: to_bool(is_collection_admin),2751 token_owner: to_bool(token_owner),2752 is_token_owner: to_bool(is_token_owner),2753 no_permission: to_bool(no_permission),2754 }2755 }2756 }27572758 #[rustfmt::skip]2759 pub const TABLE: [TestCase; 16] = [2760 // ┌╴collection_admin2761 // │ ┌╴is_collection_admin2762 // │ │ ┌╴token_owner2763 // │ │ │ ┌╴is_token_ownership2764 // │ │ │ │ ┌╴no_permission2765 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2766 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2767 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2768 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2769 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2770 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2771 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2772 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2773 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2774 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2775 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2776 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2777 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2778 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2779 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2780 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2781 ];27822783 pub fn check_token_permissions<T, FCA, FTO, FTE>(2784 collection_admin_permitted: bool,2785 token_owner_permitted: bool,2786 is_collection_admin: &mut LazyValue<bool, FCA>,2787 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>, FTO>,2788 check_token_existence: &mut LazyValue<bool, FTE>,2789 ) -> DispatchResult2790 where2791 T: Config,2792 FCA: FnOnce() -> bool,2793 FTO: FnOnce() -> Result<bool, DispatchError>,2794 FTE: FnOnce() -> bool,2795 {2796 crate::check_token_permissions::<T, FCA, FTO, FTE>(2797 collection_admin_permitted,2798 token_owner_permitted,2799 is_collection_admin,2800 check_token_ownership,2801 check_token_existence,2802 )2803 }2804}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.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -203,7 +203,6 @@
&caller,
TokenId(token_id),
properties.into_iter(),
- pallet_common::SetPropertyMode::ExistingToken,
&nesting_budget,
)
.map_err(dispatch_to_evm::<T>)
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));
}