difftreelog
doc: why transactional is needed in XCM extensions
in: master
1 file changed
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 alloc::boxed::Box;57use core::{58 marker::PhantomData,59 ops::{Deref, DerefMut},60 slice::from_ref,61 unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67 ensure, fail,68 traits::{69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 Get,72 },73 transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83 budget::Budget, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,84 CollectionLimits, CollectionMode, CollectionPermissions,85 CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,86 CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,87 Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,88 RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,89 TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,90 COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91 MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,92 NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,93};94use up_pov_estimate_rpc::PovInfo;9596#[cfg(feature = "runtime-benchmarks")]97pub mod benchmarking;98pub mod dispatch;99pub mod erc;100pub mod eth;101pub mod helpers;102#[allow(missing_docs)]103pub mod weights;104105use weights::WeightInfo;106107/// Weight info.108pub type SelfWeightOf<T> = <T as Config>::WeightInfo;109110/// Collection handle contains information about collection data and id.111/// Also provides functionality to count consumed gas.112///113/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).114/// It allows to perform common operations and queries on any collection type,115/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].116#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]117pub struct CollectionHandle<T: Config> {118 /// Collection id119 pub id: CollectionId,120 collection: Collection<T::AccountId>,121 /// Substrate recorder for counting consumed gas122 pub recorder: SubstrateRecorder<T>,123}124125impl<T: Config> WithRecorder<T> for CollectionHandle<T> {126 fn recorder(&self) -> &SubstrateRecorder<T> {127 &self.recorder128 }129 fn into_recorder(self) -> SubstrateRecorder<T> {130 self.recorder131 }132}133134impl<T: Config> CollectionHandle<T> {135 /// Same as [CollectionHandle::new] but with an explicit gas limit.136 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {137 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))138 }139140 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].141 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {142 <CollectionById<T>>::get(id).map(|collection| Self {143 id,144 collection,145 recorder,146 })147 }148149 /// Retrives collection data from storage and creates collection handle with default parameters.150 /// If collection not found return `None`151 pub fn new(id: CollectionId) -> Option<Self> {152 Self::new_with_gas_limit(id, u64::MAX)153 }154155 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.156 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {157 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)158 }159160 /// Consume gas for reading.161 pub fn consume_store_reads(162 &self,163 reads: u64,164 ) -> pallet_evm_coder_substrate::execution::Result<()> {165 self.recorder().consume_store_reads(reads)166 }167168 /// Consume gas for writing.169 pub fn consume_store_writes(170 &self,171 writes: u64,172 ) -> pallet_evm_coder_substrate::execution::Result<()> {173 self.recorder().consume_store_writes(writes)174 }175176 /// Consume gas for reading and writing.177 pub fn consume_store_reads_and_writes(178 &self,179 reads: u64,180 writes: u64,181 ) -> pallet_evm_coder_substrate::execution::Result<()> {182 self.recorder()183 .consume_store_reads_and_writes(reads, writes)184 }185186 /// Save collection to storage.187 pub fn save(&self) -> DispatchResult {188 <CollectionById<T>>::insert(self.id, &self.collection);189 Ok(())190 }191192 /// Set collection sponsor.193 ///194 /// Unique collections allows sponsoring for certain actions.195 /// This method allows you to set the sponsor of the collection.196 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].197 pub fn set_sponsor(198 &mut self,199 sender: &T::CrossAccountId,200 sponsor: T::AccountId,201 ) -> DispatchResult {202 self.check_is_internal()?;203 self.check_is_owner_or_admin(sender)?;204205 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());206207 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));208 <PalletEvm<T>>::deposit_log(209 erc::CollectionHelpersEvents::CollectionChanged {210 collection_id: eth::collection_id_to_address(self.id),211 }212 .to_log(T::ContractAddress::get()),213 );214215 self.save()216 }217218 /// Force set `sponsor`.219 ///220 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation221 /// from the `sponsor` is not required.222 ///223 /// # Arguments224 ///225 /// * `sponsor`: ID of the account of the sponsor-to-be.226 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {227 self.check_is_internal()?;228229 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());230231 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));232 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));233 <PalletEvm<T>>::deposit_log(234 erc::CollectionHelpersEvents::CollectionChanged {235 collection_id: eth::collection_id_to_address(self.id),236 }237 .to_log(T::ContractAddress::get()),238 );239240 self.save()241 }242243 /// Confirm sponsorship244 ///245 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.246 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].247 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {248 self.check_is_internal()?;249 ensure!(250 self.collection.sponsorship.pending_sponsor() == Some(sender),251 Error::<T>::ConfirmSponsorshipFail252 );253254 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());255256 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));257 <PalletEvm<T>>::deposit_log(258 erc::CollectionHelpersEvents::CollectionChanged {259 collection_id: eth::collection_id_to_address(self.id),260 }261 .to_log(T::ContractAddress::get()),262 );263264 self.save()265 }266267 /// Remove collection sponsor.268 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {269 self.check_is_internal()?;270 self.check_is_owner_or_admin(sender)?;271272 self.collection.sponsorship = SponsorshipState::Disabled;273274 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));275 <PalletEvm<T>>::deposit_log(276 erc::CollectionHelpersEvents::CollectionChanged {277 collection_id: eth::collection_id_to_address(self.id),278 }279 .to_log(T::ContractAddress::get()),280 );281 self.save()282 }283284 /// Force remove `sponsor`.285 ///286 /// Differs from `remove_sponsor` in that287 /// it doesn't require consent from the `owner` of the collection.288 pub fn force_remove_sponsor(&mut self) -> DispatchResult {289 self.check_is_internal()?;290291 self.collection.sponsorship = SponsorshipState::Disabled;292293 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));294 <PalletEvm<T>>::deposit_log(295 erc::CollectionHelpersEvents::CollectionChanged {296 collection_id: eth::collection_id_to_address(self.id),297 }298 .to_log(T::ContractAddress::get()),299 );300 self.save()301 }302303 /// Checks that the collection was created with, and must be operated upon through **Unique API**.304 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.305 pub fn check_is_internal(&self) -> DispatchResult {306 if self.flags.external {307 return Err(<Error<T>>::CollectionIsExternal)?;308 }309310 Ok(())311 }312313 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.314 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.315 pub fn check_is_external(&self) -> DispatchResult {316 if !self.flags.external {317 return Err(<Error<T>>::CollectionIsInternal)?;318 }319320 Ok(())321 }322}323324impl<T: Config> Deref for CollectionHandle<T> {325 type Target = Collection<T::AccountId>;326327 fn deref(&self) -> &Self::Target {328 &self.collection329 }330}331332impl<T: Config> DerefMut for CollectionHandle<T> {333 fn deref_mut(&mut self) -> &mut Self::Target {334 &mut self.collection335 }336}337338impl<T: Config> CollectionHandle<T> {339 /// Checks if the `user` is the owner of the collection.340 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {341 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);342 Ok(())343 }344345 /// Returns **true** if the `user` is the owner or administrator of the collection.346 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {347 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))348 }349350 /// Checks if the `user` is the owner or administrator of the collection.351 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {352 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);353 Ok(())354 }355356 /// Returns **true** if357 /// * the `user`is a collection owner or admin358 /// * the collection limits allow the owner/admins to transfer/burn any collection token359 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {360 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)361 }362363 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.364 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {365 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)366 }367368 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.369 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {370 ensure!(371 <Allowlist<T>>::get((self.id, user)),372 <Error<T>>::AddressNotInAllowlist373 );374 Ok(())375 }376377 /// Changes collection owner to another account378 /// #### Store read/writes379 /// 1 writes380 pub fn change_owner(381 &mut self,382 caller: T::CrossAccountId,383 new_owner: T::CrossAccountId,384 ) -> DispatchResult {385 self.check_is_internal()?;386 self.check_is_owner(&caller)?;387 self.collection.owner = new_owner.as_sub().clone();388389 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(390 self.id,391 new_owner.as_sub().clone(),392 ));393 <PalletEvm<T>>::deposit_log(394 erc::CollectionHelpersEvents::CollectionChanged {395 collection_id: eth::collection_id_to_address(self.id),396 }397 .to_log(T::ContractAddress::get()),398 );399400 self.save()401 }402}403404#[frame_support::pallet]405pub mod pallet {406407 use dispatch::CollectionDispatch;408 use frame_support::{409 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,410 };411 use scale_info::TypeInfo;412 use up_data_structs::{mapping::TokenAddressMapping, TokenId};413 use weights::WeightInfo;414415 use super::*;416417 #[pallet::config]418 pub trait Config:419 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo420 {421 /// Weight information for functions of this pallet.422 type WeightInfo: WeightInfo;423424 /// Events compatible with [`frame_system::Config::Event`].425 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;426427 /// Handler of accounts and payment.428 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;429430 /// Set price to create a collection.431 #[pallet::constant]432 type CollectionCreationPrice: Get<433 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,434 >;435436 /// Dispatcher of operations on collections.437 type CollectionDispatch: CollectionDispatch<Self>;438439 /// Account which holds the chain's treasury.440 type TreasuryAccountId: Get<Self::AccountId>;441442 /// Address under which the CollectionHelper contract would be available.443 #[pallet::constant]444 type ContractAddress: Get<H160>;445446 /// Mapper for token addresses to Ethereum addresses.447 type EvmTokenAddressMapping: TokenAddressMapping<H160>;448449 /// Mapper for token addresses to [`CrossAccountId`].450 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;451 }452453 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);454 /// Collection id for native fungible collction.455 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);456457 #[pallet::pallet]458 #[pallet::storage_version(STORAGE_VERSION)]459 pub struct Pallet<T>(_);460461 #[pallet::extra_constants]462 impl<T: Config> Pallet<T> {463 /// Maximum admins per collection.464 pub fn collection_admins_limit() -> u32 {465 COLLECTION_ADMINS_LIMIT466 }467 }468469 #[pallet::genesis_config]470 pub struct GenesisConfig<T>(PhantomData<T>);471472 impl<T: Config> Default for GenesisConfig<T> {473 fn default() -> Self {474 Self(Default::default())475 }476 }477478 #[pallet::genesis_build]479 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {480 fn build(&self) {481 StorageVersion::new(1).put::<Pallet<T>>();482 }483 }484485 impl<T: Config> Pallet<T> {486 /// Helper function that handles deposit events487 pub fn deposit_event(event: Event<T>) {488 let event = <T as Config>::RuntimeEvent::from(event);489 let event = event.into();490 <frame_system::Pallet<T>>::deposit_event(event)491 }492 }493494 #[pallet::event]495 pub enum Event<T: Config> {496 /// New collection was created497 CollectionCreated(498 /// Globally unique identifier of newly created collection.499 CollectionId,500 /// [`CollectionMode`] converted into _u8_.501 u8,502 /// Collection owner.503 T::AccountId,504 ),505506 /// New collection was destroyed507 CollectionDestroyed(508 /// Globally unique identifier of collection.509 CollectionId,510 ),511512 /// New item was created.513 ItemCreated(514 /// Id of the collection where item was created.515 CollectionId,516 /// Id of an item. Unique within the collection.517 TokenId,518 /// Owner of newly created item519 T::CrossAccountId,520 /// Always 1 for NFT521 u128,522 ),523524 /// Collection item was burned.525 ItemDestroyed(526 /// Id of the collection where item was destroyed.527 CollectionId,528 /// Identifier of burned NFT.529 TokenId,530 /// Which user has destroyed its tokens.531 T::CrossAccountId,532 /// Amount of token pieces destroed. Always 1 for NFT.533 u128,534 ),535536 /// Item was transferred537 Transfer(538 /// Id of collection to which item is belong.539 CollectionId,540 /// Id of an item.541 TokenId,542 /// Original owner of item.543 T::CrossAccountId,544 /// New owner of item.545 T::CrossAccountId,546 /// Amount of token pieces transfered. Always 1 for NFT.547 u128,548 ),549550 /// Amount pieces of token owned by `sender` was approved for `spender`.551 Approved(552 /// Id of collection to which item is belong.553 CollectionId,554 /// Id of an item.555 TokenId,556 /// Original owner of item.557 T::CrossAccountId,558 /// Id for which the approval was granted.559 T::CrossAccountId,560 /// Amount of token pieces transfered. Always 1 for NFT.561 u128,562 ),563564 /// A `sender` approves operations on all owned tokens for `spender`.565 ApprovedForAll(566 /// Id of collection to which item is belong.567 CollectionId,568 /// Owner of a wallet.569 T::CrossAccountId,570 /// Id for which operator status was granted or rewoked.571 T::CrossAccountId,572 /// Is operator status granted or revoked?573 bool,574 ),575576 /// The colletion property has been added or edited.577 CollectionPropertySet(578 /// Id of collection to which property has been set.579 CollectionId,580 /// The property that was set.581 PropertyKey,582 ),583584 /// The property has been deleted.585 CollectionPropertyDeleted(586 /// Id of collection to which property has been deleted.587 CollectionId,588 /// The property that was deleted.589 PropertyKey,590 ),591592 /// The token property has been added or edited.593 TokenPropertySet(594 /// Identifier of the collection whose token has the property set.595 CollectionId,596 /// The token for which the property was set.597 TokenId,598 /// The property that was set.599 PropertyKey,600 ),601602 /// The token property has been deleted.603 TokenPropertyDeleted(604 /// Identifier of the collection whose token has the property deleted.605 CollectionId,606 /// The token for which the property was deleted.607 TokenId,608 /// The property that was deleted.609 PropertyKey,610 ),611612 /// The token property permission of a collection has been set.613 PropertyPermissionSet(614 /// ID of collection to which property permission has been set.615 CollectionId,616 /// The property permission that was set.617 PropertyKey,618 ),619620 /// Address was added to the allow list.621 AllowListAddressAdded(622 /// ID of the affected collection.623 CollectionId,624 /// Address of the added account.625 T::CrossAccountId,626 ),627628 /// Address was removed from the allow list.629 AllowListAddressRemoved(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the removed account.633 T::CrossAccountId,634 ),635636 /// Collection admin was added.637 CollectionAdminAdded(638 /// ID of the affected collection.639 CollectionId,640 /// Admin address.641 T::CrossAccountId,642 ),643644 /// Collection admin was removed.645 CollectionAdminRemoved(646 /// ID of the affected collection.647 CollectionId,648 /// Removed admin address.649 T::CrossAccountId,650 ),651652 /// Collection limits were set.653 CollectionLimitSet(654 /// ID of the affected collection.655 CollectionId,656 ),657658 /// Collection owned was changed.659 CollectionOwnerChanged(660 /// ID of the affected collection.661 CollectionId,662 /// New owner address.663 T::AccountId,664 ),665666 /// Collection permissions were set.667 CollectionPermissionSet(668 /// ID of the affected collection.669 CollectionId,670 ),671672 /// Collection sponsor was set.673 CollectionSponsorSet(674 /// ID of the affected collection.675 CollectionId,676 /// New sponsor address.677 T::AccountId,678 ),679680 /// New sponsor was confirm.681 SponsorshipConfirmed(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// Collection sponsor was removed.689 CollectionSponsorRemoved(690 /// ID of the affected collection.691 CollectionId,692 ),693 }694695 #[pallet::error]696 pub enum Error<T> {697 /// This collection does not exist.698 CollectionNotFound,699 /// Sender parameter and item owner must be equal.700 MustBeTokenOwner,701 /// No permission to perform action702 NoPermission,703 /// Destroying only empty collections is allowed704 CantDestroyNotEmptyCollection,705 /// Collection is not in mint mode.706 PublicMintingNotAllowed,707 /// Address is not in allow list.708 AddressNotInAllowlist,709710 /// Collection name can not be longer than 63 char.711 CollectionNameLimitExceeded,712 /// Collection description can not be longer than 255 char.713 CollectionDescriptionLimitExceeded,714 /// Token prefix can not be longer than 15 char.715 CollectionTokenPrefixLimitExceeded,716 /// Total collections bound exceeded.717 TotalCollectionsLimitExceeded,718 /// Exceeded max admin count719 CollectionAdminCountExceeded,720 /// Collection limit bounds per collection exceeded721 CollectionLimitBoundsExceeded,722 /// Tried to enable permissions which are only permitted to be disabled723 OwnerPermissionsCantBeReverted,724 /// Collection settings not allowing items transferring725 TransferNotAllowed,726 /// Account token limit exceeded per collection727 AccountTokenLimitExceeded,728 /// Collection token limit exceeded729 CollectionTokenLimitExceeded,730 /// Metadata flag frozen731 MetadataFlagFrozen,732733 /// Item does not exist734 TokenNotFound,735 /// Item is balance not enough736 TokenValueTooLow,737 /// Requested value is more than the approved738 ApprovedValueTooLow,739 /// Tried to approve more than owned740 CantApproveMoreThanOwned,741 /// Only spending from eth mirror could be approved742 AddressIsNotEthMirror,743744 /// Can't transfer tokens to ethereum zero address745 AddressIsZero,746747 /// The operation is not supported748 UnsupportedOperation,749750 /// Insufficient funds to perform an action751 NotSufficientFounds,752753 /// User does not satisfy the nesting rule754 UserIsNotAllowedToNest,755 /// Only tokens from specific collections may nest tokens under this one756 SourceCollectionIsNotAllowedToNest,757758 /// Tried to store more data than allowed in collection field759 CollectionFieldSizeExceeded,760761 /// Tried to store more property data than allowed762 NoSpaceForProperty,763764 /// Tried to store more property keys than allowed765 PropertyLimitReached,766767 /// Property key is too long768 PropertyKeyIsTooLong,769770 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed771 InvalidCharacterInPropertyKey,772773 /// Empty property keys are forbidden774 EmptyPropertyKey,775776 /// Tried to access an external collection with an internal API777 CollectionIsExternal,778779 /// Tried to access an internal collection with an external API780 CollectionIsInternal,781782 /// This address is not set as sponsor, use setCollectionSponsor first.783 ConfirmSponsorshipFail,784785 /// The user is not an administrator.786 UserIsNotCollectionAdmin,787788 /// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.789 FungibleItemsHaveNoId,790791 /// Not Fungible item data used to mint in Fungible collection.792 NotFungibleDataUsedToMintFungibleCollectionToken,793 }794795 /// Storage of the count of created collections. Essentially contains the last collection ID.796 #[pallet::storage]797 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799 /// Storage of the count of deleted collections.800 #[pallet::storage]801 pub type DestroyedCollectionCount<T> =802 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804 /// Storage of collection info.805 #[pallet::storage]806 pub type CollectionById<T> = StorageMap<807 Hasher = Blake2_128Concat,808 Key = CollectionId,809 Value = Collection<<T as frame_system::Config>::AccountId>,810 QueryKind = OptionQuery,811 >;812813 /// Storage of collection properties.814 #[pallet::storage]815 #[pallet::getter(fn collection_properties)]816 pub type CollectionProperties<T> = StorageMap<817 Hasher = Blake2_128Concat,818 Key = CollectionId,819 Value = CollectionPropertiesT,820 QueryKind = ValueQuery,821 >;822823 /// Storage of token property permissions of a collection.824 #[pallet::storage]825 #[pallet::getter(fn property_permissions)]826 pub type CollectionPropertyPermissions<T> = StorageMap<827 Hasher = Blake2_128Concat,828 Key = CollectionId,829 Value = PropertiesPermissionMap,830 QueryKind = ValueQuery,831 >;832833 /// Storage of the amount of collection admins.834 #[pallet::storage]835 pub type AdminAmount<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = u32,839 QueryKind = ValueQuery,840 >;841842 /// List of collection admins.843 #[pallet::storage]844 pub type IsAdmin<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 /// Allowlisted collection users.854 #[pallet::storage]855 pub type Allowlist<T: Config> = StorageNMap<856 Key = (857 Key<Blake2_128Concat, CollectionId>,858 Key<Blake2_128Concat, T::CrossAccountId>,859 ),860 Value = bool,861 QueryKind = ValueQuery,862 >;863864 /// Not used by code, exists only to provide some types to metadata.865 #[pallet::storage]866 pub type DummyStorageValue<T: Config> = StorageValue<867 Value = (868 CollectionStats,869 CollectionId,870 TokenId,871 TokenChild,872 PhantomType<(873 TokenData<T::CrossAccountId>,874 RpcCollection<T::AccountId>,875 // PoV Estimate Info876 PovInfo,877 )>,878 ),879 QueryKind = OptionQuery,880 >;881}882883enum LazyValueState<'a, T> {884 Pending(Box<dyn FnOnce() -> T + 'a>),885 InProgress,886 Computed(T),887}888889/// Value representation with delayed initialization time.890pub struct LazyValue<'a, T> {891 state: LazyValueState<'a, T>,892}893894impl<'a, T> LazyValue<'a, T> {895 /// Create a new LazyValue.896 pub fn new(f: impl FnOnce() -> T + 'a) -> Self {897 Self {898 state: LazyValueState::Pending(Box::new(f)),899 }900 }901902 /// Get the value. If it is called the first time, the value will be initialized.903 pub fn value(&mut self) -> &T {904 self.force_value();905 self.value_mut()906 }907908 /// Get the value. If it is called the first time, the value will be initialized.909 pub fn value_mut(&mut self) -> &mut T {910 self.force_value();911912 if let LazyValueState::Computed(value) = &mut self.state {913 value914 } else {915 unreachable!()916 }917 }918919 fn into_inner(mut self) -> T {920 self.force_value();921 if let LazyValueState::Computed(value) = self.state {922 value923 } else {924 unreachable!()925 }926 }927928 /// Is value initialized?929 pub fn has_value(&self) -> bool {930 matches!(self.state, LazyValueState::Computed(_))931 }932933 fn force_value(&mut self) {934 use LazyValueState::*;935936 if self.has_value() {937 return;938 }939940 match sp_std::mem::replace(&mut self.state, InProgress) {941 Pending(f) => self.state = Computed(f()),942 _ => panic!("recursion isn't supported"),943 }944 }945}946947/// An issuer of a collection.948pub enum CollectionIssuer<CrossAccountId> {949 /// A user who creates the collection.950 User(CrossAccountId),951952 /// The internal mechanisms are creating the collection.953 Internals,954}955956fn check_token_permissions<T: Config>(957 collection_admin_permitted: bool,958 token_owner_permitted: bool,959 is_collection_admin: &mut LazyValue<bool>,960 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,961 is_token_exist: &mut LazyValue<bool>,962) -> DispatchResult {963 if !(collection_admin_permitted && *is_collection_admin.value()964 || token_owner_permitted && (*is_token_owner.value())?)965 {966 fail!(<Error<T>>::NoPermission);967 }968969 let token_exist_due_to_owner_check_success =970 is_token_owner.has_value() && (*is_token_owner.value())?;971972 // If the token owner check has occurred and succeeded,973 // we know the token exists (otherwise, the owner check must fail).974 if !token_exist_due_to_owner_check_success {975 // If the token owner check didn't occur,976 // we must check the token's existence ourselves.977 if !is_token_exist.value() {978 fail!(<Error<T>>::TokenNotFound);979 }980 }981982 Ok(())983}984985impl<T: Config> Pallet<T> {986 /// Enshure that receiver address is correct.987 ///988 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.989 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {990 ensure!(991 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,992 <Error<T>>::AddressIsZero993 );994 Ok(())995 }996997 /// Get a vector of collection admins.998 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {999 <IsAdmin<T>>::iter_prefix((collection,))1000 .map(|(a, _)| a)1001 .collect()1002 }10031004 /// Get a vector of users allowed to mint tokens.1005 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {1006 <Allowlist<T>>::iter_prefix((collection,))1007 .map(|(a, _)| a)1008 .collect()1009 }10101011 /// Is `user` allowed to mint token in `collection`.1012 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1013 <Allowlist<T>>::get((collection, user))1014 }10151016 /// Get statistics of collections.1017 pub fn collection_stats() -> CollectionStats {1018 let created = <CreatedCollectionCount<T>>::get();1019 let destroyed = <DestroyedCollectionCount<T>>::get();1020 CollectionStats {1021 created: created.0,1022 destroyed: destroyed.0,1023 alive: created.0 - destroyed.0,1024 }1025 }10261027 /// Get the effective limits for the collection.1028 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1029 let collection = <CollectionById<T>>::get(collection)?;1030 let limits = collection.limits;1031 let effective_limits = CollectionLimits {1032 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1033 sponsored_data_size: Some(limits.sponsored_data_size()),1034 sponsored_data_rate_limit: Some(1035 limits1036 .sponsored_data_rate_limit1037 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1038 ),1039 token_limit: Some(limits.token_limit()),1040 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1041 match collection.mode {1042 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1043 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1044 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1045 },1046 )),1047 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1048 owner_can_transfer: Some(limits.owner_can_transfer()),1049 owner_can_destroy: Some(limits.owner_can_destroy()),1050 transfers_enabled: Some(limits.transfers_enabled()),1051 };10521053 Some(effective_limits)1054 }10551056 /// Returns information about the `collection` adapted for rpc.1057 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1058 let Collection {1059 name,1060 description,1061 owner,1062 mode,1063 token_prefix,1064 sponsorship,1065 limits,1066 permissions,1067 flags,1068 } = <CollectionById<T>>::get(collection)?;10691070 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1071 .into_iter()1072 .map(|(key, permission)| PropertyKeyPermission { key, permission })1073 .collect();10741075 let properties = <CollectionProperties<T>>::get(collection)1076 .into_iter()1077 .map(|(key, value)| Property { key, value })1078 .collect();10791080 let permissions = CollectionPermissions {1081 access: Some(permissions.access()),1082 mint_mode: Some(permissions.mint_mode()),1083 nesting: Some(permissions.nesting().clone()),1084 };10851086 Some(RpcCollection {1087 name: name.into_inner(),1088 description: description.into_inner(),1089 owner,1090 mode,1091 token_prefix: token_prefix.into_inner(),1092 sponsorship,1093 limits,1094 permissions,1095 token_property_permissions,1096 properties,1097 read_only: flags.external,10981099 flags: RpcCollectionFlags {1100 foreign: flags.foreign,1101 erc721metadata: flags.erc721metadata,1102 },1103 })1104 }1105}11061107macro_rules! limit_default {1108 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1109 $(1110 if let Some($new) = $new.$field {1111 let $old = $old.$field($($arg)?);1112 let _ = $new;1113 let _ = $old;1114 $check1115 } else {1116 $new.$field = $old.$field1117 }1118 )*1119 }};1120}1121macro_rules! limit_default_clone {1122 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1123 $(1124 if let Some($new) = $new.$field.clone() {1125 let $old = $old.$field($($arg)?);1126 let _ = $new;1127 let _ = $old;1128 $check1129 } else {1130 $new.$field = $old.$field.clone()1131 }1132 )*1133 }};1134}11351136impl<T: Config> Pallet<T> {1137 /// Create new collection.1138 ///1139 /// * `owner` - The owner of the collection.1140 /// * `issuer` - An entity that creates the collection.1141 /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1142 pub fn init_collection(1143 owner: T::CrossAccountId,1144 issuer: CollectionIssuer<T::CrossAccountId>,1145 data: CreateCollectionData<T::CrossAccountId>,1146 ) -> Result<CollectionId, DispatchError> {1147 match issuer {1148 CollectionIssuer::User(payer) => {1149 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);11501151 // Take a (non-refundable) deposit of collection creation1152 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1153 imbalance.subsume(<T as Config>::Currency::deposit(1154 &T::TreasuryAccountId::get(),1155 T::CollectionCreationPrice::get(),1156 Precision::Exact,1157 )?);1158 let credit = <T as Config>::Currency::settle(1159 payer.as_sub(),1160 imbalance,1161 Preservation::Preserve,1162 )1163 .map_err(|_| Error::<T>::NotSufficientFounds)?;11641165 debug_assert!(credit.peek().is_zero());1166 }1167 CollectionIssuer::Internals => {}1168 }11691170 {1171 ensure!(1172 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1173 Error::<T>::CollectionTokenPrefixLimitExceeded1174 );1175 }11761177 let created_count = <CreatedCollectionCount<T>>::get()1178 .01179 .checked_add(1)1180 .ok_or(ArithmeticError::Overflow)?;1181 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1182 let id = CollectionId(created_count);11831184 // bound Total number of collections1185 ensure!(1186 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1187 <Error<T>>::TotalCollectionsLimitExceeded1188 );11891190 // =========11911192 let collection = Collection {1193 owner: owner.as_sub().clone(),1194 name: data.name,1195 mode: data.mode.clone(),1196 description: data.description,1197 token_prefix: data.token_prefix,1198 sponsorship: data1199 .pending_sponsor1200 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1201 .unwrap_or_default(),1202 limits: data1203 .limits1204 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1205 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1206 permissions: data1207 .permissions1208 .map(|permissions| {1209 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1210 })1211 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1212 flags: data.flags,1213 };12141215 let mut collection_properties = CollectionPropertiesT::new();1216 collection_properties1217 .try_set_from_iter(data.properties.into_iter())1218 .map_err(<Error<T>>::from)?;12191220 CollectionProperties::<T>::insert(id, collection_properties);12211222 let mut token_props_permissions = PropertiesPermissionMap::new();1223 token_props_permissions1224 .try_set_from_iter(data.token_property_permissions.into_iter())1225 .map_err(<Error<T>>::from)?;12261227 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12281229 let mut admin_amount = 0u32;1230 for admin in data.admin_list.iter() {1231 if !<IsAdmin<T>>::get((id, admin)) {1232 <IsAdmin<T>>::insert((id, admin), true);1233 admin_amount = admin_amount1234 .checked_add(1)1235 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1236 }1237 }1238 ensure!(1239 admin_amount <= Self::collection_admins_limit(),1240 <Error<T>>::CollectionAdminCountExceeded,1241 );1242 <AdminAmount<T>>::insert(id, admin_amount);12431244 <CreatedCollectionCount<T>>::put(created_count);1245 <Pallet<T>>::deposit_event(Event::CollectionCreated(1246 id,1247 data.mode.id(),1248 owner.as_sub().clone(),1249 ));1250 <PalletEvm<T>>::deposit_log(1251 erc::CollectionHelpersEvents::CollectionCreated {1252 owner: *owner.as_eth(),1253 collection_id: eth::collection_id_to_address(id),1254 }1255 .to_log(T::ContractAddress::get()),1256 );1257 <CollectionById<T>>::insert(id, collection);1258 Ok(id)1259 }12601261 /// Destroy collection.1262 ///1263 /// * `collection` - Collection handler.1264 /// * `sender` - The owner or administrator of the collection.1265 pub fn destroy_collection(1266 collection: CollectionHandle<T>,1267 sender: &T::CrossAccountId,1268 ) -> DispatchResult {1269 ensure!(1270 collection.limits.owner_can_destroy(),1271 <Error<T>>::NoPermission,1272 );1273 collection.check_is_owner(sender)?;12741275 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1276 .01277 .checked_add(1)1278 .ok_or(ArithmeticError::Overflow)?;12791280 // =========12811282 <DestroyedCollectionCount<T>>::put(destroyed_collections);1283 <CollectionById<T>>::remove(collection.id);1284 <AdminAmount<T>>::remove(collection.id);1285 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1286 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1287 <CollectionProperties<T>>::remove(collection.id);12881289 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12901291 <PalletEvm<T>>::deposit_log(1292 erc::CollectionHelpersEvents::CollectionDestroyed {1293 collection_id: eth::collection_id_to_address(collection.id),1294 }1295 .to_log(T::ContractAddress::get()),1296 );1297 Ok(())1298 }12991300 /// This function sets or removes a collection properties according to1301 /// `properties_updates` contents:1302 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1303 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1304 ///1305 /// This function fires an event for each property change.1306 /// In case of an error, all the changes (including the events) will be reverted1307 /// since the function is transactional.1308 #[transactional]1309 fn modify_collection_properties(1310 collection: &CollectionHandle<T>,1311 sender: &T::CrossAccountId,1312 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1313 ) -> DispatchResult {1314 collection.check_is_owner_or_admin(sender)?;13151316 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13171318 for (key, value) in properties_updates {1319 match value {1320 Some(value) => {1321 stored_properties1322 .try_set(key.clone(), value)1323 .map_err(<Error<T>>::from)?;13241325 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1326 <PalletEvm<T>>::deposit_log(1327 erc::CollectionHelpersEvents::CollectionChanged {1328 collection_id: eth::collection_id_to_address(collection.id),1329 }1330 .to_log(T::ContractAddress::get()),1331 );1332 }1333 None => {1334 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13351336 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1337 <PalletEvm<T>>::deposit_log(1338 erc::CollectionHelpersEvents::CollectionChanged {1339 collection_id: eth::collection_id_to_address(collection.id),1340 }1341 .to_log(T::ContractAddress::get()),1342 );1343 }1344 }1345 }13461347 <CollectionProperties<T>>::set(collection.id, stored_properties);13481349 Ok(())1350 }13511352 /// Sets or unsets the approval of a given operator.1353 ///1354 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1355 /// - `owner`: Token owner1356 /// - `operator`: Operator1357 /// - `approve`: Should operator status be granted or revoked?1358 pub fn set_allowance_for_all(1359 collection: &CollectionHandle<T>,1360 owner: &T::CrossAccountId,1361 operator: &T::CrossAccountId,1362 approve: bool,1363 set_allowance: impl FnOnce(),1364 log: evm_coder::ethereum::Log,1365 ) -> DispatchResult {1366 if collection.permissions.access() == AccessMode::AllowList {1367 collection.check_allowlist(owner)?;1368 collection.check_allowlist(operator)?;1369 }13701371 Self::ensure_correct_receiver(operator)?;13721373 set_allowance();13741375 <PalletEvm<T>>::deposit_log(log);1376 Self::deposit_event(Event::ApprovedForAll(1377 collection.id,1378 owner.clone(),1379 operator.clone(),1380 approve,1381 ));1382 Ok(())1383 }13841385 /// Set collection property.1386 ///1387 /// * `collection` - Collection handler.1388 /// * `sender` - The owner or administrator of the collection.1389 /// * `property` - The property to set.1390 pub fn set_collection_property(1391 collection: &CollectionHandle<T>,1392 sender: &T::CrossAccountId,1393 property: Property,1394 ) -> DispatchResult {1395 Self::set_collection_properties(collection, sender, [property].into_iter())1396 }13971398 /// Set a scoped collection property, where the scope is a special prefix1399 /// prohibiting a user access to change the property directly.1400 ///1401 /// * `collection_id` - ID of the collection for which the property is being set.1402 /// * `scope` - Property scope.1403 /// * `property` - The property to set.1404 pub fn set_scoped_collection_property(1405 collection_id: CollectionId,1406 scope: PropertyScope,1407 property: Property,1408 ) -> DispatchResult {1409 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1410 properties.try_scoped_set(scope, property.key, property.value)1411 })1412 .map_err(<Error<T>>::from)?;14131414 Ok(())1415 }14161417 /// Set scoped collection properties, where the scope is a special prefix1418 /// prohibiting a user access to change the properties directly.1419 ///1420 /// * `collection_id` - ID of the collection for which the properties is being set.1421 /// * `scope` - Property scope.1422 /// * `properties` - The properties to set.1423 pub fn set_scoped_collection_properties(1424 collection_id: CollectionId,1425 scope: PropertyScope,1426 properties: impl Iterator<Item = Property>,1427 ) -> DispatchResult {1428 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1429 stored_properties.try_scoped_set_from_iter(scope, properties)1430 })1431 .map_err(<Error<T>>::from)?;14321433 Ok(())1434 }14351436 /// Set collection properties.1437 ///1438 /// * `collection` - Collection handler.1439 /// * `sender` - The owner or administrator of the collection.1440 /// * `properties` - The properties to set.1441 pub fn set_collection_properties(1442 collection: &CollectionHandle<T>,1443 sender: &T::CrossAccountId,1444 properties: impl Iterator<Item = Property>,1445 ) -> DispatchResult {1446 Self::modify_collection_properties(1447 collection,1448 sender,1449 properties.map(|property| (property.key, Some(property.value))),1450 )1451 }14521453 /// Delete collection property.1454 ///1455 /// * `collection` - Collection handler.1456 /// * `sender` - The owner or administrator of the collection.1457 /// * `property` - The property to delete.1458 pub fn delete_collection_property(1459 collection: &CollectionHandle<T>,1460 sender: &T::CrossAccountId,1461 property_key: PropertyKey,1462 ) -> DispatchResult {1463 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1464 }14651466 /// Delete collection properties.1467 ///1468 /// * `collection` - Collection handler.1469 /// * `sender` - The owner or administrator of the collection.1470 /// * `properties` - The properties to delete.1471 pub fn delete_collection_properties(1472 collection: &CollectionHandle<T>,1473 sender: &T::CrossAccountId,1474 property_keys: impl Iterator<Item = PropertyKey>,1475 ) -> DispatchResult {1476 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1477 }14781479 /// Set collection propetry permission without any checks.1480 ///1481 /// Used for migrations.1482 ///1483 /// * `collection` - Collection handler.1484 /// * `property_permissions` - Property permissions.1485 pub fn set_property_permission_unchecked(1486 collection: CollectionId,1487 property_permission: PropertyKeyPermission,1488 ) -> DispatchResult {1489 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1490 permissions.try_set(property_permission.key, property_permission.permission)1491 })1492 .map_err(<Error<T>>::from)?;1493 Ok(())1494 }14951496 /// Set collection property permission.1497 ///1498 /// * `collection` - Collection handler.1499 /// * `sender` - The owner or administrator of the collection.1500 /// * `property_permission` - Property permission.1501 pub fn set_property_permission(1502 collection: &CollectionHandle<T>,1503 sender: &T::CrossAccountId,1504 property_permission: PropertyKeyPermission,1505 ) -> DispatchResult {1506 Self::set_scoped_property_permission(1507 collection,1508 sender,1509 PropertyScope::None,1510 property_permission,1511 )1512 }15131514 /// Set collection property permission with scope.1515 ///1516 /// * `collection` - Collection handler.1517 /// * `sender` - The owner or administrator of the collection.1518 /// * `scope` - Property scope.1519 /// * `property_permission` - Property permission.1520 pub fn set_scoped_property_permission(1521 collection: &CollectionHandle<T>,1522 sender: &T::CrossAccountId,1523 scope: PropertyScope,1524 property_permission: PropertyKeyPermission,1525 ) -> DispatchResult {1526 collection.check_is_owner_or_admin(sender)?;15271528 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1529 let current_permission = all_permissions.get(&property_permission.key);1530 if matches![1531 current_permission,1532 Some(PropertyPermission { mutable: false, .. })1533 ] {1534 return Err(<Error<T>>::NoPermission.into());1535 }15361537 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1538 let property_permission = property_permission.clone();1539 permissions.try_scoped_set(1540 scope,1541 property_permission.key,1542 property_permission.permission,1543 )1544 })1545 .map_err(<Error<T>>::from)?;15461547 Self::deposit_event(Event::PropertyPermissionSet(1548 collection.id,1549 property_permission.key,1550 ));1551 <PalletEvm<T>>::deposit_log(1552 erc::CollectionHelpersEvents::CollectionChanged {1553 collection_id: eth::collection_id_to_address(collection.id),1554 }1555 .to_log(T::ContractAddress::get()),1556 );15571558 Ok(())1559 }15601561 /// Set token property permission.1562 ///1563 /// * `collection` - Collection handler.1564 /// * `sender` - The owner or administrator of the collection.1565 /// * `property_permissions` - Property permissions.1566 #[transactional]1567 pub fn set_token_property_permissions(1568 collection: &CollectionHandle<T>,1569 sender: &T::CrossAccountId,1570 property_permissions: Vec<PropertyKeyPermission>,1571 ) -> DispatchResult {1572 Self::set_scoped_token_property_permissions(1573 collection,1574 sender,1575 PropertyScope::None,1576 property_permissions,1577 )1578 }15791580 /// Set token property permission with scope.1581 ///1582 /// * `collection` - Collection handler.1583 /// * `sender` - The owner or administrator of the collection.1584 /// * `scope` - Property scope.1585 /// * `property_permissions` - Property permissions.1586 #[transactional]1587 pub fn set_scoped_token_property_permissions(1588 collection: &CollectionHandle<T>,1589 sender: &T::CrossAccountId,1590 scope: PropertyScope,1591 property_permissions: Vec<PropertyKeyPermission>,1592 ) -> DispatchResult {1593 for prop_pemission in property_permissions {1594 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1595 }15961597 Ok(())1598 }15991600 /// Get collection property.1601 pub fn get_collection_property(1602 collection_id: CollectionId,1603 key: &PropertyKey,1604 ) -> Option<PropertyValue> {1605 Self::collection_properties(collection_id).get(key).cloned()1606 }16071608 /// Convert byte vector to property key vector.1609 pub fn bytes_keys_to_property_keys(1610 keys: Vec<Vec<u8>>,1611 ) -> Result<Vec<PropertyKey>, DispatchError> {1612 keys.into_iter()1613 .map(|key| -> Result<PropertyKey, DispatchError> {1614 key.try_into()1615 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1616 })1617 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1618 }16191620 /// Get properties according to given keys.1621 pub fn filter_collection_properties(1622 collection_id: CollectionId,1623 keys: Option<Vec<PropertyKey>>,1624 ) -> Result<Vec<Property>, DispatchError> {1625 let properties = Self::collection_properties(collection_id);16261627 let properties = keys1628 .map(|keys| {1629 keys.into_iter()1630 .filter_map(|key| {1631 properties.get(&key).map(|value| Property {1632 key,1633 value: value.clone(),1634 })1635 })1636 .collect()1637 })1638 .unwrap_or_else(|| {1639 properties1640 .into_iter()1641 .map(|(key, value)| Property { key, value })1642 .collect()1643 });16441645 Ok(properties)1646 }16471648 /// Get property permissions according to given keys.1649 pub fn filter_property_permissions(1650 collection_id: CollectionId,1651 keys: Option<Vec<PropertyKey>>,1652 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1653 let permissions = Self::property_permissions(collection_id);16541655 let key_permissions = keys1656 .map(|keys| {1657 keys.into_iter()1658 .filter_map(|key| {1659 permissions1660 .get(&key)1661 .map(|permission| PropertyKeyPermission {1662 key,1663 permission: permission.clone(),1664 })1665 })1666 .collect()1667 })1668 .unwrap_or_else(|| {1669 permissions1670 .into_iter()1671 .map(|(key, permission)| PropertyKeyPermission { key, permission })1672 .collect()1673 });16741675 Ok(key_permissions)1676 }16771678 /// Toggle `user` participation in the `collection`'s allow list.1679 /// #### Store read/writes1680 /// 1 writes1681 pub fn toggle_allowlist(1682 collection: &CollectionHandle<T>,1683 sender: &T::CrossAccountId,1684 user: &T::CrossAccountId,1685 allowed: bool,1686 ) -> DispatchResult {1687 collection.check_is_owner_or_admin(sender)?;16881689 // =========16901691 if allowed {1692 <Allowlist<T>>::insert((collection.id, user), true);1693 Self::deposit_event(Event::<T>::AllowListAddressAdded(1694 collection.id,1695 user.clone(),1696 ));1697 } else {1698 <Allowlist<T>>::remove((collection.id, user));1699 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1700 collection.id,1701 user.clone(),1702 ));1703 }17041705 <PalletEvm<T>>::deposit_log(1706 erc::CollectionHelpersEvents::CollectionChanged {1707 collection_id: eth::collection_id_to_address(collection.id),1708 }1709 .to_log(T::ContractAddress::get()),1710 );17111712 Ok(())1713 }17141715 /// Toggle `user` participation in the `collection`'s admin list.1716 /// #### Store read/writes1717 /// 2 reads, 2 writes1718 pub fn toggle_admin(1719 collection: &CollectionHandle<T>,1720 sender: &T::CrossAccountId,1721 user: &T::CrossAccountId,1722 admin: bool,1723 ) -> DispatchResult {1724 collection.check_is_internal()?;1725 collection.check_is_owner(sender)?;17261727 let is_admin = <IsAdmin<T>>::get((collection.id, user));1728 if is_admin == admin {1729 if admin {1730 return Ok(());1731 } else {1732 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1733 }1734 }1735 let amount = <AdminAmount<T>>::get(collection.id);17361737 // =========17381739 if admin {1740 let amount = amount1741 .checked_add(1)1742 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1743 ensure!(1744 amount <= Self::collection_admins_limit(),1745 <Error<T>>::CollectionAdminCountExceeded,1746 );17471748 <AdminAmount<T>>::insert(collection.id, amount);1749 <IsAdmin<T>>::insert((collection.id, user), true);17501751 Self::deposit_event(Event::<T>::CollectionAdminAdded(1752 collection.id,1753 user.clone(),1754 ));1755 } else {1756 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1757 <IsAdmin<T>>::remove((collection.id, user));17581759 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1760 collection.id,1761 user.clone(),1762 ));1763 }17641765 <PalletEvm<T>>::deposit_log(1766 erc::CollectionHelpersEvents::CollectionChanged {1767 collection_id: eth::collection_id_to_address(collection.id),1768 }1769 .to_log(T::ContractAddress::get()),1770 );17711772 Ok(())1773 }17741775 /// Update collection limits.1776 pub fn update_limits(1777 user: &T::CrossAccountId,1778 collection: &mut CollectionHandle<T>,1779 new_limit: CollectionLimits,1780 ) -> DispatchResult {1781 collection.check_is_internal()?;1782 collection.check_is_owner_or_admin(user)?;17831784 collection.limits =1785 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17861787 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1788 <PalletEvm<T>>::deposit_log(1789 erc::CollectionHelpersEvents::CollectionChanged {1790 collection_id: eth::collection_id_to_address(collection.id),1791 }1792 .to_log(T::ContractAddress::get()),1793 );17941795 collection.save()1796 }17971798 /// Merge set fields from `new_limit` to `old_limit`.1799 fn clamp_limits(1800 mode: CollectionMode,1801 old_limit: &CollectionLimits,1802 mut new_limit: CollectionLimits,1803 ) -> Result<CollectionLimits, DispatchError> {1804 let limits = old_limit;1805 limit_default!(old_limit, new_limit,1806 account_token_ownership_limit => ensure!(1807 new_limit <= MAX_TOKEN_OWNERSHIP,1808 <Error<T>>::CollectionLimitBoundsExceeded,1809 ),1810 sponsored_data_size => ensure!(1811 new_limit <= CUSTOM_DATA_LIMIT,1812 <Error<T>>::CollectionLimitBoundsExceeded,1813 ),18141815 sponsored_data_rate_limit => {},1816 token_limit => ensure!(1817 old_limit >= new_limit && new_limit > 0,1818 <Error<T>>::CollectionTokenLimitExceeded1819 ),18201821 sponsor_transfer_timeout(match mode {1822 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1823 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1825 }) => ensure!(1826 new_limit <= MAX_SPONSOR_TIMEOUT,1827 <Error<T>>::CollectionLimitBoundsExceeded,1828 ),1829 sponsor_approve_timeout => {},1830 owner_can_transfer => ensure!(1831 !limits.owner_can_transfer_instaled() ||1832 old_limit || !new_limit,1833 <Error<T>>::OwnerPermissionsCantBeReverted,1834 ),1835 owner_can_destroy => ensure!(1836 old_limit || !new_limit,1837 <Error<T>>::OwnerPermissionsCantBeReverted,1838 ),1839 transfers_enabled => {},1840 );1841 Ok(new_limit)1842 }18431844 /// Update collection permissions.1845 pub fn update_permissions(1846 user: &T::CrossAccountId,1847 collection: &mut CollectionHandle<T>,1848 new_permission: CollectionPermissions,1849 ) -> DispatchResult {1850 collection.check_is_internal()?;1851 collection.check_is_owner_or_admin(user)?;1852 collection.permissions = Self::clamp_permissions(1853 collection.mode.clone(),1854 &collection.permissions,1855 new_permission,1856 )?;18571858 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1859 <PalletEvm<T>>::deposit_log(1860 erc::CollectionHelpersEvents::CollectionChanged {1861 collection_id: eth::collection_id_to_address(collection.id),1862 }1863 .to_log(T::ContractAddress::get()),1864 );18651866 collection.save()1867 }18681869 /// Merge set fields from `new_permission` to `old_permission`.1870 fn clamp_permissions(1871 _mode: CollectionMode,1872 old_permission: &CollectionPermissions,1873 mut new_permission: CollectionPermissions,1874 ) -> Result<CollectionPermissions, DispatchError> {1875 limit_default_clone!(old_permission, new_permission,1876 access => {},1877 mint_mode => {},1878 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1879 );1880 Ok(new_permission)1881 }18821883 /// Repair possibly broken properties of a collection.1884 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1885 CollectionProperties::<T>::mutate(collection_id, |properties| {1886 properties.recompute_consumed_space();1887 });18881889 Ok(())1890 }1891}18921893/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1894#[macro_export]1895macro_rules! unsupported {1896 ($runtime:path) => {1897 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1898 };1899}19001901/// Return weights for various worst-case operations.1902pub trait CommonWeightInfo<CrossAccountId> {1903 /// Weight of item creation.1904 fn create_item(data: &CreateItemData) -> Weight {1905 Self::create_multiple_items(from_ref(data))1906 }19071908 /// Weight of items creation.1909 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19101911 /// Weight of items creation.1912 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19131914 /// The weight of the burning item.1915 fn burn_item() -> Weight;19161917 /// Property setting weight.1918 ///1919 /// * `amount`- The number of properties to set.1920 fn set_collection_properties(amount: u32) -> Weight;19211922 /// Collection property deletion weight.1923 ///1924 /// * `amount`- The number of properties to set.1925 fn delete_collection_properties(amount: u32) -> Weight {1926 Self::set_collection_properties(amount)1927 }19281929 /// Token property setting weight.1930 ///1931 /// * `amount`- The number of properties to set.1932 fn set_token_properties(amount: u32) -> Weight;19331934 /// Token property deletion weight.1935 ///1936 /// * `amount`- The number of properties to delete.1937 fn delete_token_properties(amount: u32) -> Weight {1938 Self::set_token_properties(amount)1939 }19401941 /// Token property permissions set weight.1942 ///1943 /// * `amount`- The number of property permissions to set.1944 fn set_token_property_permissions(amount: u32) -> Weight;19451946 /// Transfer price of the token or its parts.1947 fn transfer() -> Weight;19481949 /// The price of setting the permission of the operation from another user.1950 fn approve() -> Weight;19511952 /// The price of setting the permission of the operation from another user for eth mirror.1953 fn approve_from() -> Weight;19541955 /// Transfer price from another user.1956 fn transfer_from() -> Weight;19571958 /// The price of burning a token from another user.1959 fn burn_from() -> Weight;19601961 /// The price of setting approval for all1962 fn set_allowance_for_all() -> Weight;19631964 /// The price of repairing an item.1965 fn force_repair_item() -> Weight;1966}19671968/// Weight info extension trait for refungible pallet.1969pub trait RefungibleExtensionsWeightInfo {1970 /// Weight of token repartition.1971 fn repartition() -> Weight;1972}19731974/// Common collection operations.1975///1976/// It wraps methods in Fungible, Nonfungible and Refungible pallets1977/// and adds weight info.1978pub trait CommonCollectionOperations<T: Config> {1979 /// Create token.1980 ///1981 /// * `sender` - The user who mint the token and pays for the transaction.1982 /// * `to` - The user who will own the token.1983 /// * `data` - Token data.1984 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1985 fn create_item(1986 &self,1987 sender: T::CrossAccountId,1988 to: T::CrossAccountId,1989 data: CreateItemData,1990 nesting_budget: &dyn Budget,1991 ) -> DispatchResultWithPostInfo;19921993 /// Create multiple tokens.1994 ///1995 /// * `sender` - The user who mint the token and pays for the transaction.1996 /// * `to` - The user who will own the token.1997 /// * `data` - Token data.1998 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1999 fn create_multiple_items(2000 &self,2001 sender: T::CrossAccountId,2002 to: T::CrossAccountId,2003 data: Vec<CreateItemData>,2004 nesting_budget: &dyn Budget,2005 ) -> DispatchResultWithPostInfo;20062007 /// Create multiple tokens.2008 ///2009 /// * `sender` - The user who mint the token and pays for the transaction.2010 /// * `to` - The user who will own the token.2011 /// * `data` - Token data.2012 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2013 fn create_multiple_items_ex(2014 &self,2015 sender: T::CrossAccountId,2016 data: CreateItemExData<T::CrossAccountId>,2017 nesting_budget: &dyn Budget,2018 ) -> DispatchResultWithPostInfo;20192020 /// Burn token.2021 ///2022 /// * `sender` - The user who owns the token.2023 /// * `token` - Token id that will burned.2024 /// * `amount` - The number of parts of the token that will be burned.2025 fn burn_item(2026 &self,2027 sender: T::CrossAccountId,2028 token: TokenId,2029 amount: u128,2030 ) -> DispatchResultWithPostInfo;20312032 /// Set collection properties.2033 ///2034 /// * `sender` - Must be either the owner of the collection or its admin.2035 /// * `properties` - Properties to be set.2036 fn set_collection_properties(2037 &self,2038 sender: T::CrossAccountId,2039 properties: Vec<Property>,2040 ) -> DispatchResultWithPostInfo;20412042 /// Delete collection properties.2043 ///2044 /// * `sender` - Must be either the owner of the collection or its admin.2045 /// * `properties` - The properties to be removed.2046 fn delete_collection_properties(2047 &self,2048 sender: &T::CrossAccountId,2049 property_keys: Vec<PropertyKey>,2050 ) -> DispatchResultWithPostInfo;20512052 /// Set token properties.2053 ///2054 /// The appropriate [`PropertyPermission`] for the token property2055 /// must be set with [`Self::set_token_property_permissions`].2056 ///2057 /// * `sender` - Must be either the owner of the token or its admin.2058 /// * `token_id` - The token for which the properties are being set.2059 /// * `properties` - Properties to be set.2060 /// * `budget` - Budget for setting properties.2061 fn set_token_properties(2062 &self,2063 sender: T::CrossAccountId,2064 token_id: TokenId,2065 properties: Vec<Property>,2066 budget: &dyn Budget,2067 ) -> DispatchResultWithPostInfo;20682069 /// Remove token properties.2070 ///2071 /// The appropriate [`PropertyPermission`] for the token property2072 /// must be set with [`Self::set_token_property_permissions`].2073 ///2074 /// * `sender` - Must be either the owner of the token or its admin.2075 /// * `token_id` - The token for which the properties are being remove.2076 /// * `property_keys` - Keys to remove corresponding properties.2077 /// * `budget` - Budget for removing properties.2078 fn delete_token_properties(2079 &self,2080 sender: T::CrossAccountId,2081 token_id: TokenId,2082 property_keys: Vec<PropertyKey>,2083 budget: &dyn Budget,2084 ) -> DispatchResultWithPostInfo;20852086 /// Get token properties raw map.2087 ///2088 /// * `token_id` - The token which properties are needed.2089 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20902091 /// Set token properties raw map.2092 ///2093 /// * `token_id` - The token for which the properties are being set.2094 /// * `map` - The raw map containing the token's properties.2095 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20962097 /// Set token property permissions.2098 ///2099 /// * `sender` - Must be either the owner of the token or its admin.2100 /// * `token_id` - The token for which the properties are being set.2101 /// * `property_permissions` - Property permissions to be set.2102 /// * `budget` - Budget for setting properties.2103 fn set_token_property_permissions(2104 &self,2105 sender: &T::CrossAccountId,2106 property_permissions: Vec<PropertyKeyPermission>,2107 ) -> DispatchResultWithPostInfo;21082109 /// Transfer amount of token pieces.2110 ///2111 /// * `sender` - Donor user.2112 /// * `to` - Recepient user.2113 /// * `token` - The token of which parts are being sent.2114 /// * `amount` - The number of parts of the token that will be transferred.2115 /// * `budget` - The maximum budget that can be spent on the transfer.2116 fn transfer(2117 &self,2118 sender: T::CrossAccountId,2119 to: T::CrossAccountId,2120 token: TokenId,2121 amount: u128,2122 budget: &dyn Budget,2123 ) -> DispatchResultWithPostInfo;21242125 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2126 ///2127 /// * `sender` - The user who grants access to the token.2128 /// * `spender` - The user to whom the rights are granted.2129 /// * `token` - The token to which access is granted.2130 /// * `amount` - The amount of pieces that another user can dispose of.2131 fn approve(2132 &self,2133 sender: T::CrossAccountId,2134 spender: T::CrossAccountId,2135 token: TokenId,2136 amount: u128,2137 ) -> DispatchResultWithPostInfo;21382139 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2140 ///2141 /// * `sender` - The user who grants access to the token.2142 /// * `from` - Spender's eth mirror.2143 /// * `to` - The user to whom the rights are granted.2144 /// * `token` - The token to which access is granted.2145 /// * `amount` - The amount of pieces that another user can dispose of.2146 fn approve_from(2147 &self,2148 sender: T::CrossAccountId,2149 from: T::CrossAccountId,2150 to: T::CrossAccountId,2151 token: TokenId,2152 amount: u128,2153 ) -> DispatchResultWithPostInfo;21542155 /// Send parts of a token owned by another user.2156 ///2157 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2158 ///2159 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2160 /// * `from` - The user who owns the token.2161 /// * `to` - Recepient user.2162 /// * `token` - The token of which parts are being sent.2163 /// * `amount` - The number of parts of the token that will be transferred.2164 /// * `budget` - The maximum budget that can be spent on the transfer.2165 fn transfer_from(2166 &self,2167 sender: T::CrossAccountId,2168 from: T::CrossAccountId,2169 to: T::CrossAccountId,2170 token: TokenId,2171 amount: u128,2172 budget: &dyn Budget,2173 ) -> DispatchResultWithPostInfo;21742175 /// Burn parts of a token owned by another user.2176 ///2177 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2178 ///2179 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2180 /// * `from` - The user who owns the token.2181 /// * `token` - The token of which parts are being sent.2182 /// * `amount` - The number of parts of the token that will be transferred.2183 /// * `budget` - The maximum budget that can be spent on the burn.2184 fn burn_from(2185 &self,2186 sender: T::CrossAccountId,2187 from: T::CrossAccountId,2188 token: TokenId,2189 amount: u128,2190 budget: &dyn Budget,2191 ) -> DispatchResultWithPostInfo;21922193 /// Check permission to nest token.2194 ///2195 /// * `sender` - The user who initiated the check.2196 /// * `from` - The token that is checked for embedding.2197 /// * `under` - Token under which to check.2198 /// * `budget` - The maximum budget that can be spent on the check.2199 fn check_nesting(2200 &self,2201 sender: &T::CrossAccountId,2202 from: (CollectionId, TokenId),2203 under: TokenId,2204 budget: &dyn Budget,2205 ) -> DispatchResult;22062207 /// Nest one token into another.2208 ///2209 /// * `under` - Token holder.2210 /// * `to_nest` - Nested token.2211 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22122213 /// Unnest token.2214 ///2215 /// * `under` - Token holder.2216 /// * `to_nest` - Token to unnest.2217 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22182219 /// Get all user tokens.2220 ///2221 /// * `account` - Account for which you need to get tokens.2222 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22232224 /// Get all the tokens in the collection.2225 fn collection_tokens(&self) -> Vec<TokenId>;22262227 /// Check if the token exists.2228 ///2229 /// * `token` - Id token to check.2230 fn token_exists(&self, token: TokenId) -> bool;22312232 /// Get the id of the last minted token.2233 fn last_token_id(&self) -> TokenId;22342235 /// Get the owner of the token.2236 ///2237 /// * `token` - The token for which you need to find out the owner.2238 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22392240 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2241 ///2242 /// * `token` - Id token to check.2243 /// * `maybe_owner` - The account to check.2244 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2245 fn check_token_indirect_owner(2246 &self,2247 token: TokenId,2248 maybe_owner: &T::CrossAccountId,2249 nesting_budget: &dyn Budget,2250 ) -> Result<bool, DispatchError>;22512252 /// Returns 10 tokens owners in no particular order.2253 ///2254 /// * `token` - The token for which you need to find out the owners.2255 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22562257 /// Get the value of the token property by key.2258 ///2259 /// * `token` - Token with the property to get.2260 /// * `key` - Property name.2261 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22622263 /// Get a set of token properties by key vector.2264 ///2265 /// * `token` - Token with the property to get.2266 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2267 /// then all properties are returned.2268 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22692270 /// Amount of unique collection tokens2271 fn total_supply(&self) -> u32;22722273 /// Amount of different tokens account has.2274 ///2275 /// * `account` - The account for which need to get the balance.2276 fn account_balance(&self, account: T::CrossAccountId) -> u32;22772278 /// Amount of specific token account have.2279 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22802281 /// Amount of token pieces2282 fn total_pieces(&self, token: TokenId) -> Option<u128>;22832284 /// Get the number of parts of the token that a trusted user can manage.2285 ///2286 /// * `sender` - Trusted user.2287 /// * `spender` - Owner of the token.2288 /// * `token` - The token for which to get the value.2289 fn allowance(2290 &self,2291 sender: T::CrossAccountId,2292 spender: T::CrossAccountId,2293 token: TokenId,2294 ) -> u128;22952296 /// Get extension for RFT collection.2297 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2298 None2299 }23002301 /// Get XCM extensions.2302 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2303 None2304 }23052306 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2307 /// * `owner` - Token owner2308 /// * `operator` - Operator2309 /// * `approve` - Should operator status be granted or revoked?2310 fn set_allowance_for_all(2311 &self,2312 owner: T::CrossAccountId,2313 operator: T::CrossAccountId,2314 approve: bool,2315 ) -> DispatchResultWithPostInfo;23162317 /// Tells whether the given `owner` approves the `operator`.2318 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23192320 /// Repairs a possibly broken item.2321 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2322}23232324/// Extension for RFT collection.2325pub trait RefungibleExtensions<T>2326where2327 T: Config,2328{2329 /// Change the number of parts of the token.2330 ///2331 /// When the value changes down, this function is equivalent to burning parts of the token.2332 ///2333 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2334 /// * `token` - The token for which you want to change the number of parts.2335 /// * `amount` - The new value of the parts of the token.2336 fn repartition(2337 &self,2338 sender: &T::CrossAccountId,2339 token: TokenId,2340 amount: u128,2341 ) -> DispatchResultWithPostInfo;2342}23432344/// XCM extensions for fungible and NFT collections2345pub trait XcmExtensions<T>2346where2347 T: Config,2348{2349 /// Does the token have children?2350 fn token_has_children(&self, _token: TokenId) -> bool {2351 false2352 }23532354 /// Create a collection's item using a transaction.2355 ///2356 /// This function performs additional XCM-related checks before the actual creation.2357 #[transactional]2358 fn create_item(2359 &self,2360 depositor: &T::CrossAccountId,2361 to: T::CrossAccountId,2362 data: CreateItemData,2363 nesting_budget: &dyn Budget,2364 ) -> Result<TokenId, DispatchError> {2365 if T::CrossTokenAddressMapping::is_token_address(&to) {2366 return unsupported!(T);2367 }23682369 self.create_item_internal(depositor, to, data, nesting_budget)2370 }23712372 /// Create a collection's item.2373 fn create_item_internal(2374 &self,2375 depositor: &T::CrossAccountId,2376 to: T::CrossAccountId,2377 data: CreateItemData,2378 nesting_budget: &dyn Budget,2379 ) -> Result<TokenId, DispatchError>;23802381 /// Transfer an item from the `from` account to the `to` account using a transaction.2382 ///2383 /// This function performs additional XCM-related checks before the actual transfer.2384 #[transactional]2385 fn transfer_item(2386 &self,2387 depositor: &T::CrossAccountId,2388 from: &T::CrossAccountId,2389 to: &T::CrossAccountId,2390 token: TokenId,2391 amount: u128,2392 nesting_budget: &dyn Budget,2393 ) -> DispatchResult {2394 if T::CrossTokenAddressMapping::is_token_address(to) {2395 return unsupported!(T);2396 }23972398 if self.token_has_children(token) {2399 return unsupported!(T);2400 }24012402 self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2403 }24042405 /// Transfer an item from the `from` account to the `to` account.2406 fn transfer_item_internal(2407 &self,2408 depositor: &T::CrossAccountId,2409 from: &T::CrossAccountId,2410 to: &T::CrossAccountId,2411 token: TokenId,2412 amount: u128,2413 nesting_budget: &dyn Budget,2414 ) -> DispatchResult;24152416 /// Burn a collection's item using a transaction.2417 #[transactional]2418 fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2419 self.burn_item_internal(from, token, amount)2420 }24212422 /// Burn a collection's item.2423 fn burn_item_internal(2424 &self,2425 from: T::CrossAccountId,2426 token: TokenId,2427 amount: u128,2428 ) -> DispatchResult;2429}24302431/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2432///2433/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2434pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2435 let post_info = PostDispatchInfo {2436 actual_weight: Some(weight),2437 pays_fee: Pays::Yes,2438 };2439 match res {2440 Ok(()) => Ok(post_info),2441 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2442 }2443}24442445impl<T: Config> From<PropertiesError> for Error<T> {2446 fn from(error: PropertiesError) -> Self {2447 match error {2448 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2449 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2450 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2451 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2452 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2453 }2454 }2455}24562457/// The type-safe interface for writing properties (setting or deleting) to tokens.2458/// It has two distinct implementations for newly created tokens and existing ones.2459///2460/// This type utilizes the lazy evaluation to avoid repeating the computation2461/// of several performance-heavy or PoV-heavy tasks,2462/// such as checking the indirect ownership or reading the token property permissions.2463pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2464 collection: &'a Handle,2465 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2466 _phantom: PhantomData<(T, WriterVariant)>,2467}24682469impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2470where2471 T: Config,2472 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2473{2474 fn internal_write_token_properties(2475 &mut self,2476 token_id: TokenId,2477 mut token_lazy_info: PropertyWriterLazyTokenInfo,2478 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2479 log: evm_coder::ethereum::Log,2480 ) -> DispatchResult {2481 for (key, value) in properties_updates {2482 let permission = self2483 .collection_lazy_info2484 .property_permissions2485 .value()2486 .get(&key)2487 .cloned()2488 .unwrap_or_else(PropertyPermission::none);24892490 match permission {2491 PropertyPermission { mutable: false, .. }2492 if token_lazy_info2493 .stored_properties2494 .value()2495 .get(&key)2496 .is_some() =>2497 {2498 return Err(<Error<T>>::NoPermission.into());2499 }25002501 PropertyPermission {2502 collection_admin,2503 token_owner,2504 ..2505 } => check_token_permissions::<T>(2506 collection_admin,2507 token_owner,2508 &mut self.collection_lazy_info.is_collection_admin,2509 &mut token_lazy_info.is_token_owner,2510 &mut token_lazy_info.is_token_exist,2511 )?,2512 }25132514 match value {2515 Some(value) => {2516 token_lazy_info2517 .stored_properties2518 .value_mut()2519 .try_set(key.clone(), value)2520 .map_err(<Error<T>>::from)?;25212522 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2523 self.collection.id,2524 token_id,2525 key,2526 ));2527 }2528 None => {2529 token_lazy_info2530 .stored_properties2531 .value_mut()2532 .remove(&key)2533 .map_err(<Error<T>>::from)?;25342535 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2536 self.collection.id,2537 token_id,2538 key,2539 ));2540 }2541 }2542 }25432544 let properties_changed = token_lazy_info.stored_properties.has_value();2545 if properties_changed {2546 <PalletEvm<T>>::deposit_log(log);25472548 self.collection2549 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2550 }25512552 Ok(())2553 }2554}25552556/// A helper structure for the [`PropertyWriter`] that holds2557/// the collection-related info. The info is loaded using lazy evaluation.2558/// This info is common for any token for which we write properties.2559pub struct PropertyWriterLazyCollectionInfo<'a> {2560 is_collection_admin: LazyValue<'a, bool>,2561 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2562}25632564/// A helper structure for the [`PropertyWriter`] that holds2565/// the token-related info. The info is loaded using lazy evaluation.2566pub struct PropertyWriterLazyTokenInfo<'a> {2567 is_token_exist: LazyValue<'a, bool>,2568 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2569 stored_properties: LazyValue<'a, TokenProperties>,2570}25712572impl<'a> PropertyWriterLazyTokenInfo<'a> {2573 /// Create a lazy token info.2574 pub fn new(2575 check_token_exist: impl FnOnce() -> bool + 'a,2576 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2577 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2578 ) -> Self {2579 Self {2580 is_token_exist: LazyValue::new(check_token_exist),2581 is_token_owner: LazyValue::new(check_token_owner),2582 stored_properties: LazyValue::new(get_token_properties),2583 }2584 }2585}25862587/// A marker structure that enables the writer implementation2588/// to provide the interface to write properties to **newly created** tokens.2589pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2590impl<T: Config> NewTokenPropertyWriter<T> {2591 /// Creates a [`PropertyWriter`] for **newly created** tokens.2592 pub fn new<'a, Handle>(2593 collection: &'a Handle,2594 sender: &'a T::CrossAccountId,2595 ) -> PropertyWriter<'a, Self, T, Handle>2596 where2597 T: Config,2598 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2599 {2600 PropertyWriter {2601 collection,2602 collection_lazy_info: PropertyWriterLazyCollectionInfo {2603 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2604 property_permissions: LazyValue::new(|| {2605 <Pallet<T>>::property_permissions(collection.id)2606 }),2607 },2608 _phantom: PhantomData,2609 }2610 }2611}26122613impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2614where2615 T: Config,2616 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2617{2618 /// A function to write properties to a **newly created** token.2619 pub fn write_token_properties(2620 &mut self,2621 mint_target_is_sender: bool,2622 token_id: TokenId,2623 properties_updates: impl Iterator<Item = Property>,2624 log: evm_coder::ethereum::Log,2625 ) -> DispatchResult {2626 let check_token_exist = || {2627 debug_assert!(self.collection.token_exists(token_id));2628 true2629 };26302631 let check_token_owner = || Ok(mint_target_is_sender);26322633 let get_token_properties = || {2634 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2635 TokenProperties::new()2636 };26372638 self.internal_write_token_properties(2639 token_id,2640 PropertyWriterLazyTokenInfo::new(2641 check_token_exist,2642 check_token_owner,2643 get_token_properties,2644 ),2645 properties_updates.map(|p| (p.key, Some(p.value))),2646 log,2647 )2648 }2649}26502651/// A marker structure that enables the writer implementation2652/// to provide the interface to write properties to **already existing** tokens.2653pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2654impl<T: Config> ExistingTokenPropertyWriter<T> {2655 /// Creates a [`PropertyWriter`] for **already existing** tokens.2656 pub fn new<'a, Handle>(2657 collection: &'a Handle,2658 sender: &'a T::CrossAccountId,2659 ) -> PropertyWriter<'a, Self, T, Handle>2660 where2661 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2662 {2663 PropertyWriter {2664 collection,2665 collection_lazy_info: PropertyWriterLazyCollectionInfo {2666 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2667 property_permissions: LazyValue::new(|| {2668 <Pallet<T>>::property_permissions(collection.id)2669 }),2670 },2671 _phantom: PhantomData,2672 }2673 }2674}26752676impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2677where2678 T: Config,2679 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2680{2681 /// A function to write properties to an **already existing** token.2682 pub fn write_token_properties(2683 &mut self,2684 sender: &T::CrossAccountId,2685 token_id: TokenId,2686 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2687 nesting_budget: &dyn Budget,2688 log: evm_coder::ethereum::Log,2689 ) -> DispatchResult {2690 let check_token_exist = || self.collection.token_exists(token_id);2691 let check_token_owner = || {2692 self.collection2693 .check_token_indirect_owner(token_id, sender, nesting_budget)2694 };2695 let get_token_properties = || {2696 self.collection2697 .get_token_properties_raw(token_id)2698 .unwrap_or_default()2699 };27002701 self.internal_write_token_properties(2702 token_id,2703 PropertyWriterLazyTokenInfo::new(2704 check_token_exist,2705 check_token_owner,2706 get_token_properties,2707 ),2708 properties_updates,2709 log,2710 )2711 }2712}27132714/// A marker structure that enables the writer implementation2715/// to benchmark the token properties writing.2716#[cfg(feature = "runtime-benchmarks")]2717pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27182719#[cfg(feature = "runtime-benchmarks")]2720impl<T: Config> BenchmarkPropertyWriter<T> {2721 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2722 pub fn new<'a, Handle>(2723 collection: &'a Handle,2724 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2725 ) -> PropertyWriter<'a, Self, T, Handle>2726 where2727 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2728 {2729 PropertyWriter {2730 collection,2731 collection_lazy_info,2732 _phantom: PhantomData,2733 }2734 }27352736 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2737 pub fn load_collection_info<Handle>(2738 collection_handle: &Handle,2739 sender: &T::CrossAccountId,2740 ) -> PropertyWriterLazyCollectionInfo<'static>2741 where2742 Handle: Deref<Target = CollectionHandle<T>>,2743 {2744 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2745 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27462747 PropertyWriterLazyCollectionInfo {2748 is_collection_admin: LazyValue::new(move || is_collection_admin),2749 property_permissions: LazyValue::new(move || property_permissions),2750 }2751 }27522753 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2754 pub fn load_token_properties<Handle>(2755 collection: &Handle,2756 token_id: TokenId,2757 ) -> PropertyWriterLazyTokenInfo2758 where2759 Handle: CommonCollectionOperations<T>,2760 {2761 let stored_properties = collection2762 .get_token_properties_raw(token_id)2763 .unwrap_or_default();27642765 PropertyWriterLazyTokenInfo {2766 is_token_exist: LazyValue::new(|| true),2767 is_token_owner: LazyValue::new(|| Ok(true)),2768 stored_properties: LazyValue::new(move || stored_properties),2769 }2770 }2771}27722773#[cfg(feature = "runtime-benchmarks")]2774impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2775where2776 T: Config,2777 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2778{2779 /// A function to benchmark the writing of token properties.2780 pub fn write_token_properties(2781 &mut self,2782 token_id: TokenId,2783 properties_updates: impl Iterator<Item = Property>,2784 log: evm_coder::ethereum::Log,2785 ) -> DispatchResult {2786 let check_token_exist = || true;2787 let check_token_owner = || Ok(true);2788 let get_token_properties = TokenProperties::new;27892790 self.internal_write_token_properties(2791 token_id,2792 PropertyWriterLazyTokenInfo::new(2793 check_token_exist,2794 check_token_owner,2795 get_token_properties,2796 ),2797 properties_updates.map(|p| (p.key, Some(p.value))),2798 log,2799 )2800 }2801}28022803/// Computes the weight of writing properties to tokens.2804/// * `properties_nums` - The properties num of each created token.2805/// * `per_token_weight_weight` - The function to obtain the weight2806/// of writing properties from a token's properties num.2807pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2808 properties_nums: impl Iterator<Item = u32>,2809 per_token_weight: I,2810) -> Weight {2811 let mut weight = properties_nums2812 .filter_map(|properties_num| {2813 if properties_num > 0 {2814 Some(per_token_weight(properties_num))2815 } else {2816 None2817 }2818 })2819 .fold(Weight::zero(), |a, b| a.saturating_add(b));28202821 if !weight.is_zero() {2822 // If we are here, it means the token properties were written at least once.2823 // Because of that, some common collection data was also loaded; we must add this weight.2824 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28252826 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2827 }28282829 weight2830}28312832#[cfg(any(feature = "tests", test))]2833#[allow(missing_docs)]2834pub mod tests {2835 use crate::{Config, DispatchError, DispatchResult, LazyValue};28362837 const fn to_bool(u: u8) -> bool {2838 u != 02839 }28402841 #[derive(Debug)]2842 pub struct TestCase {2843 pub collection_admin: bool,2844 pub is_collection_admin: bool,2845 pub token_owner: bool,2846 pub is_token_owner: bool,2847 pub no_permission: bool,2848 }28492850 impl TestCase {2851 const fn new(2852 collection_admin: u8,2853 is_collection_admin: u8,2854 token_owner: u8,2855 is_token_owner: u8,2856 no_permission: u8,2857 ) -> Self {2858 Self {2859 collection_admin: to_bool(collection_admin),2860 is_collection_admin: to_bool(is_collection_admin),2861 token_owner: to_bool(token_owner),2862 is_token_owner: to_bool(is_token_owner),2863 no_permission: to_bool(no_permission),2864 }2865 }2866 }28672868 #[rustfmt::skip]2869 pub const TABLE: [TestCase; 16] = [2870 // ┌╴collection_admin2871 // │ ┌╴is_collection_admin2872 // │ │ ┌╴token_owner2873 // │ │ │ ┌╴is_token_ownership2874 // │ │ │ │ ┌╴no_permission2875 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2876 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2877 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2878 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2879 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2880 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2881 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2882 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2883 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2884 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2885 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2886 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2887 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2888 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2889 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2890 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2891 ];28922893 pub fn check_token_permissions<T: Config>(2894 collection_admin_permitted: bool,2895 token_owner_permitted: bool,2896 is_collection_admin: &mut LazyValue<bool>,2897 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2898 check_token_existence: &mut LazyValue<bool>,2899 ) -> DispatchResult {2900 crate::check_token_permissions::<T>(2901 collection_admin_permitted,2902 token_owner_permitted,2903 is_collection_admin,2904 check_token_ownership,2905 check_token_existence,2906 )2907 }2908}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 alloc::boxed::Box;57use core::{58 marker::PhantomData,59 ops::{Deref, DerefMut},60 slice::from_ref,61 unreachable,62};6364use evm_coder::ToLog;65use frame_support::{66 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Pays, PostDispatchInfo},67 ensure, fail,68 traits::{69 fungible::{Balanced, Debt, Inspect},70 tokens::{Imbalance, Precision, Preservation},71 Get,72 },73 transactional,74};75pub use pallet::*;76use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};77use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};78use sp_core::H160;79use sp_runtime::{traits::Zero, ArithmeticError, DispatchError, DispatchResult};80use sp_std::vec::Vec;81use sp_weights::Weight;82use up_data_structs::{83 budget::Budget, mapping::TokenAddressMapping, AccessMode, Collection, CollectionId,84 CollectionLimits, CollectionMode, CollectionPermissions,85 CollectionProperties as CollectionPropertiesT, CollectionStats, CreateCollectionData,86 CreateItemData, CreateItemExData, PhantomType, PropertiesError, PropertiesPermissionMap,87 Property, PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,88 RpcCollection, RpcCollectionFlags, SponsoringRateLimit, SponsorshipState, TokenChild,89 TokenData, TokenId, TokenOwnerError, TokenProperties, TrySetProperty, COLLECTION_ADMINS_LIMIT,90 COLLECTION_NUMBER_LIMIT, CUSTOM_DATA_LIMIT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91 MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_TOKEN_PREFIX_LENGTH,92 NFT_SPONSOR_TRANSFER_TIMEOUT, REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,93};94use up_pov_estimate_rpc::PovInfo;9596#[cfg(feature = "runtime-benchmarks")]97pub mod benchmarking;98pub mod dispatch;99pub mod erc;100pub mod eth;101pub mod helpers;102#[allow(missing_docs)]103pub mod weights;104105use weights::WeightInfo;106107/// Weight info.108pub type SelfWeightOf<T> = <T as Config>::WeightInfo;109110/// Collection handle contains information about collection data and id.111/// Also provides functionality to count consumed gas.112///113/// CollectionHandle is used as a generic wrapper for collections of all types (except native fungible).114/// It allows to perform common operations and queries on any collection type,115/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].116#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]117pub struct CollectionHandle<T: Config> {118 /// Collection id119 pub id: CollectionId,120 collection: Collection<T::AccountId>,121 /// Substrate recorder for counting consumed gas122 pub recorder: SubstrateRecorder<T>,123}124125impl<T: Config> WithRecorder<T> for CollectionHandle<T> {126 fn recorder(&self) -> &SubstrateRecorder<T> {127 &self.recorder128 }129 fn into_recorder(self) -> SubstrateRecorder<T> {130 self.recorder131 }132}133134impl<T: Config> CollectionHandle<T> {135 /// Same as [CollectionHandle::new] but with an explicit gas limit.136 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {137 Self::new_with_recorder(id, SubstrateRecorder::new(gas_limit))138 }139140 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].141 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {142 <CollectionById<T>>::get(id).map(|collection| Self {143 id,144 collection,145 recorder,146 })147 }148149 /// Retrives collection data from storage and creates collection handle with default parameters.150 /// If collection not found return `None`151 pub fn new(id: CollectionId) -> Option<Self> {152 Self::new_with_gas_limit(id, u64::MAX)153 }154155 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.156 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {157 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)158 }159160 /// Consume gas for reading.161 pub fn consume_store_reads(162 &self,163 reads: u64,164 ) -> pallet_evm_coder_substrate::execution::Result<()> {165 self.recorder().consume_store_reads(reads)166 }167168 /// Consume gas for writing.169 pub fn consume_store_writes(170 &self,171 writes: u64,172 ) -> pallet_evm_coder_substrate::execution::Result<()> {173 self.recorder().consume_store_writes(writes)174 }175176 /// Consume gas for reading and writing.177 pub fn consume_store_reads_and_writes(178 &self,179 reads: u64,180 writes: u64,181 ) -> pallet_evm_coder_substrate::execution::Result<()> {182 self.recorder()183 .consume_store_reads_and_writes(reads, writes)184 }185186 /// Save collection to storage.187 pub fn save(&self) -> DispatchResult {188 <CollectionById<T>>::insert(self.id, &self.collection);189 Ok(())190 }191192 /// Set collection sponsor.193 ///194 /// Unique collections allows sponsoring for certain actions.195 /// This method allows you to set the sponsor of the collection.196 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].197 pub fn set_sponsor(198 &mut self,199 sender: &T::CrossAccountId,200 sponsor: T::AccountId,201 ) -> DispatchResult {202 self.check_is_internal()?;203 self.check_is_owner_or_admin(sender)?;204205 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());206207 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));208 <PalletEvm<T>>::deposit_log(209 erc::CollectionHelpersEvents::CollectionChanged {210 collection_id: eth::collection_id_to_address(self.id),211 }212 .to_log(T::ContractAddress::get()),213 );214215 self.save()216 }217218 /// Force set `sponsor`.219 ///220 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation221 /// from the `sponsor` is not required.222 ///223 /// # Arguments224 ///225 /// * `sponsor`: ID of the account of the sponsor-to-be.226 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {227 self.check_is_internal()?;228229 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());230231 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));232 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));233 <PalletEvm<T>>::deposit_log(234 erc::CollectionHelpersEvents::CollectionChanged {235 collection_id: eth::collection_id_to_address(self.id),236 }237 .to_log(T::ContractAddress::get()),238 );239240 self.save()241 }242243 /// Confirm sponsorship244 ///245 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.246 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].247 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {248 self.check_is_internal()?;249 ensure!(250 self.collection.sponsorship.pending_sponsor() == Some(sender),251 Error::<T>::ConfirmSponsorshipFail252 );253254 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());255256 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));257 <PalletEvm<T>>::deposit_log(258 erc::CollectionHelpersEvents::CollectionChanged {259 collection_id: eth::collection_id_to_address(self.id),260 }261 .to_log(T::ContractAddress::get()),262 );263264 self.save()265 }266267 /// Remove collection sponsor.268 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {269 self.check_is_internal()?;270 self.check_is_owner_or_admin(sender)?;271272 self.collection.sponsorship = SponsorshipState::Disabled;273274 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));275 <PalletEvm<T>>::deposit_log(276 erc::CollectionHelpersEvents::CollectionChanged {277 collection_id: eth::collection_id_to_address(self.id),278 }279 .to_log(T::ContractAddress::get()),280 );281 self.save()282 }283284 /// Force remove `sponsor`.285 ///286 /// Differs from `remove_sponsor` in that287 /// it doesn't require consent from the `owner` of the collection.288 pub fn force_remove_sponsor(&mut self) -> DispatchResult {289 self.check_is_internal()?;290291 self.collection.sponsorship = SponsorshipState::Disabled;292293 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));294 <PalletEvm<T>>::deposit_log(295 erc::CollectionHelpersEvents::CollectionChanged {296 collection_id: eth::collection_id_to_address(self.id),297 }298 .to_log(T::ContractAddress::get()),299 );300 self.save()301 }302303 /// Checks that the collection was created with, and must be operated upon through **Unique API**.304 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.305 pub fn check_is_internal(&self) -> DispatchResult {306 if self.flags.external {307 return Err(<Error<T>>::CollectionIsExternal)?;308 }309310 Ok(())311 }312313 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.314 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.315 pub fn check_is_external(&self) -> DispatchResult {316 if !self.flags.external {317 return Err(<Error<T>>::CollectionIsInternal)?;318 }319320 Ok(())321 }322}323324impl<T: Config> Deref for CollectionHandle<T> {325 type Target = Collection<T::AccountId>;326327 fn deref(&self) -> &Self::Target {328 &self.collection329 }330}331332impl<T: Config> DerefMut for CollectionHandle<T> {333 fn deref_mut(&mut self) -> &mut Self::Target {334 &mut self.collection335 }336}337338impl<T: Config> CollectionHandle<T> {339 /// Checks if the `user` is the owner of the collection.340 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {341 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);342 Ok(())343 }344345 /// Returns **true** if the `user` is the owner or administrator of the collection.346 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {347 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))348 }349350 /// Checks if the `user` is the owner or administrator of the collection.351 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {352 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);353 Ok(())354 }355356 /// Returns **true** if357 /// * the `user`is a collection owner or admin358 /// * the collection limits allow the owner/admins to transfer/burn any collection token359 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {360 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)361 }362363 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.364 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {365 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)366 }367368 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.369 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {370 ensure!(371 <Allowlist<T>>::get((self.id, user)),372 <Error<T>>::AddressNotInAllowlist373 );374 Ok(())375 }376377 /// Changes collection owner to another account378 /// #### Store read/writes379 /// 1 writes380 pub fn change_owner(381 &mut self,382 caller: T::CrossAccountId,383 new_owner: T::CrossAccountId,384 ) -> DispatchResult {385 self.check_is_internal()?;386 self.check_is_owner(&caller)?;387 self.collection.owner = new_owner.as_sub().clone();388389 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(390 self.id,391 new_owner.as_sub().clone(),392 ));393 <PalletEvm<T>>::deposit_log(394 erc::CollectionHelpersEvents::CollectionChanged {395 collection_id: eth::collection_id_to_address(self.id),396 }397 .to_log(T::ContractAddress::get()),398 );399400 self.save()401 }402}403404#[frame_support::pallet]405pub mod pallet {406407 use dispatch::CollectionDispatch;408 use frame_support::{409 pallet_prelude::*, storage::Key, traits::StorageVersion, Blake2_128Concat,410 };411 use scale_info::TypeInfo;412 use up_data_structs::{mapping::TokenAddressMapping, TokenId};413 use weights::WeightInfo;414415 use super::*;416417 #[pallet::config]418 pub trait Config:419 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo420 {421 /// Weight information for functions of this pallet.422 type WeightInfo: WeightInfo;423424 /// Events compatible with [`frame_system::Config::Event`].425 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;426427 /// Handler of accounts and payment.428 type Currency: Balanced<Self::AccountId> + Inspect<Self::AccountId>;429430 /// Set price to create a collection.431 #[pallet::constant]432 type CollectionCreationPrice: Get<433 <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,434 >;435436 /// Dispatcher of operations on collections.437 type CollectionDispatch: CollectionDispatch<Self>;438439 /// Account which holds the chain's treasury.440 type TreasuryAccountId: Get<Self::AccountId>;441442 /// Address under which the CollectionHelper contract would be available.443 #[pallet::constant]444 type ContractAddress: Get<H160>;445446 /// Mapper for token addresses to Ethereum addresses.447 type EvmTokenAddressMapping: TokenAddressMapping<H160>;448449 /// Mapper for token addresses to [`CrossAccountId`].450 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;451 }452453 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);454 /// Collection id for native fungible collction.455 pub const NATIVE_FUNGIBLE_COLLECTION_ID: CollectionId = CollectionId(0);456457 #[pallet::pallet]458 #[pallet::storage_version(STORAGE_VERSION)]459 pub struct Pallet<T>(_);460461 #[pallet::extra_constants]462 impl<T: Config> Pallet<T> {463 /// Maximum admins per collection.464 pub fn collection_admins_limit() -> u32 {465 COLLECTION_ADMINS_LIMIT466 }467 }468469 #[pallet::genesis_config]470 pub struct GenesisConfig<T>(PhantomData<T>);471472 impl<T: Config> Default for GenesisConfig<T> {473 fn default() -> Self {474 Self(Default::default())475 }476 }477478 #[pallet::genesis_build]479 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {480 fn build(&self) {481 StorageVersion::new(1).put::<Pallet<T>>();482 }483 }484485 impl<T: Config> Pallet<T> {486 /// Helper function that handles deposit events487 pub fn deposit_event(event: Event<T>) {488 let event = <T as Config>::RuntimeEvent::from(event);489 let event = event.into();490 <frame_system::Pallet<T>>::deposit_event(event)491 }492 }493494 #[pallet::event]495 pub enum Event<T: Config> {496 /// New collection was created497 CollectionCreated(498 /// Globally unique identifier of newly created collection.499 CollectionId,500 /// [`CollectionMode`] converted into _u8_.501 u8,502 /// Collection owner.503 T::AccountId,504 ),505506 /// New collection was destroyed507 CollectionDestroyed(508 /// Globally unique identifier of collection.509 CollectionId,510 ),511512 /// New item was created.513 ItemCreated(514 /// Id of the collection where item was created.515 CollectionId,516 /// Id of an item. Unique within the collection.517 TokenId,518 /// Owner of newly created item519 T::CrossAccountId,520 /// Always 1 for NFT521 u128,522 ),523524 /// Collection item was burned.525 ItemDestroyed(526 /// Id of the collection where item was destroyed.527 CollectionId,528 /// Identifier of burned NFT.529 TokenId,530 /// Which user has destroyed its tokens.531 T::CrossAccountId,532 /// Amount of token pieces destroed. Always 1 for NFT.533 u128,534 ),535536 /// Item was transferred537 Transfer(538 /// Id of collection to which item is belong.539 CollectionId,540 /// Id of an item.541 TokenId,542 /// Original owner of item.543 T::CrossAccountId,544 /// New owner of item.545 T::CrossAccountId,546 /// Amount of token pieces transfered. Always 1 for NFT.547 u128,548 ),549550 /// Amount pieces of token owned by `sender` was approved for `spender`.551 Approved(552 /// Id of collection to which item is belong.553 CollectionId,554 /// Id of an item.555 TokenId,556 /// Original owner of item.557 T::CrossAccountId,558 /// Id for which the approval was granted.559 T::CrossAccountId,560 /// Amount of token pieces transfered. Always 1 for NFT.561 u128,562 ),563564 /// A `sender` approves operations on all owned tokens for `spender`.565 ApprovedForAll(566 /// Id of collection to which item is belong.567 CollectionId,568 /// Owner of a wallet.569 T::CrossAccountId,570 /// Id for which operator status was granted or rewoked.571 T::CrossAccountId,572 /// Is operator status granted or revoked?573 bool,574 ),575576 /// The colletion property has been added or edited.577 CollectionPropertySet(578 /// Id of collection to which property has been set.579 CollectionId,580 /// The property that was set.581 PropertyKey,582 ),583584 /// The property has been deleted.585 CollectionPropertyDeleted(586 /// Id of collection to which property has been deleted.587 CollectionId,588 /// The property that was deleted.589 PropertyKey,590 ),591592 /// The token property has been added or edited.593 TokenPropertySet(594 /// Identifier of the collection whose token has the property set.595 CollectionId,596 /// The token for which the property was set.597 TokenId,598 /// The property that was set.599 PropertyKey,600 ),601602 /// The token property has been deleted.603 TokenPropertyDeleted(604 /// Identifier of the collection whose token has the property deleted.605 CollectionId,606 /// The token for which the property was deleted.607 TokenId,608 /// The property that was deleted.609 PropertyKey,610 ),611612 /// The token property permission of a collection has been set.613 PropertyPermissionSet(614 /// ID of collection to which property permission has been set.615 CollectionId,616 /// The property permission that was set.617 PropertyKey,618 ),619620 /// Address was added to the allow list.621 AllowListAddressAdded(622 /// ID of the affected collection.623 CollectionId,624 /// Address of the added account.625 T::CrossAccountId,626 ),627628 /// Address was removed from the allow list.629 AllowListAddressRemoved(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the removed account.633 T::CrossAccountId,634 ),635636 /// Collection admin was added.637 CollectionAdminAdded(638 /// ID of the affected collection.639 CollectionId,640 /// Admin address.641 T::CrossAccountId,642 ),643644 /// Collection admin was removed.645 CollectionAdminRemoved(646 /// ID of the affected collection.647 CollectionId,648 /// Removed admin address.649 T::CrossAccountId,650 ),651652 /// Collection limits were set.653 CollectionLimitSet(654 /// ID of the affected collection.655 CollectionId,656 ),657658 /// Collection owned was changed.659 CollectionOwnerChanged(660 /// ID of the affected collection.661 CollectionId,662 /// New owner address.663 T::AccountId,664 ),665666 /// Collection permissions were set.667 CollectionPermissionSet(668 /// ID of the affected collection.669 CollectionId,670 ),671672 /// Collection sponsor was set.673 CollectionSponsorSet(674 /// ID of the affected collection.675 CollectionId,676 /// New sponsor address.677 T::AccountId,678 ),679680 /// New sponsor was confirm.681 SponsorshipConfirmed(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// Collection sponsor was removed.689 CollectionSponsorRemoved(690 /// ID of the affected collection.691 CollectionId,692 ),693 }694695 #[pallet::error]696 pub enum Error<T> {697 /// This collection does not exist.698 CollectionNotFound,699 /// Sender parameter and item owner must be equal.700 MustBeTokenOwner,701 /// No permission to perform action702 NoPermission,703 /// Destroying only empty collections is allowed704 CantDestroyNotEmptyCollection,705 /// Collection is not in mint mode.706 PublicMintingNotAllowed,707 /// Address is not in allow list.708 AddressNotInAllowlist,709710 /// Collection name can not be longer than 63 char.711 CollectionNameLimitExceeded,712 /// Collection description can not be longer than 255 char.713 CollectionDescriptionLimitExceeded,714 /// Token prefix can not be longer than 15 char.715 CollectionTokenPrefixLimitExceeded,716 /// Total collections bound exceeded.717 TotalCollectionsLimitExceeded,718 /// Exceeded max admin count719 CollectionAdminCountExceeded,720 /// Collection limit bounds per collection exceeded721 CollectionLimitBoundsExceeded,722 /// Tried to enable permissions which are only permitted to be disabled723 OwnerPermissionsCantBeReverted,724 /// Collection settings not allowing items transferring725 TransferNotAllowed,726 /// Account token limit exceeded per collection727 AccountTokenLimitExceeded,728 /// Collection token limit exceeded729 CollectionTokenLimitExceeded,730 /// Metadata flag frozen731 MetadataFlagFrozen,732733 /// Item does not exist734 TokenNotFound,735 /// Item is balance not enough736 TokenValueTooLow,737 /// Requested value is more than the approved738 ApprovedValueTooLow,739 /// Tried to approve more than owned740 CantApproveMoreThanOwned,741 /// Only spending from eth mirror could be approved742 AddressIsNotEthMirror,743744 /// Can't transfer tokens to ethereum zero address745 AddressIsZero,746747 /// The operation is not supported748 UnsupportedOperation,749750 /// Insufficient funds to perform an action751 NotSufficientFounds,752753 /// User does not satisfy the nesting rule754 UserIsNotAllowedToNest,755 /// Only tokens from specific collections may nest tokens under this one756 SourceCollectionIsNotAllowedToNest,757758 /// Tried to store more data than allowed in collection field759 CollectionFieldSizeExceeded,760761 /// Tried to store more property data than allowed762 NoSpaceForProperty,763764 /// Tried to store more property keys than allowed765 PropertyLimitReached,766767 /// Property key is too long768 PropertyKeyIsTooLong,769770 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed771 InvalidCharacterInPropertyKey,772773 /// Empty property keys are forbidden774 EmptyPropertyKey,775776 /// Tried to access an external collection with an internal API777 CollectionIsExternal,778779 /// Tried to access an internal collection with an external API780 CollectionIsInternal,781782 /// This address is not set as sponsor, use setCollectionSponsor first.783 ConfirmSponsorshipFail,784785 /// The user is not an administrator.786 UserIsNotCollectionAdmin,787788 /// Fungible tokens hold no ID, and the default value of TokenId for a fungible collection is 0.789 FungibleItemsHaveNoId,790791 /// Not Fungible item data used to mint in Fungible collection.792 NotFungibleDataUsedToMintFungibleCollectionToken,793 }794795 /// Storage of the count of created collections. Essentially contains the last collection ID.796 #[pallet::storage]797 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799 /// Storage of the count of deleted collections.800 #[pallet::storage]801 pub type DestroyedCollectionCount<T> =802 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804 /// Storage of collection info.805 #[pallet::storage]806 pub type CollectionById<T> = StorageMap<807 Hasher = Blake2_128Concat,808 Key = CollectionId,809 Value = Collection<<T as frame_system::Config>::AccountId>,810 QueryKind = OptionQuery,811 >;812813 /// Storage of collection properties.814 #[pallet::storage]815 #[pallet::getter(fn collection_properties)]816 pub type CollectionProperties<T> = StorageMap<817 Hasher = Blake2_128Concat,818 Key = CollectionId,819 Value = CollectionPropertiesT,820 QueryKind = ValueQuery,821 >;822823 /// Storage of token property permissions of a collection.824 #[pallet::storage]825 #[pallet::getter(fn property_permissions)]826 pub type CollectionPropertyPermissions<T> = StorageMap<827 Hasher = Blake2_128Concat,828 Key = CollectionId,829 Value = PropertiesPermissionMap,830 QueryKind = ValueQuery,831 >;832833 /// Storage of the amount of collection admins.834 #[pallet::storage]835 pub type AdminAmount<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = u32,839 QueryKind = ValueQuery,840 >;841842 /// List of collection admins.843 #[pallet::storage]844 pub type IsAdmin<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 /// Allowlisted collection users.854 #[pallet::storage]855 pub type Allowlist<T: Config> = StorageNMap<856 Key = (857 Key<Blake2_128Concat, CollectionId>,858 Key<Blake2_128Concat, T::CrossAccountId>,859 ),860 Value = bool,861 QueryKind = ValueQuery,862 >;863864 /// Not used by code, exists only to provide some types to metadata.865 #[pallet::storage]866 pub type DummyStorageValue<T: Config> = StorageValue<867 Value = (868 CollectionStats,869 CollectionId,870 TokenId,871 TokenChild,872 PhantomType<(873 TokenData<T::CrossAccountId>,874 RpcCollection<T::AccountId>,875 // PoV Estimate Info876 PovInfo,877 )>,878 ),879 QueryKind = OptionQuery,880 >;881}882883enum LazyValueState<'a, T> {884 Pending(Box<dyn FnOnce() -> T + 'a>),885 InProgress,886 Computed(T),887}888889/// Value representation with delayed initialization time.890pub struct LazyValue<'a, T> {891 state: LazyValueState<'a, T>,892}893894impl<'a, T> LazyValue<'a, T> {895 /// Create a new LazyValue.896 pub fn new(f: impl FnOnce() -> T + 'a) -> Self {897 Self {898 state: LazyValueState::Pending(Box::new(f)),899 }900 }901902 /// Get the value. If it is called the first time, the value will be initialized.903 pub fn value(&mut self) -> &T {904 self.force_value();905 self.value_mut()906 }907908 /// Get the value. If it is called the first time, the value will be initialized.909 pub fn value_mut(&mut self) -> &mut T {910 self.force_value();911912 if let LazyValueState::Computed(value) = &mut self.state {913 value914 } else {915 unreachable!()916 }917 }918919 fn into_inner(mut self) -> T {920 self.force_value();921 if let LazyValueState::Computed(value) = self.state {922 value923 } else {924 unreachable!()925 }926 }927928 /// Is value initialized?929 pub fn has_value(&self) -> bool {930 matches!(self.state, LazyValueState::Computed(_))931 }932933 fn force_value(&mut self) {934 use LazyValueState::*;935936 if self.has_value() {937 return;938 }939940 match sp_std::mem::replace(&mut self.state, InProgress) {941 Pending(f) => self.state = Computed(f()),942 _ => panic!("recursion isn't supported"),943 }944 }945}946947/// An issuer of a collection.948pub enum CollectionIssuer<CrossAccountId> {949 /// A user who creates the collection.950 User(CrossAccountId),951952 /// The internal mechanisms are creating the collection.953 Internals,954}955956fn check_token_permissions<T: Config>(957 collection_admin_permitted: bool,958 token_owner_permitted: bool,959 is_collection_admin: &mut LazyValue<bool>,960 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,961 is_token_exist: &mut LazyValue<bool>,962) -> DispatchResult {963 if !(collection_admin_permitted && *is_collection_admin.value()964 || token_owner_permitted && (*is_token_owner.value())?)965 {966 fail!(<Error<T>>::NoPermission);967 }968969 let token_exist_due_to_owner_check_success =970 is_token_owner.has_value() && (*is_token_owner.value())?;971972 // If the token owner check has occurred and succeeded,973 // we know the token exists (otherwise, the owner check must fail).974 if !token_exist_due_to_owner_check_success {975 // If the token owner check didn't occur,976 // we must check the token's existence ourselves.977 if !is_token_exist.value() {978 fail!(<Error<T>>::TokenNotFound);979 }980 }981982 Ok(())983}984985impl<T: Config> Pallet<T> {986 /// Enshure that receiver address is correct.987 ///988 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.989 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {990 ensure!(991 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,992 <Error<T>>::AddressIsZero993 );994 Ok(())995 }996997 /// Get a vector of collection admins.998 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {999 <IsAdmin<T>>::iter_prefix((collection,))1000 .map(|(a, _)| a)1001 .collect()1002 }10031004 /// Get a vector of users allowed to mint tokens.1005 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {1006 <Allowlist<T>>::iter_prefix((collection,))1007 .map(|(a, _)| a)1008 .collect()1009 }10101011 /// Is `user` allowed to mint token in `collection`.1012 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1013 <Allowlist<T>>::get((collection, user))1014 }10151016 /// Get statistics of collections.1017 pub fn collection_stats() -> CollectionStats {1018 let created = <CreatedCollectionCount<T>>::get();1019 let destroyed = <DestroyedCollectionCount<T>>::get();1020 CollectionStats {1021 created: created.0,1022 destroyed: destroyed.0,1023 alive: created.0 - destroyed.0,1024 }1025 }10261027 /// Get the effective limits for the collection.1028 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1029 let collection = <CollectionById<T>>::get(collection)?;1030 let limits = collection.limits;1031 let effective_limits = CollectionLimits {1032 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1033 sponsored_data_size: Some(limits.sponsored_data_size()),1034 sponsored_data_rate_limit: Some(1035 limits1036 .sponsored_data_rate_limit1037 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1038 ),1039 token_limit: Some(limits.token_limit()),1040 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1041 match collection.mode {1042 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1043 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1044 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1045 },1046 )),1047 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1048 owner_can_transfer: Some(limits.owner_can_transfer()),1049 owner_can_destroy: Some(limits.owner_can_destroy()),1050 transfers_enabled: Some(limits.transfers_enabled()),1051 };10521053 Some(effective_limits)1054 }10551056 /// Returns information about the `collection` adapted for rpc.1057 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1058 let Collection {1059 name,1060 description,1061 owner,1062 mode,1063 token_prefix,1064 sponsorship,1065 limits,1066 permissions,1067 flags,1068 } = <CollectionById<T>>::get(collection)?;10691070 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1071 .into_iter()1072 .map(|(key, permission)| PropertyKeyPermission { key, permission })1073 .collect();10741075 let properties = <CollectionProperties<T>>::get(collection)1076 .into_iter()1077 .map(|(key, value)| Property { key, value })1078 .collect();10791080 let permissions = CollectionPermissions {1081 access: Some(permissions.access()),1082 mint_mode: Some(permissions.mint_mode()),1083 nesting: Some(permissions.nesting().clone()),1084 };10851086 Some(RpcCollection {1087 name: name.into_inner(),1088 description: description.into_inner(),1089 owner,1090 mode,1091 token_prefix: token_prefix.into_inner(),1092 sponsorship,1093 limits,1094 permissions,1095 token_property_permissions,1096 properties,1097 read_only: flags.external,10981099 flags: RpcCollectionFlags {1100 foreign: flags.foreign,1101 erc721metadata: flags.erc721metadata,1102 },1103 })1104 }1105}11061107macro_rules! limit_default {1108 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1109 $(1110 if let Some($new) = $new.$field {1111 let $old = $old.$field($($arg)?);1112 let _ = $new;1113 let _ = $old;1114 $check1115 } else {1116 $new.$field = $old.$field1117 }1118 )*1119 }};1120}1121macro_rules! limit_default_clone {1122 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1123 $(1124 if let Some($new) = $new.$field.clone() {1125 let $old = $old.$field($($arg)?);1126 let _ = $new;1127 let _ = $old;1128 $check1129 } else {1130 $new.$field = $old.$field.clone()1131 }1132 )*1133 }};1134}11351136impl<T: Config> Pallet<T> {1137 /// Create new collection.1138 ///1139 /// * `owner` - The owner of the collection.1140 /// * `issuer` - An entity that creates the collection.1141 /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1142 pub fn init_collection(1143 owner: T::CrossAccountId,1144 issuer: CollectionIssuer<T::CrossAccountId>,1145 data: CreateCollectionData<T::CrossAccountId>,1146 ) -> Result<CollectionId, DispatchError> {1147 match issuer {1148 CollectionIssuer::User(payer) => {1149 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);11501151 // Take a (non-refundable) deposit of collection creation1152 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1153 imbalance.subsume(<T as Config>::Currency::deposit(1154 &T::TreasuryAccountId::get(),1155 T::CollectionCreationPrice::get(),1156 Precision::Exact,1157 )?);1158 let credit = <T as Config>::Currency::settle(1159 payer.as_sub(),1160 imbalance,1161 Preservation::Preserve,1162 )1163 .map_err(|_| Error::<T>::NotSufficientFounds)?;11641165 debug_assert!(credit.peek().is_zero());1166 }1167 CollectionIssuer::Internals => {}1168 }11691170 {1171 ensure!(1172 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1173 Error::<T>::CollectionTokenPrefixLimitExceeded1174 );1175 }11761177 let created_count = <CreatedCollectionCount<T>>::get()1178 .01179 .checked_add(1)1180 .ok_or(ArithmeticError::Overflow)?;1181 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1182 let id = CollectionId(created_count);11831184 // bound Total number of collections1185 ensure!(1186 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1187 <Error<T>>::TotalCollectionsLimitExceeded1188 );11891190 // =========11911192 let collection = Collection {1193 owner: owner.as_sub().clone(),1194 name: data.name,1195 mode: data.mode.clone(),1196 description: data.description,1197 token_prefix: data.token_prefix,1198 sponsorship: data1199 .pending_sponsor1200 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1201 .unwrap_or_default(),1202 limits: data1203 .limits1204 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1205 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1206 permissions: data1207 .permissions1208 .map(|permissions| {1209 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1210 })1211 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1212 flags: data.flags,1213 };12141215 let mut collection_properties = CollectionPropertiesT::new();1216 collection_properties1217 .try_set_from_iter(data.properties.into_iter())1218 .map_err(<Error<T>>::from)?;12191220 CollectionProperties::<T>::insert(id, collection_properties);12211222 let mut token_props_permissions = PropertiesPermissionMap::new();1223 token_props_permissions1224 .try_set_from_iter(data.token_property_permissions.into_iter())1225 .map_err(<Error<T>>::from)?;12261227 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12281229 let mut admin_amount = 0u32;1230 for admin in data.admin_list.iter() {1231 if !<IsAdmin<T>>::get((id, admin)) {1232 <IsAdmin<T>>::insert((id, admin), true);1233 admin_amount = admin_amount1234 .checked_add(1)1235 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1236 }1237 }1238 ensure!(1239 admin_amount <= Self::collection_admins_limit(),1240 <Error<T>>::CollectionAdminCountExceeded,1241 );1242 <AdminAmount<T>>::insert(id, admin_amount);12431244 <CreatedCollectionCount<T>>::put(created_count);1245 <Pallet<T>>::deposit_event(Event::CollectionCreated(1246 id,1247 data.mode.id(),1248 owner.as_sub().clone(),1249 ));1250 <PalletEvm<T>>::deposit_log(1251 erc::CollectionHelpersEvents::CollectionCreated {1252 owner: *owner.as_eth(),1253 collection_id: eth::collection_id_to_address(id),1254 }1255 .to_log(T::ContractAddress::get()),1256 );1257 <CollectionById<T>>::insert(id, collection);1258 Ok(id)1259 }12601261 /// Destroy collection.1262 ///1263 /// * `collection` - Collection handler.1264 /// * `sender` - The owner or administrator of the collection.1265 pub fn destroy_collection(1266 collection: CollectionHandle<T>,1267 sender: &T::CrossAccountId,1268 ) -> DispatchResult {1269 ensure!(1270 collection.limits.owner_can_destroy(),1271 <Error<T>>::NoPermission,1272 );1273 collection.check_is_owner(sender)?;12741275 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1276 .01277 .checked_add(1)1278 .ok_or(ArithmeticError::Overflow)?;12791280 // =========12811282 <DestroyedCollectionCount<T>>::put(destroyed_collections);1283 <CollectionById<T>>::remove(collection.id);1284 <AdminAmount<T>>::remove(collection.id);1285 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1286 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1287 <CollectionProperties<T>>::remove(collection.id);12881289 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12901291 <PalletEvm<T>>::deposit_log(1292 erc::CollectionHelpersEvents::CollectionDestroyed {1293 collection_id: eth::collection_id_to_address(collection.id),1294 }1295 .to_log(T::ContractAddress::get()),1296 );1297 Ok(())1298 }12991300 /// This function sets or removes a collection properties according to1301 /// `properties_updates` contents:1302 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1303 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1304 ///1305 /// This function fires an event for each property change.1306 /// In case of an error, all the changes (including the events) will be reverted1307 /// since the function is transactional.1308 #[transactional]1309 fn modify_collection_properties(1310 collection: &CollectionHandle<T>,1311 sender: &T::CrossAccountId,1312 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1313 ) -> DispatchResult {1314 collection.check_is_owner_or_admin(sender)?;13151316 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13171318 for (key, value) in properties_updates {1319 match value {1320 Some(value) => {1321 stored_properties1322 .try_set(key.clone(), value)1323 .map_err(<Error<T>>::from)?;13241325 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1326 <PalletEvm<T>>::deposit_log(1327 erc::CollectionHelpersEvents::CollectionChanged {1328 collection_id: eth::collection_id_to_address(collection.id),1329 }1330 .to_log(T::ContractAddress::get()),1331 );1332 }1333 None => {1334 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13351336 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1337 <PalletEvm<T>>::deposit_log(1338 erc::CollectionHelpersEvents::CollectionChanged {1339 collection_id: eth::collection_id_to_address(collection.id),1340 }1341 .to_log(T::ContractAddress::get()),1342 );1343 }1344 }1345 }13461347 <CollectionProperties<T>>::set(collection.id, stored_properties);13481349 Ok(())1350 }13511352 /// Sets or unsets the approval of a given operator.1353 ///1354 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1355 /// - `owner`: Token owner1356 /// - `operator`: Operator1357 /// - `approve`: Should operator status be granted or revoked?1358 pub fn set_allowance_for_all(1359 collection: &CollectionHandle<T>,1360 owner: &T::CrossAccountId,1361 operator: &T::CrossAccountId,1362 approve: bool,1363 set_allowance: impl FnOnce(),1364 log: evm_coder::ethereum::Log,1365 ) -> DispatchResult {1366 if collection.permissions.access() == AccessMode::AllowList {1367 collection.check_allowlist(owner)?;1368 collection.check_allowlist(operator)?;1369 }13701371 Self::ensure_correct_receiver(operator)?;13721373 set_allowance();13741375 <PalletEvm<T>>::deposit_log(log);1376 Self::deposit_event(Event::ApprovedForAll(1377 collection.id,1378 owner.clone(),1379 operator.clone(),1380 approve,1381 ));1382 Ok(())1383 }13841385 /// Set collection property.1386 ///1387 /// * `collection` - Collection handler.1388 /// * `sender` - The owner or administrator of the collection.1389 /// * `property` - The property to set.1390 pub fn set_collection_property(1391 collection: &CollectionHandle<T>,1392 sender: &T::CrossAccountId,1393 property: Property,1394 ) -> DispatchResult {1395 Self::set_collection_properties(collection, sender, [property].into_iter())1396 }13971398 /// Set a scoped collection property, where the scope is a special prefix1399 /// prohibiting a user access to change the property directly.1400 ///1401 /// * `collection_id` - ID of the collection for which the property is being set.1402 /// * `scope` - Property scope.1403 /// * `property` - The property to set.1404 pub fn set_scoped_collection_property(1405 collection_id: CollectionId,1406 scope: PropertyScope,1407 property: Property,1408 ) -> DispatchResult {1409 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1410 properties.try_scoped_set(scope, property.key, property.value)1411 })1412 .map_err(<Error<T>>::from)?;14131414 Ok(())1415 }14161417 /// Set scoped collection properties, where the scope is a special prefix1418 /// prohibiting a user access to change the properties directly.1419 ///1420 /// * `collection_id` - ID of the collection for which the properties is being set.1421 /// * `scope` - Property scope.1422 /// * `properties` - The properties to set.1423 pub fn set_scoped_collection_properties(1424 collection_id: CollectionId,1425 scope: PropertyScope,1426 properties: impl Iterator<Item = Property>,1427 ) -> DispatchResult {1428 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1429 stored_properties.try_scoped_set_from_iter(scope, properties)1430 })1431 .map_err(<Error<T>>::from)?;14321433 Ok(())1434 }14351436 /// Set collection properties.1437 ///1438 /// * `collection` - Collection handler.1439 /// * `sender` - The owner or administrator of the collection.1440 /// * `properties` - The properties to set.1441 pub fn set_collection_properties(1442 collection: &CollectionHandle<T>,1443 sender: &T::CrossAccountId,1444 properties: impl Iterator<Item = Property>,1445 ) -> DispatchResult {1446 Self::modify_collection_properties(1447 collection,1448 sender,1449 properties.map(|property| (property.key, Some(property.value))),1450 )1451 }14521453 /// Delete collection property.1454 ///1455 /// * `collection` - Collection handler.1456 /// * `sender` - The owner or administrator of the collection.1457 /// * `property` - The property to delete.1458 pub fn delete_collection_property(1459 collection: &CollectionHandle<T>,1460 sender: &T::CrossAccountId,1461 property_key: PropertyKey,1462 ) -> DispatchResult {1463 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1464 }14651466 /// Delete collection properties.1467 ///1468 /// * `collection` - Collection handler.1469 /// * `sender` - The owner or administrator of the collection.1470 /// * `properties` - The properties to delete.1471 pub fn delete_collection_properties(1472 collection: &CollectionHandle<T>,1473 sender: &T::CrossAccountId,1474 property_keys: impl Iterator<Item = PropertyKey>,1475 ) -> DispatchResult {1476 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1477 }14781479 /// Set collection propetry permission without any checks.1480 ///1481 /// Used for migrations.1482 ///1483 /// * `collection` - Collection handler.1484 /// * `property_permissions` - Property permissions.1485 pub fn set_property_permission_unchecked(1486 collection: CollectionId,1487 property_permission: PropertyKeyPermission,1488 ) -> DispatchResult {1489 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1490 permissions.try_set(property_permission.key, property_permission.permission)1491 })1492 .map_err(<Error<T>>::from)?;1493 Ok(())1494 }14951496 /// Set collection property permission.1497 ///1498 /// * `collection` - Collection handler.1499 /// * `sender` - The owner or administrator of the collection.1500 /// * `property_permission` - Property permission.1501 pub fn set_property_permission(1502 collection: &CollectionHandle<T>,1503 sender: &T::CrossAccountId,1504 property_permission: PropertyKeyPermission,1505 ) -> DispatchResult {1506 Self::set_scoped_property_permission(1507 collection,1508 sender,1509 PropertyScope::None,1510 property_permission,1511 )1512 }15131514 /// Set collection property permission with scope.1515 ///1516 /// * `collection` - Collection handler.1517 /// * `sender` - The owner or administrator of the collection.1518 /// * `scope` - Property scope.1519 /// * `property_permission` - Property permission.1520 pub fn set_scoped_property_permission(1521 collection: &CollectionHandle<T>,1522 sender: &T::CrossAccountId,1523 scope: PropertyScope,1524 property_permission: PropertyKeyPermission,1525 ) -> DispatchResult {1526 collection.check_is_owner_or_admin(sender)?;15271528 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1529 let current_permission = all_permissions.get(&property_permission.key);1530 if matches![1531 current_permission,1532 Some(PropertyPermission { mutable: false, .. })1533 ] {1534 return Err(<Error<T>>::NoPermission.into());1535 }15361537 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1538 let property_permission = property_permission.clone();1539 permissions.try_scoped_set(1540 scope,1541 property_permission.key,1542 property_permission.permission,1543 )1544 })1545 .map_err(<Error<T>>::from)?;15461547 Self::deposit_event(Event::PropertyPermissionSet(1548 collection.id,1549 property_permission.key,1550 ));1551 <PalletEvm<T>>::deposit_log(1552 erc::CollectionHelpersEvents::CollectionChanged {1553 collection_id: eth::collection_id_to_address(collection.id),1554 }1555 .to_log(T::ContractAddress::get()),1556 );15571558 Ok(())1559 }15601561 /// Set token property permission.1562 ///1563 /// * `collection` - Collection handler.1564 /// * `sender` - The owner or administrator of the collection.1565 /// * `property_permissions` - Property permissions.1566 #[transactional]1567 pub fn set_token_property_permissions(1568 collection: &CollectionHandle<T>,1569 sender: &T::CrossAccountId,1570 property_permissions: Vec<PropertyKeyPermission>,1571 ) -> DispatchResult {1572 Self::set_scoped_token_property_permissions(1573 collection,1574 sender,1575 PropertyScope::None,1576 property_permissions,1577 )1578 }15791580 /// Set token property permission with scope.1581 ///1582 /// * `collection` - Collection handler.1583 /// * `sender` - The owner or administrator of the collection.1584 /// * `scope` - Property scope.1585 /// * `property_permissions` - Property permissions.1586 #[transactional]1587 pub fn set_scoped_token_property_permissions(1588 collection: &CollectionHandle<T>,1589 sender: &T::CrossAccountId,1590 scope: PropertyScope,1591 property_permissions: Vec<PropertyKeyPermission>,1592 ) -> DispatchResult {1593 for prop_pemission in property_permissions {1594 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1595 }15961597 Ok(())1598 }15991600 /// Get collection property.1601 pub fn get_collection_property(1602 collection_id: CollectionId,1603 key: &PropertyKey,1604 ) -> Option<PropertyValue> {1605 Self::collection_properties(collection_id).get(key).cloned()1606 }16071608 /// Convert byte vector to property key vector.1609 pub fn bytes_keys_to_property_keys(1610 keys: Vec<Vec<u8>>,1611 ) -> Result<Vec<PropertyKey>, DispatchError> {1612 keys.into_iter()1613 .map(|key| -> Result<PropertyKey, DispatchError> {1614 key.try_into()1615 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1616 })1617 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1618 }16191620 /// Get properties according to given keys.1621 pub fn filter_collection_properties(1622 collection_id: CollectionId,1623 keys: Option<Vec<PropertyKey>>,1624 ) -> Result<Vec<Property>, DispatchError> {1625 let properties = Self::collection_properties(collection_id);16261627 let properties = keys1628 .map(|keys| {1629 keys.into_iter()1630 .filter_map(|key| {1631 properties.get(&key).map(|value| Property {1632 key,1633 value: value.clone(),1634 })1635 })1636 .collect()1637 })1638 .unwrap_or_else(|| {1639 properties1640 .into_iter()1641 .map(|(key, value)| Property { key, value })1642 .collect()1643 });16441645 Ok(properties)1646 }16471648 /// Get property permissions according to given keys.1649 pub fn filter_property_permissions(1650 collection_id: CollectionId,1651 keys: Option<Vec<PropertyKey>>,1652 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1653 let permissions = Self::property_permissions(collection_id);16541655 let key_permissions = keys1656 .map(|keys| {1657 keys.into_iter()1658 .filter_map(|key| {1659 permissions1660 .get(&key)1661 .map(|permission| PropertyKeyPermission {1662 key,1663 permission: permission.clone(),1664 })1665 })1666 .collect()1667 })1668 .unwrap_or_else(|| {1669 permissions1670 .into_iter()1671 .map(|(key, permission)| PropertyKeyPermission { key, permission })1672 .collect()1673 });16741675 Ok(key_permissions)1676 }16771678 /// Toggle `user` participation in the `collection`'s allow list.1679 /// #### Store read/writes1680 /// 1 writes1681 pub fn toggle_allowlist(1682 collection: &CollectionHandle<T>,1683 sender: &T::CrossAccountId,1684 user: &T::CrossAccountId,1685 allowed: bool,1686 ) -> DispatchResult {1687 collection.check_is_owner_or_admin(sender)?;16881689 // =========16901691 if allowed {1692 <Allowlist<T>>::insert((collection.id, user), true);1693 Self::deposit_event(Event::<T>::AllowListAddressAdded(1694 collection.id,1695 user.clone(),1696 ));1697 } else {1698 <Allowlist<T>>::remove((collection.id, user));1699 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1700 collection.id,1701 user.clone(),1702 ));1703 }17041705 <PalletEvm<T>>::deposit_log(1706 erc::CollectionHelpersEvents::CollectionChanged {1707 collection_id: eth::collection_id_to_address(collection.id),1708 }1709 .to_log(T::ContractAddress::get()),1710 );17111712 Ok(())1713 }17141715 /// Toggle `user` participation in the `collection`'s admin list.1716 /// #### Store read/writes1717 /// 2 reads, 2 writes1718 pub fn toggle_admin(1719 collection: &CollectionHandle<T>,1720 sender: &T::CrossAccountId,1721 user: &T::CrossAccountId,1722 admin: bool,1723 ) -> DispatchResult {1724 collection.check_is_internal()?;1725 collection.check_is_owner(sender)?;17261727 let is_admin = <IsAdmin<T>>::get((collection.id, user));1728 if is_admin == admin {1729 if admin {1730 return Ok(());1731 } else {1732 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1733 }1734 }1735 let amount = <AdminAmount<T>>::get(collection.id);17361737 // =========17381739 if admin {1740 let amount = amount1741 .checked_add(1)1742 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1743 ensure!(1744 amount <= Self::collection_admins_limit(),1745 <Error<T>>::CollectionAdminCountExceeded,1746 );17471748 <AdminAmount<T>>::insert(collection.id, amount);1749 <IsAdmin<T>>::insert((collection.id, user), true);17501751 Self::deposit_event(Event::<T>::CollectionAdminAdded(1752 collection.id,1753 user.clone(),1754 ));1755 } else {1756 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1757 <IsAdmin<T>>::remove((collection.id, user));17581759 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1760 collection.id,1761 user.clone(),1762 ));1763 }17641765 <PalletEvm<T>>::deposit_log(1766 erc::CollectionHelpersEvents::CollectionChanged {1767 collection_id: eth::collection_id_to_address(collection.id),1768 }1769 .to_log(T::ContractAddress::get()),1770 );17711772 Ok(())1773 }17741775 /// Update collection limits.1776 pub fn update_limits(1777 user: &T::CrossAccountId,1778 collection: &mut CollectionHandle<T>,1779 new_limit: CollectionLimits,1780 ) -> DispatchResult {1781 collection.check_is_internal()?;1782 collection.check_is_owner_or_admin(user)?;17831784 collection.limits =1785 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17861787 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1788 <PalletEvm<T>>::deposit_log(1789 erc::CollectionHelpersEvents::CollectionChanged {1790 collection_id: eth::collection_id_to_address(collection.id),1791 }1792 .to_log(T::ContractAddress::get()),1793 );17941795 collection.save()1796 }17971798 /// Merge set fields from `new_limit` to `old_limit`.1799 fn clamp_limits(1800 mode: CollectionMode,1801 old_limit: &CollectionLimits,1802 mut new_limit: CollectionLimits,1803 ) -> Result<CollectionLimits, DispatchError> {1804 let limits = old_limit;1805 limit_default!(old_limit, new_limit,1806 account_token_ownership_limit => ensure!(1807 new_limit <= MAX_TOKEN_OWNERSHIP,1808 <Error<T>>::CollectionLimitBoundsExceeded,1809 ),1810 sponsored_data_size => ensure!(1811 new_limit <= CUSTOM_DATA_LIMIT,1812 <Error<T>>::CollectionLimitBoundsExceeded,1813 ),18141815 sponsored_data_rate_limit => {},1816 token_limit => ensure!(1817 old_limit >= new_limit && new_limit > 0,1818 <Error<T>>::CollectionTokenLimitExceeded1819 ),18201821 sponsor_transfer_timeout(match mode {1822 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1823 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1824 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1825 }) => ensure!(1826 new_limit <= MAX_SPONSOR_TIMEOUT,1827 <Error<T>>::CollectionLimitBoundsExceeded,1828 ),1829 sponsor_approve_timeout => {},1830 owner_can_transfer => ensure!(1831 !limits.owner_can_transfer_instaled() ||1832 old_limit || !new_limit,1833 <Error<T>>::OwnerPermissionsCantBeReverted,1834 ),1835 owner_can_destroy => ensure!(1836 old_limit || !new_limit,1837 <Error<T>>::OwnerPermissionsCantBeReverted,1838 ),1839 transfers_enabled => {},1840 );1841 Ok(new_limit)1842 }18431844 /// Update collection permissions.1845 pub fn update_permissions(1846 user: &T::CrossAccountId,1847 collection: &mut CollectionHandle<T>,1848 new_permission: CollectionPermissions,1849 ) -> DispatchResult {1850 collection.check_is_internal()?;1851 collection.check_is_owner_or_admin(user)?;1852 collection.permissions = Self::clamp_permissions(1853 collection.mode.clone(),1854 &collection.permissions,1855 new_permission,1856 )?;18571858 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1859 <PalletEvm<T>>::deposit_log(1860 erc::CollectionHelpersEvents::CollectionChanged {1861 collection_id: eth::collection_id_to_address(collection.id),1862 }1863 .to_log(T::ContractAddress::get()),1864 );18651866 collection.save()1867 }18681869 /// Merge set fields from `new_permission` to `old_permission`.1870 fn clamp_permissions(1871 _mode: CollectionMode,1872 old_permission: &CollectionPermissions,1873 mut new_permission: CollectionPermissions,1874 ) -> Result<CollectionPermissions, DispatchError> {1875 limit_default_clone!(old_permission, new_permission,1876 access => {},1877 mint_mode => {},1878 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1879 );1880 Ok(new_permission)1881 }18821883 /// Repair possibly broken properties of a collection.1884 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1885 CollectionProperties::<T>::mutate(collection_id, |properties| {1886 properties.recompute_consumed_space();1887 });18881889 Ok(())1890 }1891}18921893/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1894#[macro_export]1895macro_rules! unsupported {1896 ($runtime:path) => {1897 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1898 };1899}19001901/// Return weights for various worst-case operations.1902pub trait CommonWeightInfo<CrossAccountId> {1903 /// Weight of item creation.1904 fn create_item(data: &CreateItemData) -> Weight {1905 Self::create_multiple_items(from_ref(data))1906 }19071908 /// Weight of items creation.1909 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19101911 /// Weight of items creation.1912 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19131914 /// The weight of the burning item.1915 fn burn_item() -> Weight;19161917 /// Property setting weight.1918 ///1919 /// * `amount`- The number of properties to set.1920 fn set_collection_properties(amount: u32) -> Weight;19211922 /// Collection property deletion weight.1923 ///1924 /// * `amount`- The number of properties to set.1925 fn delete_collection_properties(amount: u32) -> Weight {1926 Self::set_collection_properties(amount)1927 }19281929 /// Token property setting weight.1930 ///1931 /// * `amount`- The number of properties to set.1932 fn set_token_properties(amount: u32) -> Weight;19331934 /// Token property deletion weight.1935 ///1936 /// * `amount`- The number of properties to delete.1937 fn delete_token_properties(amount: u32) -> Weight {1938 Self::set_token_properties(amount)1939 }19401941 /// Token property permissions set weight.1942 ///1943 /// * `amount`- The number of property permissions to set.1944 fn set_token_property_permissions(amount: u32) -> Weight;19451946 /// Transfer price of the token or its parts.1947 fn transfer() -> Weight;19481949 /// The price of setting the permission of the operation from another user.1950 fn approve() -> Weight;19511952 /// The price of setting the permission of the operation from another user for eth mirror.1953 fn approve_from() -> Weight;19541955 /// Transfer price from another user.1956 fn transfer_from() -> Weight;19571958 /// The price of burning a token from another user.1959 fn burn_from() -> Weight;19601961 /// The price of setting approval for all1962 fn set_allowance_for_all() -> Weight;19631964 /// The price of repairing an item.1965 fn force_repair_item() -> Weight;1966}19671968/// Weight info extension trait for refungible pallet.1969pub trait RefungibleExtensionsWeightInfo {1970 /// Weight of token repartition.1971 fn repartition() -> Weight;1972}19731974/// Common collection operations.1975///1976/// It wraps methods in Fungible, Nonfungible and Refungible pallets1977/// and adds weight info.1978pub trait CommonCollectionOperations<T: Config> {1979 /// Create token.1980 ///1981 /// * `sender` - The user who mint the token and pays for the transaction.1982 /// * `to` - The user who will own the token.1983 /// * `data` - Token data.1984 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1985 fn create_item(1986 &self,1987 sender: T::CrossAccountId,1988 to: T::CrossAccountId,1989 data: CreateItemData,1990 nesting_budget: &dyn Budget,1991 ) -> DispatchResultWithPostInfo;19921993 /// Create multiple tokens.1994 ///1995 /// * `sender` - The user who mint the token and pays for the transaction.1996 /// * `to` - The user who will own the token.1997 /// * `data` - Token data.1998 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1999 fn create_multiple_items(2000 &self,2001 sender: T::CrossAccountId,2002 to: T::CrossAccountId,2003 data: Vec<CreateItemData>,2004 nesting_budget: &dyn Budget,2005 ) -> DispatchResultWithPostInfo;20062007 /// Create multiple tokens.2008 ///2009 /// * `sender` - The user who mint the token and pays for the transaction.2010 /// * `to` - The user who will own the token.2011 /// * `data` - Token data.2012 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2013 fn create_multiple_items_ex(2014 &self,2015 sender: T::CrossAccountId,2016 data: CreateItemExData<T::CrossAccountId>,2017 nesting_budget: &dyn Budget,2018 ) -> DispatchResultWithPostInfo;20192020 /// Burn token.2021 ///2022 /// * `sender` - The user who owns the token.2023 /// * `token` - Token id that will burned.2024 /// * `amount` - The number of parts of the token that will be burned.2025 fn burn_item(2026 &self,2027 sender: T::CrossAccountId,2028 token: TokenId,2029 amount: u128,2030 ) -> DispatchResultWithPostInfo;20312032 /// Set collection properties.2033 ///2034 /// * `sender` - Must be either the owner of the collection or its admin.2035 /// * `properties` - Properties to be set.2036 fn set_collection_properties(2037 &self,2038 sender: T::CrossAccountId,2039 properties: Vec<Property>,2040 ) -> DispatchResultWithPostInfo;20412042 /// Delete collection properties.2043 ///2044 /// * `sender` - Must be either the owner of the collection or its admin.2045 /// * `properties` - The properties to be removed.2046 fn delete_collection_properties(2047 &self,2048 sender: &T::CrossAccountId,2049 property_keys: Vec<PropertyKey>,2050 ) -> DispatchResultWithPostInfo;20512052 /// Set token properties.2053 ///2054 /// The appropriate [`PropertyPermission`] for the token property2055 /// must be set with [`Self::set_token_property_permissions`].2056 ///2057 /// * `sender` - Must be either the owner of the token or its admin.2058 /// * `token_id` - The token for which the properties are being set.2059 /// * `properties` - Properties to be set.2060 /// * `budget` - Budget for setting properties.2061 fn set_token_properties(2062 &self,2063 sender: T::CrossAccountId,2064 token_id: TokenId,2065 properties: Vec<Property>,2066 budget: &dyn Budget,2067 ) -> DispatchResultWithPostInfo;20682069 /// Remove token properties.2070 ///2071 /// The appropriate [`PropertyPermission`] for the token property2072 /// must be set with [`Self::set_token_property_permissions`].2073 ///2074 /// * `sender` - Must be either the owner of the token or its admin.2075 /// * `token_id` - The token for which the properties are being remove.2076 /// * `property_keys` - Keys to remove corresponding properties.2077 /// * `budget` - Budget for removing properties.2078 fn delete_token_properties(2079 &self,2080 sender: T::CrossAccountId,2081 token_id: TokenId,2082 property_keys: Vec<PropertyKey>,2083 budget: &dyn Budget,2084 ) -> DispatchResultWithPostInfo;20852086 /// Get token properties raw map.2087 ///2088 /// * `token_id` - The token which properties are needed.2089 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20902091 /// Set token properties raw map.2092 ///2093 /// * `token_id` - The token for which the properties are being set.2094 /// * `map` - The raw map containing the token's properties.2095 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20962097 /// Set token property permissions.2098 ///2099 /// * `sender` - Must be either the owner of the token or its admin.2100 /// * `token_id` - The token for which the properties are being set.2101 /// * `property_permissions` - Property permissions to be set.2102 /// * `budget` - Budget for setting properties.2103 fn set_token_property_permissions(2104 &self,2105 sender: &T::CrossAccountId,2106 property_permissions: Vec<PropertyKeyPermission>,2107 ) -> DispatchResultWithPostInfo;21082109 /// Transfer amount of token pieces.2110 ///2111 /// * `sender` - Donor user.2112 /// * `to` - Recepient user.2113 /// * `token` - The token of which parts are being sent.2114 /// * `amount` - The number of parts of the token that will be transferred.2115 /// * `budget` - The maximum budget that can be spent on the transfer.2116 fn transfer(2117 &self,2118 sender: T::CrossAccountId,2119 to: T::CrossAccountId,2120 token: TokenId,2121 amount: u128,2122 budget: &dyn Budget,2123 ) -> DispatchResultWithPostInfo;21242125 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2126 ///2127 /// * `sender` - The user who grants access to the token.2128 /// * `spender` - The user to whom the rights are granted.2129 /// * `token` - The token to which access is granted.2130 /// * `amount` - The amount of pieces that another user can dispose of.2131 fn approve(2132 &self,2133 sender: T::CrossAccountId,2134 spender: T::CrossAccountId,2135 token: TokenId,2136 amount: u128,2137 ) -> DispatchResultWithPostInfo;21382139 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2140 ///2141 /// * `sender` - The user who grants access to the token.2142 /// * `from` - Spender's eth mirror.2143 /// * `to` - The user to whom the rights are granted.2144 /// * `token` - The token to which access is granted.2145 /// * `amount` - The amount of pieces that another user can dispose of.2146 fn approve_from(2147 &self,2148 sender: T::CrossAccountId,2149 from: T::CrossAccountId,2150 to: T::CrossAccountId,2151 token: TokenId,2152 amount: u128,2153 ) -> DispatchResultWithPostInfo;21542155 /// Send parts of a token owned by another user.2156 ///2157 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2158 ///2159 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2160 /// * `from` - The user who owns the token.2161 /// * `to` - Recepient user.2162 /// * `token` - The token of which parts are being sent.2163 /// * `amount` - The number of parts of the token that will be transferred.2164 /// * `budget` - The maximum budget that can be spent on the transfer.2165 fn transfer_from(2166 &self,2167 sender: T::CrossAccountId,2168 from: T::CrossAccountId,2169 to: T::CrossAccountId,2170 token: TokenId,2171 amount: u128,2172 budget: &dyn Budget,2173 ) -> DispatchResultWithPostInfo;21742175 /// Burn parts of a token owned by another user.2176 ///2177 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2178 ///2179 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2180 /// * `from` - The user who owns the token.2181 /// * `token` - The token of which parts are being sent.2182 /// * `amount` - The number of parts of the token that will be transferred.2183 /// * `budget` - The maximum budget that can be spent on the burn.2184 fn burn_from(2185 &self,2186 sender: T::CrossAccountId,2187 from: T::CrossAccountId,2188 token: TokenId,2189 amount: u128,2190 budget: &dyn Budget,2191 ) -> DispatchResultWithPostInfo;21922193 /// Check permission to nest token.2194 ///2195 /// * `sender` - The user who initiated the check.2196 /// * `from` - The token that is checked for embedding.2197 /// * `under` - Token under which to check.2198 /// * `budget` - The maximum budget that can be spent on the check.2199 fn check_nesting(2200 &self,2201 sender: &T::CrossAccountId,2202 from: (CollectionId, TokenId),2203 under: TokenId,2204 budget: &dyn Budget,2205 ) -> DispatchResult;22062207 /// Nest one token into another.2208 ///2209 /// * `under` - Token holder.2210 /// * `to_nest` - Nested token.2211 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22122213 /// Unnest token.2214 ///2215 /// * `under` - Token holder.2216 /// * `to_nest` - Token to unnest.2217 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22182219 /// Get all user tokens.2220 ///2221 /// * `account` - Account for which you need to get tokens.2222 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22232224 /// Get all the tokens in the collection.2225 fn collection_tokens(&self) -> Vec<TokenId>;22262227 /// Check if the token exists.2228 ///2229 /// * `token` - Id token to check.2230 fn token_exists(&self, token: TokenId) -> bool;22312232 /// Get the id of the last minted token.2233 fn last_token_id(&self) -> TokenId;22342235 /// Get the owner of the token.2236 ///2237 /// * `token` - The token for which you need to find out the owner.2238 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22392240 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2241 ///2242 /// * `token` - Id token to check.2243 /// * `maybe_owner` - The account to check.2244 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2245 fn check_token_indirect_owner(2246 &self,2247 token: TokenId,2248 maybe_owner: &T::CrossAccountId,2249 nesting_budget: &dyn Budget,2250 ) -> Result<bool, DispatchError>;22512252 /// Returns 10 tokens owners in no particular order.2253 ///2254 /// * `token` - The token for which you need to find out the owners.2255 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22562257 /// Get the value of the token property by key.2258 ///2259 /// * `token` - Token with the property to get.2260 /// * `key` - Property name.2261 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22622263 /// Get a set of token properties by key vector.2264 ///2265 /// * `token` - Token with the property to get.2266 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2267 /// then all properties are returned.2268 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22692270 /// Amount of unique collection tokens2271 fn total_supply(&self) -> u32;22722273 /// Amount of different tokens account has.2274 ///2275 /// * `account` - The account for which need to get the balance.2276 fn account_balance(&self, account: T::CrossAccountId) -> u32;22772278 /// Amount of specific token account have.2279 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22802281 /// Amount of token pieces2282 fn total_pieces(&self, token: TokenId) -> Option<u128>;22832284 /// Get the number of parts of the token that a trusted user can manage.2285 ///2286 /// * `sender` - Trusted user.2287 /// * `spender` - Owner of the token.2288 /// * `token` - The token for which to get the value.2289 fn allowance(2290 &self,2291 sender: T::CrossAccountId,2292 spender: T::CrossAccountId,2293 token: TokenId,2294 ) -> u128;22952296 /// Get extension for RFT collection.2297 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2298 None2299 }23002301 /// Get XCM extensions.2302 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2303 None2304 }23052306 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2307 /// * `owner` - Token owner2308 /// * `operator` - Operator2309 /// * `approve` - Should operator status be granted or revoked?2310 fn set_allowance_for_all(2311 &self,2312 owner: T::CrossAccountId,2313 operator: T::CrossAccountId,2314 approve: bool,2315 ) -> DispatchResultWithPostInfo;23162317 /// Tells whether the given `owner` approves the `operator`.2318 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23192320 /// Repairs a possibly broken item.2321 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2322}23232324/// Extension for RFT collection.2325pub trait RefungibleExtensions<T>2326where2327 T: Config,2328{2329 /// Change the number of parts of the token.2330 ///2331 /// When the value changes down, this function is equivalent to burning parts of the token.2332 ///2333 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2334 /// * `token` - The token for which you want to change the number of parts.2335 /// * `amount` - The new value of the parts of the token.2336 fn repartition(2337 &self,2338 sender: &T::CrossAccountId,2339 token: TokenId,2340 amount: u128,2341 ) -> DispatchResultWithPostInfo;2342}23432344/// XCM extensions for fungible and NFT collections2345pub trait XcmExtensions<T>2346where2347 T: Config,2348{2349 /// Does the token have children?2350 fn token_has_children(&self, _token: TokenId) -> bool {2351 false2352 }23532354 /// Create a collection's item using a transaction.2355 ///2356 /// This function performs additional XCM-related checks before the actual creation.2357 ///2358 /// The `transactional` attribute is needed because the inbound XCM messages2359 /// are processed in a non-transactional context.2360 /// To perform the needed logic, we use the internal pallets' functions2361 /// that are not inherently safe to use outside a transaction.2362 ///2363 /// This requirement is temporary until XCM message processing becomes transactional:2364 /// https://github.com/paritytech/polkadot-sdk/issues/4902365 #[transactional]2366 fn create_item(2367 &self,2368 depositor: &T::CrossAccountId,2369 to: T::CrossAccountId,2370 data: CreateItemData,2371 nesting_budget: &dyn Budget,2372 ) -> Result<TokenId, DispatchError> {2373 if T::CrossTokenAddressMapping::is_token_address(&to) {2374 return unsupported!(T);2375 }23762377 self.create_item_internal(depositor, to, data, nesting_budget)2378 }23792380 /// Create a collection's item.2381 fn create_item_internal(2382 &self,2383 depositor: &T::CrossAccountId,2384 to: T::CrossAccountId,2385 data: CreateItemData,2386 nesting_budget: &dyn Budget,2387 ) -> Result<TokenId, DispatchError>;23882389 /// Transfer an item from the `from` account to the `to` account using a transaction.2390 ///2391 /// This function performs additional XCM-related checks before the actual transfer.2392 ///2393 /// The `transactional` attribute is needed because the inbound XCM messages2394 /// are processed in a non-transactional context.2395 /// To perform the needed logic, we use the internal pallets' functions2396 /// that are not inherently safe to use outside a transaction.2397 ///2398 /// This requirement is temporary until XCM message processing becomes transactional:2399 /// https://github.com/paritytech/polkadot-sdk/issues/4902400 #[transactional]2401 fn transfer_item(2402 &self,2403 depositor: &T::CrossAccountId,2404 from: &T::CrossAccountId,2405 to: &T::CrossAccountId,2406 token: TokenId,2407 amount: u128,2408 nesting_budget: &dyn Budget,2409 ) -> DispatchResult {2410 if T::CrossTokenAddressMapping::is_token_address(to) {2411 return unsupported!(T);2412 }24132414 if self.token_has_children(token) {2415 return unsupported!(T);2416 }24172418 self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2419 }24202421 /// Transfer an item from the `from` account to the `to` account.2422 fn transfer_item_internal(2423 &self,2424 depositor: &T::CrossAccountId,2425 from: &T::CrossAccountId,2426 to: &T::CrossAccountId,2427 token: TokenId,2428 amount: u128,2429 nesting_budget: &dyn Budget,2430 ) -> DispatchResult;24312432 /// Burn a collection's item using a transaction.2433 ///2434 /// The `transactional` attribute is needed because the inbound XCM messages2435 /// are processed in a non-transactional context.2436 /// To perform the needed logic, we use the internal pallets' functions2437 /// that are not inherently safe to use outside a transaction.2438 ///2439 /// This requirement is temporary until XCM message processing becomes transactional:2440 /// https://github.com/paritytech/polkadot-sdk/issues/4902441 #[transactional]2442 fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2443 self.burn_item_internal(from, token, amount)2444 }24452446 /// Burn a collection's item.2447 fn burn_item_internal(2448 &self,2449 from: T::CrossAccountId,2450 token: TokenId,2451 amount: u128,2452 ) -> DispatchResult;2453}24542455/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2456///2457/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2458pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2459 let post_info = PostDispatchInfo {2460 actual_weight: Some(weight),2461 pays_fee: Pays::Yes,2462 };2463 match res {2464 Ok(()) => Ok(post_info),2465 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2466 }2467}24682469impl<T: Config> From<PropertiesError> for Error<T> {2470 fn from(error: PropertiesError) -> Self {2471 match error {2472 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2473 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2474 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2475 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2476 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2477 }2478 }2479}24802481/// The type-safe interface for writing properties (setting or deleting) to tokens.2482/// It has two distinct implementations for newly created tokens and existing ones.2483///2484/// This type utilizes the lazy evaluation to avoid repeating the computation2485/// of several performance-heavy or PoV-heavy tasks,2486/// such as checking the indirect ownership or reading the token property permissions.2487pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2488 collection: &'a Handle,2489 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2490 _phantom: PhantomData<(T, WriterVariant)>,2491}24922493impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2494where2495 T: Config,2496 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2497{2498 fn internal_write_token_properties(2499 &mut self,2500 token_id: TokenId,2501 mut token_lazy_info: PropertyWriterLazyTokenInfo,2502 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2503 log: evm_coder::ethereum::Log,2504 ) -> DispatchResult {2505 for (key, value) in properties_updates {2506 let permission = self2507 .collection_lazy_info2508 .property_permissions2509 .value()2510 .get(&key)2511 .cloned()2512 .unwrap_or_else(PropertyPermission::none);25132514 match permission {2515 PropertyPermission { mutable: false, .. }2516 if token_lazy_info2517 .stored_properties2518 .value()2519 .get(&key)2520 .is_some() =>2521 {2522 return Err(<Error<T>>::NoPermission.into());2523 }25242525 PropertyPermission {2526 collection_admin,2527 token_owner,2528 ..2529 } => check_token_permissions::<T>(2530 collection_admin,2531 token_owner,2532 &mut self.collection_lazy_info.is_collection_admin,2533 &mut token_lazy_info.is_token_owner,2534 &mut token_lazy_info.is_token_exist,2535 )?,2536 }25372538 match value {2539 Some(value) => {2540 token_lazy_info2541 .stored_properties2542 .value_mut()2543 .try_set(key.clone(), value)2544 .map_err(<Error<T>>::from)?;25452546 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2547 self.collection.id,2548 token_id,2549 key,2550 ));2551 }2552 None => {2553 token_lazy_info2554 .stored_properties2555 .value_mut()2556 .remove(&key)2557 .map_err(<Error<T>>::from)?;25582559 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2560 self.collection.id,2561 token_id,2562 key,2563 ));2564 }2565 }2566 }25672568 let properties_changed = token_lazy_info.stored_properties.has_value();2569 if properties_changed {2570 <PalletEvm<T>>::deposit_log(log);25712572 self.collection2573 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2574 }25752576 Ok(())2577 }2578}25792580/// A helper structure for the [`PropertyWriter`] that holds2581/// the collection-related info. The info is loaded using lazy evaluation.2582/// This info is common for any token for which we write properties.2583pub struct PropertyWriterLazyCollectionInfo<'a> {2584 is_collection_admin: LazyValue<'a, bool>,2585 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2586}25872588/// A helper structure for the [`PropertyWriter`] that holds2589/// the token-related info. The info is loaded using lazy evaluation.2590pub struct PropertyWriterLazyTokenInfo<'a> {2591 is_token_exist: LazyValue<'a, bool>,2592 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2593 stored_properties: LazyValue<'a, TokenProperties>,2594}25952596impl<'a> PropertyWriterLazyTokenInfo<'a> {2597 /// Create a lazy token info.2598 pub fn new(2599 check_token_exist: impl FnOnce() -> bool + 'a,2600 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2601 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2602 ) -> Self {2603 Self {2604 is_token_exist: LazyValue::new(check_token_exist),2605 is_token_owner: LazyValue::new(check_token_owner),2606 stored_properties: LazyValue::new(get_token_properties),2607 }2608 }2609}26102611/// A marker structure that enables the writer implementation2612/// to provide the interface to write properties to **newly created** tokens.2613pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2614impl<T: Config> NewTokenPropertyWriter<T> {2615 /// Creates a [`PropertyWriter`] for **newly created** tokens.2616 pub fn new<'a, Handle>(2617 collection: &'a Handle,2618 sender: &'a T::CrossAccountId,2619 ) -> PropertyWriter<'a, Self, T, Handle>2620 where2621 T: Config,2622 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2623 {2624 PropertyWriter {2625 collection,2626 collection_lazy_info: PropertyWriterLazyCollectionInfo {2627 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2628 property_permissions: LazyValue::new(|| {2629 <Pallet<T>>::property_permissions(collection.id)2630 }),2631 },2632 _phantom: PhantomData,2633 }2634 }2635}26362637impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2638where2639 T: Config,2640 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2641{2642 /// A function to write properties to a **newly created** token.2643 pub fn write_token_properties(2644 &mut self,2645 mint_target_is_sender: bool,2646 token_id: TokenId,2647 properties_updates: impl Iterator<Item = Property>,2648 log: evm_coder::ethereum::Log,2649 ) -> DispatchResult {2650 let check_token_exist = || {2651 debug_assert!(self.collection.token_exists(token_id));2652 true2653 };26542655 let check_token_owner = || Ok(mint_target_is_sender);26562657 let get_token_properties = || {2658 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2659 TokenProperties::new()2660 };26612662 self.internal_write_token_properties(2663 token_id,2664 PropertyWriterLazyTokenInfo::new(2665 check_token_exist,2666 check_token_owner,2667 get_token_properties,2668 ),2669 properties_updates.map(|p| (p.key, Some(p.value))),2670 log,2671 )2672 }2673}26742675/// A marker structure that enables the writer implementation2676/// to provide the interface to write properties to **already existing** tokens.2677pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2678impl<T: Config> ExistingTokenPropertyWriter<T> {2679 /// Creates a [`PropertyWriter`] for **already existing** tokens.2680 pub fn new<'a, Handle>(2681 collection: &'a Handle,2682 sender: &'a T::CrossAccountId,2683 ) -> PropertyWriter<'a, Self, T, Handle>2684 where2685 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2686 {2687 PropertyWriter {2688 collection,2689 collection_lazy_info: PropertyWriterLazyCollectionInfo {2690 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2691 property_permissions: LazyValue::new(|| {2692 <Pallet<T>>::property_permissions(collection.id)2693 }),2694 },2695 _phantom: PhantomData,2696 }2697 }2698}26992700impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2701where2702 T: Config,2703 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2704{2705 /// A function to write properties to an **already existing** token.2706 pub fn write_token_properties(2707 &mut self,2708 sender: &T::CrossAccountId,2709 token_id: TokenId,2710 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2711 nesting_budget: &dyn Budget,2712 log: evm_coder::ethereum::Log,2713 ) -> DispatchResult {2714 let check_token_exist = || self.collection.token_exists(token_id);2715 let check_token_owner = || {2716 self.collection2717 .check_token_indirect_owner(token_id, sender, nesting_budget)2718 };2719 let get_token_properties = || {2720 self.collection2721 .get_token_properties_raw(token_id)2722 .unwrap_or_default()2723 };27242725 self.internal_write_token_properties(2726 token_id,2727 PropertyWriterLazyTokenInfo::new(2728 check_token_exist,2729 check_token_owner,2730 get_token_properties,2731 ),2732 properties_updates,2733 log,2734 )2735 }2736}27372738/// A marker structure that enables the writer implementation2739/// to benchmark the token properties writing.2740#[cfg(feature = "runtime-benchmarks")]2741pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27422743#[cfg(feature = "runtime-benchmarks")]2744impl<T: Config> BenchmarkPropertyWriter<T> {2745 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2746 pub fn new<'a, Handle>(2747 collection: &'a Handle,2748 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2749 ) -> PropertyWriter<'a, Self, T, Handle>2750 where2751 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2752 {2753 PropertyWriter {2754 collection,2755 collection_lazy_info,2756 _phantom: PhantomData,2757 }2758 }27592760 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2761 pub fn load_collection_info<Handle>(2762 collection_handle: &Handle,2763 sender: &T::CrossAccountId,2764 ) -> PropertyWriterLazyCollectionInfo<'static>2765 where2766 Handle: Deref<Target = CollectionHandle<T>>,2767 {2768 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2769 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27702771 PropertyWriterLazyCollectionInfo {2772 is_collection_admin: LazyValue::new(move || is_collection_admin),2773 property_permissions: LazyValue::new(move || property_permissions),2774 }2775 }27762777 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2778 pub fn load_token_properties<Handle>(2779 collection: &Handle,2780 token_id: TokenId,2781 ) -> PropertyWriterLazyTokenInfo2782 where2783 Handle: CommonCollectionOperations<T>,2784 {2785 let stored_properties = collection2786 .get_token_properties_raw(token_id)2787 .unwrap_or_default();27882789 PropertyWriterLazyTokenInfo {2790 is_token_exist: LazyValue::new(|| true),2791 is_token_owner: LazyValue::new(|| Ok(true)),2792 stored_properties: LazyValue::new(move || stored_properties),2793 }2794 }2795}27962797#[cfg(feature = "runtime-benchmarks")]2798impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2799where2800 T: Config,2801 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2802{2803 /// A function to benchmark the writing of token properties.2804 pub fn write_token_properties(2805 &mut self,2806 token_id: TokenId,2807 properties_updates: impl Iterator<Item = Property>,2808 log: evm_coder::ethereum::Log,2809 ) -> DispatchResult {2810 let check_token_exist = || true;2811 let check_token_owner = || Ok(true);2812 let get_token_properties = TokenProperties::new;28132814 self.internal_write_token_properties(2815 token_id,2816 PropertyWriterLazyTokenInfo::new(2817 check_token_exist,2818 check_token_owner,2819 get_token_properties,2820 ),2821 properties_updates.map(|p| (p.key, Some(p.value))),2822 log,2823 )2824 }2825}28262827/// Computes the weight of writing properties to tokens.2828/// * `properties_nums` - The properties num of each created token.2829/// * `per_token_weight_weight` - The function to obtain the weight2830/// of writing properties from a token's properties num.2831pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2832 properties_nums: impl Iterator<Item = u32>,2833 per_token_weight: I,2834) -> Weight {2835 let mut weight = properties_nums2836 .filter_map(|properties_num| {2837 if properties_num > 0 {2838 Some(per_token_weight(properties_num))2839 } else {2840 None2841 }2842 })2843 .fold(Weight::zero(), |a, b| a.saturating_add(b));28442845 if !weight.is_zero() {2846 // If we are here, it means the token properties were written at least once.2847 // Because of that, some common collection data was also loaded; we must add this weight.2848 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28492850 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2851 }28522853 weight2854}28552856#[cfg(any(feature = "tests", test))]2857#[allow(missing_docs)]2858pub mod tests {2859 use crate::{Config, DispatchError, DispatchResult, LazyValue};28602861 const fn to_bool(u: u8) -> bool {2862 u != 02863 }28642865 #[derive(Debug)]2866 pub struct TestCase {2867 pub collection_admin: bool,2868 pub is_collection_admin: bool,2869 pub token_owner: bool,2870 pub is_token_owner: bool,2871 pub no_permission: bool,2872 }28732874 impl TestCase {2875 const fn new(2876 collection_admin: u8,2877 is_collection_admin: u8,2878 token_owner: u8,2879 is_token_owner: u8,2880 no_permission: u8,2881 ) -> Self {2882 Self {2883 collection_admin: to_bool(collection_admin),2884 is_collection_admin: to_bool(is_collection_admin),2885 token_owner: to_bool(token_owner),2886 is_token_owner: to_bool(is_token_owner),2887 no_permission: to_bool(no_permission),2888 }2889 }2890 }28912892 #[rustfmt::skip]2893 pub const TABLE: [TestCase; 16] = [2894 // ┌╴collection_admin2895 // │ ┌╴is_collection_admin2896 // │ │ ┌╴token_owner2897 // │ │ │ ┌╴is_token_ownership2898 // │ │ │ │ ┌╴no_permission2899 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2900 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2901 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2902 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2903 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2904 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2905 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2906 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2907 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2908 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2909 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2910 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2911 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2912 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2913 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2914 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2915 ];29162917 pub fn check_token_permissions<T: Config>(2918 collection_admin_permitted: bool,2919 token_owner_permitted: bool,2920 is_collection_admin: &mut LazyValue<bool>,2921 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2922 check_token_existence: &mut LazyValue<bool>,2923 ) -> DispatchResult {2924 crate::check_token_permissions::<T>(2925 collection_admin_permitted,2926 token_owner_permitted,2927 is_collection_admin,2928 check_token_ownership,2929 check_token_existence,2930 )2931 }2932}