difftreelog
fix clippy
in: master
5 files 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}946947fn check_token_permissions<T: Config>(948 collection_admin_permitted: bool,949 token_owner_permitted: bool,950 is_collection_admin: &mut LazyValue<bool>,951 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,952 is_token_exist: &mut LazyValue<bool>,953) -> DispatchResult {954 if !(collection_admin_permitted && *is_collection_admin.value()955 || token_owner_permitted && (*is_token_owner.value())?)956 {957 fail!(<Error<T>>::NoPermission);958 }959960 let token_exist_due_to_owner_check_success =961 is_token_owner.has_value() && (*is_token_owner.value())?;962963 // If the token owner check has occurred and succeeded,964 // we know the token exists (otherwise, the owner check must fail).965 if !token_exist_due_to_owner_check_success {966 // If the token owner check didn't occur,967 // we must check the token's existence ourselves.968 if !is_token_exist.value() {969 fail!(<Error<T>>::TokenNotFound);970 }971 }972973 Ok(())974}975976impl<T: Config> Pallet<T> {977 /// Enshure that receiver address is correct.978 ///979 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.980 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {981 ensure!(982 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,983 <Error<T>>::AddressIsZero984 );985 Ok(())986 }987988 /// Get a vector of collection admins.989 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {990 <IsAdmin<T>>::iter_prefix((collection,))991 .map(|(a, _)| a)992 .collect()993 }994995 /// Get a vector of users allowed to mint tokens.996 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {997 <Allowlist<T>>::iter_prefix((collection,))998 .map(|(a, _)| a)999 .collect()1000 }10011002 /// Is `user` allowed to mint token in `collection`.1003 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1004 <Allowlist<T>>::get((collection, user))1005 }10061007 /// Get statistics of collections.1008 pub fn collection_stats() -> CollectionStats {1009 let created = <CreatedCollectionCount<T>>::get();1010 let destroyed = <DestroyedCollectionCount<T>>::get();1011 CollectionStats {1012 created: created.0,1013 destroyed: destroyed.0,1014 alive: created.0 - destroyed.0,1015 }1016 }10171018 /// Get the effective limits for the collection.1019 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1020 let collection = <CollectionById<T>>::get(collection)?;1021 let limits = collection.limits;1022 let effective_limits = CollectionLimits {1023 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1024 sponsored_data_size: Some(limits.sponsored_data_size()),1025 sponsored_data_rate_limit: Some(1026 limits1027 .sponsored_data_rate_limit1028 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1029 ),1030 token_limit: Some(limits.token_limit()),1031 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1032 match collection.mode {1033 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1034 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1035 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1036 },1037 )),1038 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1039 owner_can_transfer: Some(limits.owner_can_transfer()),1040 owner_can_destroy: Some(limits.owner_can_destroy()),1041 transfers_enabled: Some(limits.transfers_enabled()),1042 };10431044 Some(effective_limits)1045 }10461047 /// Returns information about the `collection` adapted for rpc.1048 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1049 let Collection {1050 name,1051 description,1052 owner,1053 mode,1054 token_prefix,1055 sponsorship,1056 limits,1057 permissions,1058 flags,1059 } = <CollectionById<T>>::get(collection)?;10601061 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1062 .into_iter()1063 .map(|(key, permission)| PropertyKeyPermission { key, permission })1064 .collect();10651066 let properties = <CollectionProperties<T>>::get(collection)1067 .into_iter()1068 .map(|(key, value)| Property { key, value })1069 .collect();10701071 let permissions = CollectionPermissions {1072 access: Some(permissions.access()),1073 mint_mode: Some(permissions.mint_mode()),1074 nesting: Some(permissions.nesting().clone()),1075 };10761077 Some(RpcCollection {1078 name: name.into_inner(),1079 description: description.into_inner(),1080 owner,1081 mode,1082 token_prefix: token_prefix.into_inner(),1083 sponsorship,1084 limits,1085 permissions,1086 token_property_permissions,1087 properties,1088 read_only: flags.external,10891090 flags: RpcCollectionFlags {1091 foreign: flags.foreign,1092 erc721metadata: flags.erc721metadata,1093 },1094 })1095 }1096}10971098macro_rules! limit_default {1099 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1100 $(1101 if let Some($new) = $new.$field {1102 let $old = $old.$field($($arg)?);1103 let _ = $new;1104 let _ = $old;1105 $check1106 } else {1107 $new.$field = $old.$field1108 }1109 )*1110 }};1111}1112macro_rules! limit_default_clone {1113 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1114 $(1115 if let Some($new) = $new.$field.clone() {1116 let $old = $old.$field($($arg)?);1117 let _ = $new;1118 let _ = $old;1119 $check1120 } else {1121 $new.$field = $old.$field.clone()1122 }1123 )*1124 }};1125}11261127impl<T: Config> Pallet<T> {1128 /// Create new collection.1129 ///1130 /// * `owner` - The owner of the collection.1131 /// * `payer` - If set, the user that will pay a deposit for the collection creation.1132 /// * `data` - Description of the created collection.1133 /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1134 pub fn init_collection(1135 owner: T::CrossAccountId,1136 payer: Option<T::CrossAccountId>,1137 is_special_collection: bool,1138 data: CreateCollectionData<T::CrossAccountId>,1139 ) -> Result<CollectionId, DispatchError> {1140 if !is_special_collection {1141 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1142 }11431144 // Take a (non-refundable) deposit of collection creation1145 if let Some(payer) = payer {1146 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1147 imbalance.subsume(<T as Config>::Currency::deposit(1148 &T::TreasuryAccountId::get(),1149 T::CollectionCreationPrice::get(),1150 Precision::Exact,1151 )?);1152 let credit =1153 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1154 .map_err(|_| Error::<T>::NotSufficientFounds)?;11551156 debug_assert!(credit.peek().is_zero())1157 }11581159 Self::init_collection_internal(owner, data)1160 }11611162 fn init_collection_internal(1163 owner: T::CrossAccountId,1164 data: CreateCollectionData<T::CrossAccountId>,1165 ) -> Result<CollectionId, DispatchError> {1166 {1167 ensure!(1168 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1169 Error::<T>::CollectionTokenPrefixLimitExceeded1170 );1171 }11721173 let created_count = <CreatedCollectionCount<T>>::get()1174 .01175 .checked_add(1)1176 .ok_or(ArithmeticError::Overflow)?;1177 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1178 let id = CollectionId(created_count);11791180 // bound Total number of collections1181 ensure!(1182 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1183 <Error<T>>::TotalCollectionsLimitExceeded1184 );11851186 // =========11871188 let collection = Collection {1189 owner: owner.as_sub().clone(),1190 name: data.name,1191 mode: data.mode.clone(),1192 description: data.description,1193 token_prefix: data.token_prefix,1194 sponsorship: data1195 .pending_sponsor1196 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1197 .unwrap_or_default(),1198 limits: data1199 .limits1200 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1201 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1202 permissions: data1203 .permissions1204 .map(|permissions| {1205 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1206 })1207 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1208 flags: data.flags,1209 };12101211 let mut collection_properties = CollectionPropertiesT::new();1212 collection_properties1213 .try_set_from_iter(data.properties.into_iter())1214 .map_err(<Error<T>>::from)?;12151216 CollectionProperties::<T>::insert(id, collection_properties);12171218 let mut token_props_permissions = PropertiesPermissionMap::new();1219 token_props_permissions1220 .try_set_from_iter(data.token_property_permissions.into_iter())1221 .map_err(<Error<T>>::from)?;12221223 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12241225 let mut admin_amount = 0u32;1226 for admin in data.admin_list.iter() {1227 if !<IsAdmin<T>>::get((id, admin)) {1228 <IsAdmin<T>>::insert((id, admin), true);1229 admin_amount = admin_amount1230 .checked_add(1)1231 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1232 }1233 }1234 ensure!(1235 admin_amount <= Self::collection_admins_limit(),1236 <Error<T>>::CollectionAdminCountExceeded,1237 );1238 <AdminAmount<T>>::insert(id, admin_amount);12391240 <CreatedCollectionCount<T>>::put(created_count);1241 <Pallet<T>>::deposit_event(Event::CollectionCreated(1242 id,1243 data.mode.id(),1244 owner.as_sub().clone(),1245 ));1246 <PalletEvm<T>>::deposit_log(1247 erc::CollectionHelpersEvents::CollectionCreated {1248 owner: *owner.as_eth(),1249 collection_id: eth::collection_id_to_address(id),1250 }1251 .to_log(T::ContractAddress::get()),1252 );1253 <CollectionById<T>>::insert(id, collection);1254 Ok(id)1255 }12561257 /// Destroy collection.1258 ///1259 /// * `collection` - Collection handler.1260 /// * `sender` - The owner or administrator of the collection.1261 pub fn destroy_collection(1262 collection: CollectionHandle<T>,1263 sender: &T::CrossAccountId,1264 ) -> DispatchResult {1265 ensure!(1266 collection.limits.owner_can_destroy(),1267 <Error<T>>::NoPermission,1268 );1269 collection.check_is_owner(sender)?;12701271 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1272 .01273 .checked_add(1)1274 .ok_or(ArithmeticError::Overflow)?;12751276 // =========12771278 <DestroyedCollectionCount<T>>::put(destroyed_collections);1279 <CollectionById<T>>::remove(collection.id);1280 <AdminAmount<T>>::remove(collection.id);1281 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1282 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1283 <CollectionProperties<T>>::remove(collection.id);12841285 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12861287 <PalletEvm<T>>::deposit_log(1288 erc::CollectionHelpersEvents::CollectionDestroyed {1289 collection_id: eth::collection_id_to_address(collection.id),1290 }1291 .to_log(T::ContractAddress::get()),1292 );1293 Ok(())1294 }12951296 /// This function sets or removes a collection properties according to1297 /// `properties_updates` contents:1298 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1299 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1300 ///1301 /// This function fires an event for each property change.1302 /// In case of an error, all the changes (including the events) will be reverted1303 /// since the function is transactional.1304 #[transactional]1305 fn modify_collection_properties(1306 collection: &CollectionHandle<T>,1307 sender: &T::CrossAccountId,1308 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1309 ) -> DispatchResult {1310 collection.check_is_owner_or_admin(sender)?;13111312 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13131314 for (key, value) in properties_updates {1315 match value {1316 Some(value) => {1317 stored_properties1318 .try_set(key.clone(), value)1319 .map_err(<Error<T>>::from)?;13201321 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1322 <PalletEvm<T>>::deposit_log(1323 erc::CollectionHelpersEvents::CollectionChanged {1324 collection_id: eth::collection_id_to_address(collection.id),1325 }1326 .to_log(T::ContractAddress::get()),1327 );1328 }1329 None => {1330 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13311332 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1333 <PalletEvm<T>>::deposit_log(1334 erc::CollectionHelpersEvents::CollectionChanged {1335 collection_id: eth::collection_id_to_address(collection.id),1336 }1337 .to_log(T::ContractAddress::get()),1338 );1339 }1340 }1341 }13421343 <CollectionProperties<T>>::set(collection.id, stored_properties);13441345 Ok(())1346 }13471348 /// Sets or unsets the approval of a given operator.1349 ///1350 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1351 /// - `owner`: Token owner1352 /// - `operator`: Operator1353 /// - `approve`: Should operator status be granted or revoked?1354 pub fn set_allowance_for_all(1355 collection: &CollectionHandle<T>,1356 owner: &T::CrossAccountId,1357 operator: &T::CrossAccountId,1358 approve: bool,1359 set_allowance: impl FnOnce(),1360 log: evm_coder::ethereum::Log,1361 ) -> DispatchResult {1362 if collection.permissions.access() == AccessMode::AllowList {1363 collection.check_allowlist(owner)?;1364 collection.check_allowlist(operator)?;1365 }13661367 Self::ensure_correct_receiver(operator)?;13681369 set_allowance();13701371 <PalletEvm<T>>::deposit_log(log);1372 Self::deposit_event(Event::ApprovedForAll(1373 collection.id,1374 owner.clone(),1375 operator.clone(),1376 approve,1377 ));1378 Ok(())1379 }13801381 /// Set collection property.1382 ///1383 /// * `collection` - Collection handler.1384 /// * `sender` - The owner or administrator of the collection.1385 /// * `property` - The property to set.1386 pub fn set_collection_property(1387 collection: &CollectionHandle<T>,1388 sender: &T::CrossAccountId,1389 property: Property,1390 ) -> DispatchResult {1391 Self::set_collection_properties(collection, sender, [property].into_iter())1392 }13931394 /// Set a scoped collection property, where the scope is a special prefix1395 /// prohibiting a user access to change the property directly.1396 ///1397 /// * `collection_id` - ID of the collection for which the property is being set.1398 /// * `scope` - Property scope.1399 /// * `property` - The property to set.1400 pub fn set_scoped_collection_property(1401 collection_id: CollectionId,1402 scope: PropertyScope,1403 property: Property,1404 ) -> DispatchResult {1405 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1406 properties.try_scoped_set(scope, property.key, property.value)1407 })1408 .map_err(<Error<T>>::from)?;14091410 Ok(())1411 }14121413 /// Set scoped collection properties, where the scope is a special prefix1414 /// prohibiting a user access to change the properties directly.1415 ///1416 /// * `collection_id` - ID of the collection for which the properties is being set.1417 /// * `scope` - Property scope.1418 /// * `properties` - The properties to set.1419 pub fn set_scoped_collection_properties(1420 collection_id: CollectionId,1421 scope: PropertyScope,1422 properties: impl Iterator<Item = Property>,1423 ) -> DispatchResult {1424 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1425 stored_properties.try_scoped_set_from_iter(scope, properties)1426 })1427 .map_err(<Error<T>>::from)?;14281429 Ok(())1430 }14311432 /// Set collection properties.1433 ///1434 /// * `collection` - Collection handler.1435 /// * `sender` - The owner or administrator of the collection.1436 /// * `properties` - The properties to set.1437 pub fn set_collection_properties(1438 collection: &CollectionHandle<T>,1439 sender: &T::CrossAccountId,1440 properties: impl Iterator<Item = Property>,1441 ) -> DispatchResult {1442 Self::modify_collection_properties(1443 collection,1444 sender,1445 properties.map(|property| (property.key, Some(property.value))),1446 )1447 }14481449 /// Delete collection property.1450 ///1451 /// * `collection` - Collection handler.1452 /// * `sender` - The owner or administrator of the collection.1453 /// * `property` - The property to delete.1454 pub fn delete_collection_property(1455 collection: &CollectionHandle<T>,1456 sender: &T::CrossAccountId,1457 property_key: PropertyKey,1458 ) -> DispatchResult {1459 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1460 }14611462 /// Delete collection properties.1463 ///1464 /// * `collection` - Collection handler.1465 /// * `sender` - The owner or administrator of the collection.1466 /// * `properties` - The properties to delete.1467 pub fn delete_collection_properties(1468 collection: &CollectionHandle<T>,1469 sender: &T::CrossAccountId,1470 property_keys: impl Iterator<Item = PropertyKey>,1471 ) -> DispatchResult {1472 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1473 }14741475 /// Set collection propetry permission without any checks.1476 ///1477 /// Used for migrations.1478 ///1479 /// * `collection` - Collection handler.1480 /// * `property_permissions` - Property permissions.1481 pub fn set_property_permission_unchecked(1482 collection: CollectionId,1483 property_permission: PropertyKeyPermission,1484 ) -> DispatchResult {1485 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1486 permissions.try_set(property_permission.key, property_permission.permission)1487 })1488 .map_err(<Error<T>>::from)?;1489 Ok(())1490 }14911492 /// Set collection property permission.1493 ///1494 /// * `collection` - Collection handler.1495 /// * `sender` - The owner or administrator of the collection.1496 /// * `property_permission` - Property permission.1497 pub fn set_property_permission(1498 collection: &CollectionHandle<T>,1499 sender: &T::CrossAccountId,1500 property_permission: PropertyKeyPermission,1501 ) -> DispatchResult {1502 Self::set_scoped_property_permission(1503 collection,1504 sender,1505 PropertyScope::None,1506 property_permission,1507 )1508 }15091510 /// Set collection property permission with scope.1511 ///1512 /// * `collection` - Collection handler.1513 /// * `sender` - The owner or administrator of the collection.1514 /// * `scope` - Property scope.1515 /// * `property_permission` - Property permission.1516 pub fn set_scoped_property_permission(1517 collection: &CollectionHandle<T>,1518 sender: &T::CrossAccountId,1519 scope: PropertyScope,1520 property_permission: PropertyKeyPermission,1521 ) -> DispatchResult {1522 collection.check_is_owner_or_admin(sender)?;15231524 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1525 let current_permission = all_permissions.get(&property_permission.key);1526 if matches![1527 current_permission,1528 Some(PropertyPermission { mutable: false, .. })1529 ] {1530 return Err(<Error<T>>::NoPermission.into());1531 }15321533 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1534 let property_permission = property_permission.clone();1535 permissions.try_scoped_set(1536 scope,1537 property_permission.key,1538 property_permission.permission,1539 )1540 })1541 .map_err(<Error<T>>::from)?;15421543 Self::deposit_event(Event::PropertyPermissionSet(1544 collection.id,1545 property_permission.key,1546 ));1547 <PalletEvm<T>>::deposit_log(1548 erc::CollectionHelpersEvents::CollectionChanged {1549 collection_id: eth::collection_id_to_address(collection.id),1550 }1551 .to_log(T::ContractAddress::get()),1552 );15531554 Ok(())1555 }15561557 /// Set token property permission.1558 ///1559 /// * `collection` - Collection handler.1560 /// * `sender` - The owner or administrator of the collection.1561 /// * `property_permissions` - Property permissions.1562 #[transactional]1563 pub fn set_token_property_permissions(1564 collection: &CollectionHandle<T>,1565 sender: &T::CrossAccountId,1566 property_permissions: Vec<PropertyKeyPermission>,1567 ) -> DispatchResult {1568 Self::set_scoped_token_property_permissions(1569 collection,1570 sender,1571 PropertyScope::None,1572 property_permissions,1573 )1574 }15751576 /// Set token property permission with scope.1577 ///1578 /// * `collection` - Collection handler.1579 /// * `sender` - The owner or administrator of the collection.1580 /// * `scope` - Property scope.1581 /// * `property_permissions` - Property permissions.1582 #[transactional]1583 pub fn set_scoped_token_property_permissions(1584 collection: &CollectionHandle<T>,1585 sender: &T::CrossAccountId,1586 scope: PropertyScope,1587 property_permissions: Vec<PropertyKeyPermission>,1588 ) -> DispatchResult {1589 for prop_pemission in property_permissions {1590 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1591 }15921593 Ok(())1594 }15951596 /// Get collection property.1597 pub fn get_collection_property(1598 collection_id: CollectionId,1599 key: &PropertyKey,1600 ) -> Option<PropertyValue> {1601 Self::collection_properties(collection_id).get(key).cloned()1602 }16031604 /// Convert byte vector to property key vector.1605 pub fn bytes_keys_to_property_keys(1606 keys: Vec<Vec<u8>>,1607 ) -> Result<Vec<PropertyKey>, DispatchError> {1608 keys.into_iter()1609 .map(|key| -> Result<PropertyKey, DispatchError> {1610 key.try_into()1611 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1612 })1613 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1614 }16151616 /// Get properties according to given keys.1617 pub fn filter_collection_properties(1618 collection_id: CollectionId,1619 keys: Option<Vec<PropertyKey>>,1620 ) -> Result<Vec<Property>, DispatchError> {1621 let properties = Self::collection_properties(collection_id);16221623 let properties = keys1624 .map(|keys| {1625 keys.into_iter()1626 .filter_map(|key| {1627 properties.get(&key).map(|value| Property {1628 key,1629 value: value.clone(),1630 })1631 })1632 .collect()1633 })1634 .unwrap_or_else(|| {1635 properties1636 .into_iter()1637 .map(|(key, value)| Property { key, value })1638 .collect()1639 });16401641 Ok(properties)1642 }16431644 /// Get property permissions according to given keys.1645 pub fn filter_property_permissions(1646 collection_id: CollectionId,1647 keys: Option<Vec<PropertyKey>>,1648 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1649 let permissions = Self::property_permissions(collection_id);16501651 let key_permissions = keys1652 .map(|keys| {1653 keys.into_iter()1654 .filter_map(|key| {1655 permissions1656 .get(&key)1657 .map(|permission| PropertyKeyPermission {1658 key,1659 permission: permission.clone(),1660 })1661 })1662 .collect()1663 })1664 .unwrap_or_else(|| {1665 permissions1666 .into_iter()1667 .map(|(key, permission)| PropertyKeyPermission { key, permission })1668 .collect()1669 });16701671 Ok(key_permissions)1672 }16731674 /// Toggle `user` participation in the `collection`'s allow list.1675 /// #### Store read/writes1676 /// 1 writes1677 pub fn toggle_allowlist(1678 collection: &CollectionHandle<T>,1679 sender: &T::CrossAccountId,1680 user: &T::CrossAccountId,1681 allowed: bool,1682 ) -> DispatchResult {1683 collection.check_is_owner_or_admin(sender)?;16841685 // =========16861687 if allowed {1688 <Allowlist<T>>::insert((collection.id, user), true);1689 Self::deposit_event(Event::<T>::AllowListAddressAdded(1690 collection.id,1691 user.clone(),1692 ));1693 } else {1694 <Allowlist<T>>::remove((collection.id, user));1695 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1696 collection.id,1697 user.clone(),1698 ));1699 }17001701 <PalletEvm<T>>::deposit_log(1702 erc::CollectionHelpersEvents::CollectionChanged {1703 collection_id: eth::collection_id_to_address(collection.id),1704 }1705 .to_log(T::ContractAddress::get()),1706 );17071708 Ok(())1709 }17101711 /// Toggle `user` participation in the `collection`'s admin list.1712 /// #### Store read/writes1713 /// 2 reads, 2 writes1714 pub fn toggle_admin(1715 collection: &CollectionHandle<T>,1716 sender: &T::CrossAccountId,1717 user: &T::CrossAccountId,1718 admin: bool,1719 ) -> DispatchResult {1720 collection.check_is_internal()?;1721 collection.check_is_owner(sender)?;17221723 let is_admin = <IsAdmin<T>>::get((collection.id, user));1724 if is_admin == admin {1725 if admin {1726 return Ok(());1727 } else {1728 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1729 }1730 }1731 let amount = <AdminAmount<T>>::get(collection.id);17321733 // =========17341735 if admin {1736 let amount = amount1737 .checked_add(1)1738 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1739 ensure!(1740 amount <= Self::collection_admins_limit(),1741 <Error<T>>::CollectionAdminCountExceeded,1742 );17431744 <AdminAmount<T>>::insert(collection.id, amount);1745 <IsAdmin<T>>::insert((collection.id, user), true);17461747 Self::deposit_event(Event::<T>::CollectionAdminAdded(1748 collection.id,1749 user.clone(),1750 ));1751 } else {1752 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1753 <IsAdmin<T>>::remove((collection.id, user));17541755 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1756 collection.id,1757 user.clone(),1758 ));1759 }17601761 <PalletEvm<T>>::deposit_log(1762 erc::CollectionHelpersEvents::CollectionChanged {1763 collection_id: eth::collection_id_to_address(collection.id),1764 }1765 .to_log(T::ContractAddress::get()),1766 );17671768 Ok(())1769 }17701771 /// Update collection limits.1772 pub fn update_limits(1773 user: &T::CrossAccountId,1774 collection: &mut CollectionHandle<T>,1775 new_limit: CollectionLimits,1776 ) -> DispatchResult {1777 collection.check_is_internal()?;1778 collection.check_is_owner_or_admin(user)?;17791780 collection.limits =1781 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17821783 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1784 <PalletEvm<T>>::deposit_log(1785 erc::CollectionHelpersEvents::CollectionChanged {1786 collection_id: eth::collection_id_to_address(collection.id),1787 }1788 .to_log(T::ContractAddress::get()),1789 );17901791 collection.save()1792 }17931794 /// Merge set fields from `new_limit` to `old_limit`.1795 fn clamp_limits(1796 mode: CollectionMode,1797 old_limit: &CollectionLimits,1798 mut new_limit: CollectionLimits,1799 ) -> Result<CollectionLimits, DispatchError> {1800 let limits = old_limit;1801 limit_default!(old_limit, new_limit,1802 account_token_ownership_limit => ensure!(1803 new_limit <= MAX_TOKEN_OWNERSHIP,1804 <Error<T>>::CollectionLimitBoundsExceeded,1805 ),1806 sponsored_data_size => ensure!(1807 new_limit <= CUSTOM_DATA_LIMIT,1808 <Error<T>>::CollectionLimitBoundsExceeded,1809 ),18101811 sponsored_data_rate_limit => {},1812 token_limit => ensure!(1813 old_limit >= new_limit && new_limit > 0,1814 <Error<T>>::CollectionTokenLimitExceeded1815 ),18161817 sponsor_transfer_timeout(match mode {1818 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1819 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1820 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1821 }) => ensure!(1822 new_limit <= MAX_SPONSOR_TIMEOUT,1823 <Error<T>>::CollectionLimitBoundsExceeded,1824 ),1825 sponsor_approve_timeout => {},1826 owner_can_transfer => ensure!(1827 !limits.owner_can_transfer_instaled() ||1828 old_limit || !new_limit,1829 <Error<T>>::OwnerPermissionsCantBeReverted,1830 ),1831 owner_can_destroy => ensure!(1832 old_limit || !new_limit,1833 <Error<T>>::OwnerPermissionsCantBeReverted,1834 ),1835 transfers_enabled => {},1836 );1837 Ok(new_limit)1838 }18391840 /// Update collection permissions.1841 pub fn update_permissions(1842 user: &T::CrossAccountId,1843 collection: &mut CollectionHandle<T>,1844 new_permission: CollectionPermissions,1845 ) -> DispatchResult {1846 collection.check_is_internal()?;1847 collection.check_is_owner_or_admin(user)?;1848 collection.permissions = Self::clamp_permissions(1849 collection.mode.clone(),1850 &collection.permissions,1851 new_permission,1852 )?;18531854 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1855 <PalletEvm<T>>::deposit_log(1856 erc::CollectionHelpersEvents::CollectionChanged {1857 collection_id: eth::collection_id_to_address(collection.id),1858 }1859 .to_log(T::ContractAddress::get()),1860 );18611862 collection.save()1863 }18641865 /// Merge set fields from `new_permission` to `old_permission`.1866 fn clamp_permissions(1867 _mode: CollectionMode,1868 old_permission: &CollectionPermissions,1869 mut new_permission: CollectionPermissions,1870 ) -> Result<CollectionPermissions, DispatchError> {1871 limit_default_clone!(old_permission, new_permission,1872 access => {},1873 mint_mode => {},1874 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1875 );1876 Ok(new_permission)1877 }18781879 /// Repair possibly broken properties of a collection.1880 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1881 CollectionProperties::<T>::mutate(collection_id, |properties| {1882 properties.recompute_consumed_space();1883 });18841885 Ok(())1886 }1887}18881889/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1890#[macro_export]1891macro_rules! unsupported {1892 ($runtime:path) => {1893 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1894 };1895}18961897/// Return weights for various worst-case operations.1898pub trait CommonWeightInfo<CrossAccountId> {1899 /// Weight of item creation.1900 fn create_item(data: &CreateItemData) -> Weight {1901 Self::create_multiple_items(from_ref(data))1902 }19031904 /// Weight of items creation.1905 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19061907 /// Weight of items creation.1908 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19091910 /// The weight of the burning item.1911 fn burn_item() -> Weight;19121913 /// Property setting weight.1914 ///1915 /// * `amount`- The number of properties to set.1916 fn set_collection_properties(amount: u32) -> Weight;19171918 /// Collection property deletion weight.1919 ///1920 /// * `amount`- The number of properties to set.1921 fn delete_collection_properties(amount: u32) -> Weight {1922 Self::set_collection_properties(amount)1923 }19241925 /// Token property setting weight.1926 ///1927 /// * `amount`- The number of properties to set.1928 fn set_token_properties(amount: u32) -> Weight;19291930 /// Token property deletion weight.1931 ///1932 /// * `amount`- The number of properties to delete.1933 fn delete_token_properties(amount: u32) -> Weight {1934 Self::set_token_properties(amount)1935 }19361937 /// Token property permissions set weight.1938 ///1939 /// * `amount`- The number of property permissions to set.1940 fn set_token_property_permissions(amount: u32) -> Weight;19411942 /// Transfer price of the token or its parts.1943 fn transfer() -> Weight;19441945 /// The price of setting the permission of the operation from another user.1946 fn approve() -> Weight;19471948 /// The price of setting the permission of the operation from another user for eth mirror.1949 fn approve_from() -> Weight;19501951 /// Transfer price from another user.1952 fn transfer_from() -> Weight;19531954 /// The price of burning a token from another user.1955 fn burn_from() -> Weight;19561957 /// The price of setting approval for all1958 fn set_allowance_for_all() -> Weight;19591960 /// The price of repairing an item.1961 fn force_repair_item() -> Weight;1962}19631964/// Weight info extension trait for refungible pallet.1965pub trait RefungibleExtensionsWeightInfo {1966 /// Weight of token repartition.1967 fn repartition() -> Weight;1968}19691970/// Common collection operations.1971///1972/// It wraps methods in Fungible, Nonfungible and Refungible pallets1973/// and adds weight info.1974pub trait CommonCollectionOperations<T: Config> {1975 /// Create token.1976 ///1977 /// * `sender` - The user who mint the token and pays for the transaction.1978 /// * `to` - The user who will own the token.1979 /// * `data` - Token data.1980 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1981 fn create_item(1982 &self,1983 sender: T::CrossAccountId,1984 to: T::CrossAccountId,1985 data: CreateItemData,1986 nesting_budget: &dyn Budget,1987 ) -> DispatchResultWithPostInfo;19881989 /// Create multiple tokens.1990 ///1991 /// * `sender` - The user who mint the token and pays for the transaction.1992 /// * `to` - The user who will own the token.1993 /// * `data` - Token data.1994 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1995 fn create_multiple_items(1996 &self,1997 sender: T::CrossAccountId,1998 to: T::CrossAccountId,1999 data: Vec<CreateItemData>,2000 nesting_budget: &dyn Budget,2001 ) -> DispatchResultWithPostInfo;20022003 /// Create multiple tokens.2004 ///2005 /// * `sender` - The user who mint the token and pays for the transaction.2006 /// * `to` - The user who will own the token.2007 /// * `data` - Token data.2008 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2009 fn create_multiple_items_ex(2010 &self,2011 sender: T::CrossAccountId,2012 data: CreateItemExData<T::CrossAccountId>,2013 nesting_budget: &dyn Budget,2014 ) -> DispatchResultWithPostInfo;20152016 /// Burn token.2017 ///2018 /// * `sender` - The user who owns the token.2019 /// * `token` - Token id that will burned.2020 /// * `amount` - The number of parts of the token that will be burned.2021 fn burn_item(2022 &self,2023 sender: T::CrossAccountId,2024 token: TokenId,2025 amount: u128,2026 ) -> DispatchResultWithPostInfo;20272028 /// Set collection properties.2029 ///2030 /// * `sender` - Must be either the owner of the collection or its admin.2031 /// * `properties` - Properties to be set.2032 fn set_collection_properties(2033 &self,2034 sender: T::CrossAccountId,2035 properties: Vec<Property>,2036 ) -> DispatchResultWithPostInfo;20372038 /// Delete collection properties.2039 ///2040 /// * `sender` - Must be either the owner of the collection or its admin.2041 /// * `properties` - The properties to be removed.2042 fn delete_collection_properties(2043 &self,2044 sender: &T::CrossAccountId,2045 property_keys: Vec<PropertyKey>,2046 ) -> DispatchResultWithPostInfo;20472048 /// Set token properties.2049 ///2050 /// The appropriate [`PropertyPermission`] for the token property2051 /// must be set with [`Self::set_token_property_permissions`].2052 ///2053 /// * `sender` - Must be either the owner of the token or its admin.2054 /// * `token_id` - The token for which the properties are being set.2055 /// * `properties` - Properties to be set.2056 /// * `budget` - Budget for setting properties.2057 fn set_token_properties(2058 &self,2059 sender: T::CrossAccountId,2060 token_id: TokenId,2061 properties: Vec<Property>,2062 budget: &dyn Budget,2063 ) -> DispatchResultWithPostInfo;20642065 /// Remove token properties.2066 ///2067 /// The appropriate [`PropertyPermission`] for the token property2068 /// must be set with [`Self::set_token_property_permissions`].2069 ///2070 /// * `sender` - Must be either the owner of the token or its admin.2071 /// * `token_id` - The token for which the properties are being remove.2072 /// * `property_keys` - Keys to remove corresponding properties.2073 /// * `budget` - Budget for removing properties.2074 fn delete_token_properties(2075 &self,2076 sender: T::CrossAccountId,2077 token_id: TokenId,2078 property_keys: Vec<PropertyKey>,2079 budget: &dyn Budget,2080 ) -> DispatchResultWithPostInfo;20812082 /// Get token properties raw map.2083 ///2084 /// * `token_id` - The token which properties are needed.2085 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20862087 /// Set token properties raw map.2088 ///2089 /// * `token_id` - The token for which the properties are being set.2090 /// * `map` - The raw map containing the token's properties.2091 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20922093 /// Set token property permissions.2094 ///2095 /// * `sender` - Must be either the owner of the token or its admin.2096 /// * `token_id` - The token for which the properties are being set.2097 /// * `property_permissions` - Property permissions to be set.2098 /// * `budget` - Budget for setting properties.2099 fn set_token_property_permissions(2100 &self,2101 sender: &T::CrossAccountId,2102 property_permissions: Vec<PropertyKeyPermission>,2103 ) -> DispatchResultWithPostInfo;21042105 /// Transfer amount of token pieces.2106 ///2107 /// * `sender` - Donor user.2108 /// * `to` - Recepient user.2109 /// * `token` - The token of which parts are being sent.2110 /// * `amount` - The number of parts of the token that will be transferred.2111 /// * `budget` - The maximum budget that can be spent on the transfer.2112 fn transfer(2113 &self,2114 sender: T::CrossAccountId,2115 to: T::CrossAccountId,2116 token: TokenId,2117 amount: u128,2118 budget: &dyn Budget,2119 ) -> DispatchResultWithPostInfo;21202121 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2122 ///2123 /// * `sender` - The user who grants access to the token.2124 /// * `spender` - The user to whom the rights are granted.2125 /// * `token` - The token to which access is granted.2126 /// * `amount` - The amount of pieces that another user can dispose of.2127 fn approve(2128 &self,2129 sender: T::CrossAccountId,2130 spender: T::CrossAccountId,2131 token: TokenId,2132 amount: u128,2133 ) -> DispatchResultWithPostInfo;21342135 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2136 ///2137 /// * `sender` - The user who grants access to the token.2138 /// * `from` - Spender's eth mirror.2139 /// * `to` - The user to whom the rights are granted.2140 /// * `token` - The token to which access is granted.2141 /// * `amount` - The amount of pieces that another user can dispose of.2142 fn approve_from(2143 &self,2144 sender: T::CrossAccountId,2145 from: T::CrossAccountId,2146 to: T::CrossAccountId,2147 token: TokenId,2148 amount: u128,2149 ) -> DispatchResultWithPostInfo;21502151 /// Send parts of a token owned by another user.2152 ///2153 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2154 ///2155 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2156 /// * `from` - The user who owns the token.2157 /// * `to` - Recepient user.2158 /// * `token` - The token of which parts are being sent.2159 /// * `amount` - The number of parts of the token that will be transferred.2160 /// * `budget` - The maximum budget that can be spent on the transfer.2161 fn transfer_from(2162 &self,2163 sender: T::CrossAccountId,2164 from: T::CrossAccountId,2165 to: T::CrossAccountId,2166 token: TokenId,2167 amount: u128,2168 budget: &dyn Budget,2169 ) -> DispatchResultWithPostInfo;21702171 /// Burn parts of a token owned by another user.2172 ///2173 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2174 ///2175 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2176 /// * `from` - The user who owns the token.2177 /// * `token` - The token of which parts are being sent.2178 /// * `amount` - The number of parts of the token that will be transferred.2179 /// * `budget` - The maximum budget that can be spent on the burn.2180 fn burn_from(2181 &self,2182 sender: T::CrossAccountId,2183 from: T::CrossAccountId,2184 token: TokenId,2185 amount: u128,2186 budget: &dyn Budget,2187 ) -> DispatchResultWithPostInfo;21882189 /// Check permission to nest token.2190 ///2191 /// * `sender` - The user who initiated the check.2192 /// * `from` - The token that is checked for embedding.2193 /// * `under` - Token under which to check.2194 /// * `budget` - The maximum budget that can be spent on the check.2195 fn check_nesting(2196 &self,2197 sender: &T::CrossAccountId,2198 from: (CollectionId, TokenId),2199 under: TokenId,2200 budget: &dyn Budget,2201 ) -> DispatchResult;22022203 /// Nest one token into another.2204 ///2205 /// * `under` - Token holder.2206 /// * `to_nest` - Nested token.2207 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22082209 /// Unnest token.2210 ///2211 /// * `under` - Token holder.2212 /// * `to_nest` - Token to unnest.2213 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22142215 /// Get all user tokens.2216 ///2217 /// * `account` - Account for which you need to get tokens.2218 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22192220 /// Get all the tokens in the collection.2221 fn collection_tokens(&self) -> Vec<TokenId>;22222223 /// Check if the token exists.2224 ///2225 /// * `token` - Id token to check.2226 fn token_exists(&self, token: TokenId) -> bool;22272228 /// Get the id of the last minted token.2229 fn last_token_id(&self) -> TokenId;22302231 /// Get the owner of the token.2232 ///2233 /// * `token` - The token for which you need to find out the owner.2234 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22352236 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2237 ///2238 /// * `token` - Id token to check.2239 /// * `maybe_owner` - The account to check.2240 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2241 fn check_token_indirect_owner(2242 &self,2243 token: TokenId,2244 maybe_owner: &T::CrossAccountId,2245 nesting_budget: &dyn Budget,2246 ) -> Result<bool, DispatchError>;22472248 /// Returns 10 tokens owners in no particular order.2249 ///2250 /// * `token` - The token for which you need to find out the owners.2251 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22522253 /// Get the value of the token property by key.2254 ///2255 /// * `token` - Token with the property to get.2256 /// * `key` - Property name.2257 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22582259 /// Get a set of token properties by key vector.2260 ///2261 /// * `token` - Token with the property to get.2262 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2263 /// then all properties are returned.2264 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22652266 /// Amount of unique collection tokens2267 fn total_supply(&self) -> u32;22682269 /// Amount of different tokens account has.2270 ///2271 /// * `account` - The account for which need to get the balance.2272 fn account_balance(&self, account: T::CrossAccountId) -> u32;22732274 /// Amount of specific token account have.2275 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22762277 /// Amount of token pieces2278 fn total_pieces(&self, token: TokenId) -> Option<u128>;22792280 /// Get the number of parts of the token that a trusted user can manage.2281 ///2282 /// * `sender` - Trusted user.2283 /// * `spender` - Owner of the token.2284 /// * `token` - The token for which to get the value.2285 fn allowance(2286 &self,2287 sender: T::CrossAccountId,2288 spender: T::CrossAccountId,2289 token: TokenId,2290 ) -> u128;22912292 /// Get extension for RFT collection.2293 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2294 None2295 }22962297 /// Get XCM extensions.2298 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2299 None2300 }23012302 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2303 /// * `owner` - Token owner2304 /// * `operator` - Operator2305 /// * `approve` - Should operator status be granted or revoked?2306 fn set_allowance_for_all(2307 &self,2308 owner: T::CrossAccountId,2309 operator: T::CrossAccountId,2310 approve: bool,2311 ) -> DispatchResultWithPostInfo;23122313 /// Tells whether the given `owner` approves the `operator`.2314 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23152316 /// Repairs a possibly broken item.2317 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2318}23192320/// Extension for RFT collection.2321pub trait RefungibleExtensions<T>2322where2323 T: Config,2324{2325 /// Change the number of parts of the token.2326 ///2327 /// When the value changes down, this function is equivalent to burning parts of the token.2328 ///2329 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2330 /// * `token` - The token for which you want to change the number of parts.2331 /// * `amount` - The new value of the parts of the token.2332 fn repartition(2333 &self,2334 sender: &T::CrossAccountId,2335 token: TokenId,2336 amount: u128,2337 ) -> DispatchResultWithPostInfo;2338}23392340/// XCM extensions for fungible and NFT collections2341pub trait XcmExtensions<T>2342where2343 T: Config,2344{2345 /// Does the token have children?2346 fn token_has_children(&self, _token: TokenId) -> bool {2347 false2348 }23492350 /// Create a collection's item using a transaction.2351 ///2352 /// This function performs additional XCM-related checks before the actual creation.2353 #[transactional]2354 fn create_item(2355 &self,2356 depositor: &T::CrossAccountId,2357 to: T::CrossAccountId,2358 data: CreateItemData,2359 nesting_budget: &dyn Budget,2360 ) -> Result<TokenId, DispatchError> {2361 if T::CrossTokenAddressMapping::is_token_address(&to) {2362 return unsupported!(T);2363 }23642365 self.create_item_internal(depositor, to, data, nesting_budget)2366 }23672368 /// Create a collection's item.2369 fn create_item_internal(2370 &self,2371 depositor: &T::CrossAccountId,2372 to: T::CrossAccountId,2373 data: CreateItemData,2374 nesting_budget: &dyn Budget,2375 ) -> Result<TokenId, DispatchError>;23762377 /// Transfer an item from the `from` account to the `to` account using a transaction.2378 ///2379 /// This function performs additional XCM-related checks before the actual transfer.2380 #[transactional]2381 fn transfer_item(2382 &self,2383 depositor: &T::CrossAccountId,2384 from: &T::CrossAccountId,2385 to: &T::CrossAccountId,2386 token: TokenId,2387 amount: u128,2388 nesting_budget: &dyn Budget,2389 ) -> DispatchResult {2390 if T::CrossTokenAddressMapping::is_token_address(&to) {2391 return unsupported!(T);2392 }23932394 self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2395 }23962397 /// Transfer an item from the `from` account to the `to` account.2398 fn transfer_item_internal(2399 &self,2400 depositor: &T::CrossAccountId,2401 from: &T::CrossAccountId,2402 to: &T::CrossAccountId,2403 token: TokenId,2404 amount: u128,2405 nesting_budget: &dyn Budget,2406 ) -> DispatchResult;24072408 /// Burn a collection's item using a transaction.2409 #[transactional]2410 fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2411 self.burn_item_internal(from, token, amount)2412 }24132414 /// Burn a collection's item.2415 fn burn_item_internal(2416 &self,2417 from: T::CrossAccountId,2418 token: TokenId,2419 amount: u128,2420 ) -> DispatchResult;2421}24222423/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2424///2425/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2426pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2427 let post_info = PostDispatchInfo {2428 actual_weight: Some(weight),2429 pays_fee: Pays::Yes,2430 };2431 match res {2432 Ok(()) => Ok(post_info),2433 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2434 }2435}24362437impl<T: Config> From<PropertiesError> for Error<T> {2438 fn from(error: PropertiesError) -> Self {2439 match error {2440 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2441 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2442 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2443 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2444 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2445 }2446 }2447}24482449/// The type-safe interface for writing properties (setting or deleting) to tokens.2450/// It has two distinct implementations for newly created tokens and existing ones.2451///2452/// This type utilizes the lazy evaluation to avoid repeating the computation2453/// of several performance-heavy or PoV-heavy tasks,2454/// such as checking the indirect ownership or reading the token property permissions.2455pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2456 collection: &'a Handle,2457 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2458 _phantom: PhantomData<(T, WriterVariant)>,2459}24602461impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2462where2463 T: Config,2464 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2465{2466 fn internal_write_token_properties(2467 &mut self,2468 token_id: TokenId,2469 mut token_lazy_info: PropertyWriterLazyTokenInfo,2470 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2471 log: evm_coder::ethereum::Log,2472 ) -> DispatchResult {2473 for (key, value) in properties_updates {2474 let permission = self2475 .collection_lazy_info2476 .property_permissions2477 .value()2478 .get(&key)2479 .cloned()2480 .unwrap_or_else(PropertyPermission::none);24812482 match permission {2483 PropertyPermission { mutable: false, .. }2484 if token_lazy_info2485 .stored_properties2486 .value()2487 .get(&key)2488 .is_some() =>2489 {2490 return Err(<Error<T>>::NoPermission.into());2491 }24922493 PropertyPermission {2494 collection_admin,2495 token_owner,2496 ..2497 } => check_token_permissions::<T>(2498 collection_admin,2499 token_owner,2500 &mut self.collection_lazy_info.is_collection_admin,2501 &mut token_lazy_info.is_token_owner,2502 &mut token_lazy_info.is_token_exist,2503 )?,2504 }25052506 match value {2507 Some(value) => {2508 token_lazy_info2509 .stored_properties2510 .value_mut()2511 .try_set(key.clone(), value)2512 .map_err(<Error<T>>::from)?;25132514 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2515 self.collection.id,2516 token_id,2517 key,2518 ));2519 }2520 None => {2521 token_lazy_info2522 .stored_properties2523 .value_mut()2524 .remove(&key)2525 .map_err(<Error<T>>::from)?;25262527 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2528 self.collection.id,2529 token_id,2530 key,2531 ));2532 }2533 }2534 }25352536 let properties_changed = token_lazy_info.stored_properties.has_value();2537 if properties_changed {2538 <PalletEvm<T>>::deposit_log(log);25392540 self.collection2541 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2542 }25432544 Ok(())2545 }2546}25472548/// A helper structure for the [`PropertyWriter`] that holds2549/// the collection-related info. The info is loaded using lazy evaluation.2550/// This info is common for any token for which we write properties.2551pub struct PropertyWriterLazyCollectionInfo<'a> {2552 is_collection_admin: LazyValue<'a, bool>,2553 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2554}25552556/// A helper structure for the [`PropertyWriter`] that holds2557/// the token-related info. The info is loaded using lazy evaluation.2558pub struct PropertyWriterLazyTokenInfo<'a> {2559 is_token_exist: LazyValue<'a, bool>,2560 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2561 stored_properties: LazyValue<'a, TokenProperties>,2562}25632564impl<'a> PropertyWriterLazyTokenInfo<'a> {2565 /// Create a lazy token info.2566 pub fn new(2567 check_token_exist: impl FnOnce() -> bool + 'a,2568 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2569 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2570 ) -> Self {2571 Self {2572 is_token_exist: LazyValue::new(check_token_exist),2573 is_token_owner: LazyValue::new(check_token_owner),2574 stored_properties: LazyValue::new(get_token_properties),2575 }2576 }2577}25782579/// A marker structure that enables the writer implementation2580/// to provide the interface to write properties to **newly created** tokens.2581pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2582impl<T: Config> NewTokenPropertyWriter<T> {2583 /// Creates a [`PropertyWriter`] for **newly created** tokens.2584 pub fn new<'a, Handle>(2585 collection: &'a Handle,2586 sender: &'a T::CrossAccountId,2587 ) -> PropertyWriter<'a, Self, T, Handle>2588 where2589 T: Config,2590 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2591 {2592 PropertyWriter {2593 collection,2594 collection_lazy_info: PropertyWriterLazyCollectionInfo {2595 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2596 property_permissions: LazyValue::new(|| {2597 <Pallet<T>>::property_permissions(collection.id)2598 }),2599 },2600 _phantom: PhantomData,2601 }2602 }2603}26042605impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2606where2607 T: Config,2608 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2609{2610 /// A function to write properties to a **newly created** token.2611 pub fn write_token_properties(2612 &mut self,2613 mint_target_is_sender: bool,2614 token_id: TokenId,2615 properties_updates: impl Iterator<Item = Property>,2616 log: evm_coder::ethereum::Log,2617 ) -> DispatchResult {2618 let check_token_exist = || {2619 debug_assert!(self.collection.token_exists(token_id));2620 true2621 };26222623 let check_token_owner = || Ok(mint_target_is_sender);26242625 let get_token_properties = || {2626 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2627 TokenProperties::new()2628 };26292630 self.internal_write_token_properties(2631 token_id,2632 PropertyWriterLazyTokenInfo::new(2633 check_token_exist,2634 check_token_owner,2635 get_token_properties,2636 ),2637 properties_updates.map(|p| (p.key, Some(p.value))),2638 log,2639 )2640 }2641}26422643/// A marker structure that enables the writer implementation2644/// to provide the interface to write properties to **already existing** tokens.2645pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2646impl<T: Config> ExistingTokenPropertyWriter<T> {2647 /// Creates a [`PropertyWriter`] for **already existing** tokens.2648 pub fn new<'a, Handle>(2649 collection: &'a Handle,2650 sender: &'a T::CrossAccountId,2651 ) -> PropertyWriter<'a, Self, T, Handle>2652 where2653 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2654 {2655 PropertyWriter {2656 collection,2657 collection_lazy_info: PropertyWriterLazyCollectionInfo {2658 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2659 property_permissions: LazyValue::new(|| {2660 <Pallet<T>>::property_permissions(collection.id)2661 }),2662 },2663 _phantom: PhantomData,2664 }2665 }2666}26672668impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2669where2670 T: Config,2671 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2672{2673 /// A function to write properties to an **already existing** token.2674 pub fn write_token_properties(2675 &mut self,2676 sender: &T::CrossAccountId,2677 token_id: TokenId,2678 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2679 nesting_budget: &dyn Budget,2680 log: evm_coder::ethereum::Log,2681 ) -> DispatchResult {2682 let check_token_exist = || self.collection.token_exists(token_id);2683 let check_token_owner = || {2684 self.collection2685 .check_token_indirect_owner(token_id, sender, nesting_budget)2686 };2687 let get_token_properties = || {2688 self.collection2689 .get_token_properties_raw(token_id)2690 .unwrap_or_default()2691 };26922693 self.internal_write_token_properties(2694 token_id,2695 PropertyWriterLazyTokenInfo::new(2696 check_token_exist,2697 check_token_owner,2698 get_token_properties,2699 ),2700 properties_updates,2701 log,2702 )2703 }2704}27052706/// A marker structure that enables the writer implementation2707/// to benchmark the token properties writing.2708#[cfg(feature = "runtime-benchmarks")]2709pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27102711#[cfg(feature = "runtime-benchmarks")]2712impl<T: Config> BenchmarkPropertyWriter<T> {2713 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2714 pub fn new<'a, Handle>(2715 collection: &'a Handle,2716 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2717 ) -> PropertyWriter<'a, Self, T, Handle>2718 where2719 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2720 {2721 PropertyWriter {2722 collection,2723 collection_lazy_info,2724 _phantom: PhantomData,2725 }2726 }27272728 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2729 pub fn load_collection_info<Handle>(2730 collection_handle: &Handle,2731 sender: &T::CrossAccountId,2732 ) -> PropertyWriterLazyCollectionInfo<'static>2733 where2734 Handle: Deref<Target = CollectionHandle<T>>,2735 {2736 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2737 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27382739 PropertyWriterLazyCollectionInfo {2740 is_collection_admin: LazyValue::new(move || is_collection_admin),2741 property_permissions: LazyValue::new(move || property_permissions),2742 }2743 }27442745 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2746 pub fn load_token_properties<Handle>(2747 collection: &Handle,2748 token_id: TokenId,2749 ) -> PropertyWriterLazyTokenInfo2750 where2751 Handle: CommonCollectionOperations<T>,2752 {2753 let stored_properties = collection2754 .get_token_properties_raw(token_id)2755 .unwrap_or_default();27562757 PropertyWriterLazyTokenInfo {2758 is_token_exist: LazyValue::new(|| true),2759 is_token_owner: LazyValue::new(|| Ok(true)),2760 stored_properties: LazyValue::new(move || stored_properties),2761 }2762 }2763}27642765#[cfg(feature = "runtime-benchmarks")]2766impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2767where2768 T: Config,2769 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2770{2771 /// A function to benchmark the writing of token properties.2772 pub fn write_token_properties(2773 &mut self,2774 token_id: TokenId,2775 properties_updates: impl Iterator<Item = Property>,2776 log: evm_coder::ethereum::Log,2777 ) -> DispatchResult {2778 let check_token_exist = || true;2779 let check_token_owner = || Ok(true);2780 let get_token_properties = TokenProperties::new;27812782 self.internal_write_token_properties(2783 token_id,2784 PropertyWriterLazyTokenInfo::new(2785 check_token_exist,2786 check_token_owner,2787 get_token_properties,2788 ),2789 properties_updates.map(|p| (p.key, Some(p.value))),2790 log,2791 )2792 }2793}27942795/// Computes the weight of writing properties to tokens.2796/// * `properties_nums` - The properties num of each created token.2797/// * `per_token_weight_weight` - The function to obtain the weight2798/// of writing properties from a token's properties num.2799pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2800 properties_nums: impl Iterator<Item = u32>,2801 per_token_weight: I,2802) -> Weight {2803 let mut weight = properties_nums2804 .filter_map(|properties_num| {2805 if properties_num > 0 {2806 Some(per_token_weight(properties_num))2807 } else {2808 None2809 }2810 })2811 .fold(Weight::zero(), |a, b| a.saturating_add(b));28122813 if !weight.is_zero() {2814 // If we are here, it means the token properties were written at least once.2815 // Because of that, some common collection data was also loaded; we must add this weight.2816 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28172818 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2819 }28202821 weight2822}28232824#[cfg(any(feature = "tests", test))]2825#[allow(missing_docs)]2826pub mod tests {2827 use crate::{Config, DispatchError, DispatchResult, LazyValue};28282829 const fn to_bool(u: u8) -> bool {2830 u != 02831 }28322833 #[derive(Debug)]2834 pub struct TestCase {2835 pub collection_admin: bool,2836 pub is_collection_admin: bool,2837 pub token_owner: bool,2838 pub is_token_owner: bool,2839 pub no_permission: bool,2840 }28412842 impl TestCase {2843 const fn new(2844 collection_admin: u8,2845 is_collection_admin: u8,2846 token_owner: u8,2847 is_token_owner: u8,2848 no_permission: u8,2849 ) -> Self {2850 Self {2851 collection_admin: to_bool(collection_admin),2852 is_collection_admin: to_bool(is_collection_admin),2853 token_owner: to_bool(token_owner),2854 is_token_owner: to_bool(is_token_owner),2855 no_permission: to_bool(no_permission),2856 }2857 }2858 }28592860 #[rustfmt::skip]2861 pub const TABLE: [TestCase; 16] = [2862 // ┌╴collection_admin2863 // │ ┌╴is_collection_admin2864 // │ │ ┌╴token_owner2865 // │ │ │ ┌╴is_token_ownership2866 // │ │ │ │ ┌╴no_permission2867 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2868 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2869 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2870 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2871 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2872 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2873 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2874 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2875 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2876 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2877 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2878 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2879 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2880 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2881 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2882 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2883 ];28842885 pub fn check_token_permissions<T: Config>(2886 collection_admin_permitted: bool,2887 token_owner_permitted: bool,2888 is_collection_admin: &mut LazyValue<bool>,2889 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2890 check_token_existence: &mut LazyValue<bool>,2891 ) -> DispatchResult {2892 crate::check_token_permissions::<T>(2893 collection_admin_permitted,2894 token_owner_permitted,2895 is_collection_admin,2896 check_token_ownership,2897 check_token_existence,2898 )2899 }2900}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}946947fn check_token_permissions<T: Config>(948 collection_admin_permitted: bool,949 token_owner_permitted: bool,950 is_collection_admin: &mut LazyValue<bool>,951 is_token_owner: &mut LazyValue<Result<bool, DispatchError>>,952 is_token_exist: &mut LazyValue<bool>,953) -> DispatchResult {954 if !(collection_admin_permitted && *is_collection_admin.value()955 || token_owner_permitted && (*is_token_owner.value())?)956 {957 fail!(<Error<T>>::NoPermission);958 }959960 let token_exist_due_to_owner_check_success =961 is_token_owner.has_value() && (*is_token_owner.value())?;962963 // If the token owner check has occurred and succeeded,964 // we know the token exists (otherwise, the owner check must fail).965 if !token_exist_due_to_owner_check_success {966 // If the token owner check didn't occur,967 // we must check the token's existence ourselves.968 if !is_token_exist.value() {969 fail!(<Error<T>>::TokenNotFound);970 }971 }972973 Ok(())974}975976impl<T: Config> Pallet<T> {977 /// Enshure that receiver address is correct.978 ///979 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.980 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {981 ensure!(982 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,983 <Error<T>>::AddressIsZero984 );985 Ok(())986 }987988 /// Get a vector of collection admins.989 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {990 <IsAdmin<T>>::iter_prefix((collection,))991 .map(|(a, _)| a)992 .collect()993 }994995 /// Get a vector of users allowed to mint tokens.996 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {997 <Allowlist<T>>::iter_prefix((collection,))998 .map(|(a, _)| a)999 .collect()1000 }10011002 /// Is `user` allowed to mint token in `collection`.1003 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {1004 <Allowlist<T>>::get((collection, user))1005 }10061007 /// Get statistics of collections.1008 pub fn collection_stats() -> CollectionStats {1009 let created = <CreatedCollectionCount<T>>::get();1010 let destroyed = <DestroyedCollectionCount<T>>::get();1011 CollectionStats {1012 created: created.0,1013 destroyed: destroyed.0,1014 alive: created.0 - destroyed.0,1015 }1016 }10171018 /// Get the effective limits for the collection.1019 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {1020 let collection = <CollectionById<T>>::get(collection)?;1021 let limits = collection.limits;1022 let effective_limits = CollectionLimits {1023 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),1024 sponsored_data_size: Some(limits.sponsored_data_size()),1025 sponsored_data_rate_limit: Some(1026 limits1027 .sponsored_data_rate_limit1028 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),1029 ),1030 token_limit: Some(limits.token_limit()),1031 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(1032 match collection.mode {1033 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1034 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1035 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1036 },1037 )),1038 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),1039 owner_can_transfer: Some(limits.owner_can_transfer()),1040 owner_can_destroy: Some(limits.owner_can_destroy()),1041 transfers_enabled: Some(limits.transfers_enabled()),1042 };10431044 Some(effective_limits)1045 }10461047 /// Returns information about the `collection` adapted for rpc.1048 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {1049 let Collection {1050 name,1051 description,1052 owner,1053 mode,1054 token_prefix,1055 sponsorship,1056 limits,1057 permissions,1058 flags,1059 } = <CollectionById<T>>::get(collection)?;10601061 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1062 .into_iter()1063 .map(|(key, permission)| PropertyKeyPermission { key, permission })1064 .collect();10651066 let properties = <CollectionProperties<T>>::get(collection)1067 .into_iter()1068 .map(|(key, value)| Property { key, value })1069 .collect();10701071 let permissions = CollectionPermissions {1072 access: Some(permissions.access()),1073 mint_mode: Some(permissions.mint_mode()),1074 nesting: Some(permissions.nesting().clone()),1075 };10761077 Some(RpcCollection {1078 name: name.into_inner(),1079 description: description.into_inner(),1080 owner,1081 mode,1082 token_prefix: token_prefix.into_inner(),1083 sponsorship,1084 limits,1085 permissions,1086 token_property_permissions,1087 properties,1088 read_only: flags.external,10891090 flags: RpcCollectionFlags {1091 foreign: flags.foreign,1092 erc721metadata: flags.erc721metadata,1093 },1094 })1095 }1096}10971098macro_rules! limit_default {1099 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1100 $(1101 if let Some($new) = $new.$field {1102 let $old = $old.$field($($arg)?);1103 let _ = $new;1104 let _ = $old;1105 $check1106 } else {1107 $new.$field = $old.$field1108 }1109 )*1110 }};1111}1112macro_rules! limit_default_clone {1113 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1114 $(1115 if let Some($new) = $new.$field.clone() {1116 let $old = $old.$field($($arg)?);1117 let _ = $new;1118 let _ = $old;1119 $check1120 } else {1121 $new.$field = $old.$field.clone()1122 }1123 )*1124 }};1125}11261127impl<T: Config> Pallet<T> {1128 /// Create new collection.1129 ///1130 /// * `owner` - The owner of the collection.1131 /// * `payer` - If set, the user that will pay a deposit for the collection creation.1132 /// * `data` - Description of the created collection.1133 /// * `is_special_collection` -- Whether this collection is a special one, i.e. can have special flags set.1134 pub fn init_collection(1135 owner: T::CrossAccountId,1136 payer: Option<T::CrossAccountId>,1137 is_special_collection: bool,1138 data: CreateCollectionData<T::CrossAccountId>,1139 ) -> Result<CollectionId, DispatchError> {1140 if !is_special_collection {1141 ensure!(data.flags.is_allowed_for_user(), <Error<T>>::NoPermission);1142 }11431144 // Take a (non-refundable) deposit of collection creation1145 if let Some(payer) = payer {1146 let mut imbalance = <Debt<T::AccountId, <T as Config>::Currency>>::zero();1147 imbalance.subsume(<T as Config>::Currency::deposit(1148 &T::TreasuryAccountId::get(),1149 T::CollectionCreationPrice::get(),1150 Precision::Exact,1151 )?);1152 let credit =1153 <T as Config>::Currency::settle(payer.as_sub(), imbalance, Preservation::Preserve)1154 .map_err(|_| Error::<T>::NotSufficientFounds)?;11551156 debug_assert!(credit.peek().is_zero())1157 }11581159 Self::init_collection_internal(owner, data)1160 }11611162 fn init_collection_internal(1163 owner: T::CrossAccountId,1164 data: CreateCollectionData<T::CrossAccountId>,1165 ) -> Result<CollectionId, DispatchError> {1166 {1167 ensure!(1168 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1169 Error::<T>::CollectionTokenPrefixLimitExceeded1170 );1171 }11721173 let created_count = <CreatedCollectionCount<T>>::get()1174 .01175 .checked_add(1)1176 .ok_or(ArithmeticError::Overflow)?;1177 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1178 let id = CollectionId(created_count);11791180 // bound Total number of collections1181 ensure!(1182 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1183 <Error<T>>::TotalCollectionsLimitExceeded1184 );11851186 // =========11871188 let collection = Collection {1189 owner: owner.as_sub().clone(),1190 name: data.name,1191 mode: data.mode.clone(),1192 description: data.description,1193 token_prefix: data.token_prefix,1194 sponsorship: data1195 .pending_sponsor1196 .map(|sponsor| SponsorshipState::Unconfirmed(sponsor.as_sub().clone()))1197 .unwrap_or_default(),1198 limits: data1199 .limits1200 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1201 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1202 permissions: data1203 .permissions1204 .map(|permissions| {1205 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1206 })1207 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1208 flags: data.flags,1209 };12101211 let mut collection_properties = CollectionPropertiesT::new();1212 collection_properties1213 .try_set_from_iter(data.properties.into_iter())1214 .map_err(<Error<T>>::from)?;12151216 CollectionProperties::<T>::insert(id, collection_properties);12171218 let mut token_props_permissions = PropertiesPermissionMap::new();1219 token_props_permissions1220 .try_set_from_iter(data.token_property_permissions.into_iter())1221 .map_err(<Error<T>>::from)?;12221223 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);12241225 let mut admin_amount = 0u32;1226 for admin in data.admin_list.iter() {1227 if !<IsAdmin<T>>::get((id, admin)) {1228 <IsAdmin<T>>::insert((id, admin), true);1229 admin_amount = admin_amount1230 .checked_add(1)1231 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1232 }1233 }1234 ensure!(1235 admin_amount <= Self::collection_admins_limit(),1236 <Error<T>>::CollectionAdminCountExceeded,1237 );1238 <AdminAmount<T>>::insert(id, admin_amount);12391240 <CreatedCollectionCount<T>>::put(created_count);1241 <Pallet<T>>::deposit_event(Event::CollectionCreated(1242 id,1243 data.mode.id(),1244 owner.as_sub().clone(),1245 ));1246 <PalletEvm<T>>::deposit_log(1247 erc::CollectionHelpersEvents::CollectionCreated {1248 owner: *owner.as_eth(),1249 collection_id: eth::collection_id_to_address(id),1250 }1251 .to_log(T::ContractAddress::get()),1252 );1253 <CollectionById<T>>::insert(id, collection);1254 Ok(id)1255 }12561257 /// Destroy collection.1258 ///1259 /// * `collection` - Collection handler.1260 /// * `sender` - The owner or administrator of the collection.1261 pub fn destroy_collection(1262 collection: CollectionHandle<T>,1263 sender: &T::CrossAccountId,1264 ) -> DispatchResult {1265 ensure!(1266 collection.limits.owner_can_destroy(),1267 <Error<T>>::NoPermission,1268 );1269 collection.check_is_owner(sender)?;12701271 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1272 .01273 .checked_add(1)1274 .ok_or(ArithmeticError::Overflow)?;12751276 // =========12771278 <DestroyedCollectionCount<T>>::put(destroyed_collections);1279 <CollectionById<T>>::remove(collection.id);1280 <AdminAmount<T>>::remove(collection.id);1281 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1282 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1283 <CollectionProperties<T>>::remove(collection.id);12841285 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12861287 <PalletEvm<T>>::deposit_log(1288 erc::CollectionHelpersEvents::CollectionDestroyed {1289 collection_id: eth::collection_id_to_address(collection.id),1290 }1291 .to_log(T::ContractAddress::get()),1292 );1293 Ok(())1294 }12951296 /// This function sets or removes a collection properties according to1297 /// `properties_updates` contents:1298 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1299 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1300 ///1301 /// This function fires an event for each property change.1302 /// In case of an error, all the changes (including the events) will be reverted1303 /// since the function is transactional.1304 #[transactional]1305 fn modify_collection_properties(1306 collection: &CollectionHandle<T>,1307 sender: &T::CrossAccountId,1308 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1309 ) -> DispatchResult {1310 collection.check_is_owner_or_admin(sender)?;13111312 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);13131314 for (key, value) in properties_updates {1315 match value {1316 Some(value) => {1317 stored_properties1318 .try_set(key.clone(), value)1319 .map_err(<Error<T>>::from)?;13201321 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1322 <PalletEvm<T>>::deposit_log(1323 erc::CollectionHelpersEvents::CollectionChanged {1324 collection_id: eth::collection_id_to_address(collection.id),1325 }1326 .to_log(T::ContractAddress::get()),1327 );1328 }1329 None => {1330 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13311332 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1333 <PalletEvm<T>>::deposit_log(1334 erc::CollectionHelpersEvents::CollectionChanged {1335 collection_id: eth::collection_id_to_address(collection.id),1336 }1337 .to_log(T::ContractAddress::get()),1338 );1339 }1340 }1341 }13421343 <CollectionProperties<T>>::set(collection.id, stored_properties);13441345 Ok(())1346 }13471348 /// Sets or unsets the approval of a given operator.1349 ///1350 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1351 /// - `owner`: Token owner1352 /// - `operator`: Operator1353 /// - `approve`: Should operator status be granted or revoked?1354 pub fn set_allowance_for_all(1355 collection: &CollectionHandle<T>,1356 owner: &T::CrossAccountId,1357 operator: &T::CrossAccountId,1358 approve: bool,1359 set_allowance: impl FnOnce(),1360 log: evm_coder::ethereum::Log,1361 ) -> DispatchResult {1362 if collection.permissions.access() == AccessMode::AllowList {1363 collection.check_allowlist(owner)?;1364 collection.check_allowlist(operator)?;1365 }13661367 Self::ensure_correct_receiver(operator)?;13681369 set_allowance();13701371 <PalletEvm<T>>::deposit_log(log);1372 Self::deposit_event(Event::ApprovedForAll(1373 collection.id,1374 owner.clone(),1375 operator.clone(),1376 approve,1377 ));1378 Ok(())1379 }13801381 /// Set collection property.1382 ///1383 /// * `collection` - Collection handler.1384 /// * `sender` - The owner or administrator of the collection.1385 /// * `property` - The property to set.1386 pub fn set_collection_property(1387 collection: &CollectionHandle<T>,1388 sender: &T::CrossAccountId,1389 property: Property,1390 ) -> DispatchResult {1391 Self::set_collection_properties(collection, sender, [property].into_iter())1392 }13931394 /// Set a scoped collection property, where the scope is a special prefix1395 /// prohibiting a user access to change the property directly.1396 ///1397 /// * `collection_id` - ID of the collection for which the property is being set.1398 /// * `scope` - Property scope.1399 /// * `property` - The property to set.1400 pub fn set_scoped_collection_property(1401 collection_id: CollectionId,1402 scope: PropertyScope,1403 property: Property,1404 ) -> DispatchResult {1405 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1406 properties.try_scoped_set(scope, property.key, property.value)1407 })1408 .map_err(<Error<T>>::from)?;14091410 Ok(())1411 }14121413 /// Set scoped collection properties, where the scope is a special prefix1414 /// prohibiting a user access to change the properties directly.1415 ///1416 /// * `collection_id` - ID of the collection for which the properties is being set.1417 /// * `scope` - Property scope.1418 /// * `properties` - The properties to set.1419 pub fn set_scoped_collection_properties(1420 collection_id: CollectionId,1421 scope: PropertyScope,1422 properties: impl Iterator<Item = Property>,1423 ) -> DispatchResult {1424 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1425 stored_properties.try_scoped_set_from_iter(scope, properties)1426 })1427 .map_err(<Error<T>>::from)?;14281429 Ok(())1430 }14311432 /// Set collection properties.1433 ///1434 /// * `collection` - Collection handler.1435 /// * `sender` - The owner or administrator of the collection.1436 /// * `properties` - The properties to set.1437 pub fn set_collection_properties(1438 collection: &CollectionHandle<T>,1439 sender: &T::CrossAccountId,1440 properties: impl Iterator<Item = Property>,1441 ) -> DispatchResult {1442 Self::modify_collection_properties(1443 collection,1444 sender,1445 properties.map(|property| (property.key, Some(property.value))),1446 )1447 }14481449 /// Delete collection property.1450 ///1451 /// * `collection` - Collection handler.1452 /// * `sender` - The owner or administrator of the collection.1453 /// * `property` - The property to delete.1454 pub fn delete_collection_property(1455 collection: &CollectionHandle<T>,1456 sender: &T::CrossAccountId,1457 property_key: PropertyKey,1458 ) -> DispatchResult {1459 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1460 }14611462 /// Delete collection properties.1463 ///1464 /// * `collection` - Collection handler.1465 /// * `sender` - The owner or administrator of the collection.1466 /// * `properties` - The properties to delete.1467 pub fn delete_collection_properties(1468 collection: &CollectionHandle<T>,1469 sender: &T::CrossAccountId,1470 property_keys: impl Iterator<Item = PropertyKey>,1471 ) -> DispatchResult {1472 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1473 }14741475 /// Set collection propetry permission without any checks.1476 ///1477 /// Used for migrations.1478 ///1479 /// * `collection` - Collection handler.1480 /// * `property_permissions` - Property permissions.1481 pub fn set_property_permission_unchecked(1482 collection: CollectionId,1483 property_permission: PropertyKeyPermission,1484 ) -> DispatchResult {1485 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1486 permissions.try_set(property_permission.key, property_permission.permission)1487 })1488 .map_err(<Error<T>>::from)?;1489 Ok(())1490 }14911492 /// Set collection property permission.1493 ///1494 /// * `collection` - Collection handler.1495 /// * `sender` - The owner or administrator of the collection.1496 /// * `property_permission` - Property permission.1497 pub fn set_property_permission(1498 collection: &CollectionHandle<T>,1499 sender: &T::CrossAccountId,1500 property_permission: PropertyKeyPermission,1501 ) -> DispatchResult {1502 Self::set_scoped_property_permission(1503 collection,1504 sender,1505 PropertyScope::None,1506 property_permission,1507 )1508 }15091510 /// Set collection property permission with scope.1511 ///1512 /// * `collection` - Collection handler.1513 /// * `sender` - The owner or administrator of the collection.1514 /// * `scope` - Property scope.1515 /// * `property_permission` - Property permission.1516 pub fn set_scoped_property_permission(1517 collection: &CollectionHandle<T>,1518 sender: &T::CrossAccountId,1519 scope: PropertyScope,1520 property_permission: PropertyKeyPermission,1521 ) -> DispatchResult {1522 collection.check_is_owner_or_admin(sender)?;15231524 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1525 let current_permission = all_permissions.get(&property_permission.key);1526 if matches![1527 current_permission,1528 Some(PropertyPermission { mutable: false, .. })1529 ] {1530 return Err(<Error<T>>::NoPermission.into());1531 }15321533 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1534 let property_permission = property_permission.clone();1535 permissions.try_scoped_set(1536 scope,1537 property_permission.key,1538 property_permission.permission,1539 )1540 })1541 .map_err(<Error<T>>::from)?;15421543 Self::deposit_event(Event::PropertyPermissionSet(1544 collection.id,1545 property_permission.key,1546 ));1547 <PalletEvm<T>>::deposit_log(1548 erc::CollectionHelpersEvents::CollectionChanged {1549 collection_id: eth::collection_id_to_address(collection.id),1550 }1551 .to_log(T::ContractAddress::get()),1552 );15531554 Ok(())1555 }15561557 /// Set token property permission.1558 ///1559 /// * `collection` - Collection handler.1560 /// * `sender` - The owner or administrator of the collection.1561 /// * `property_permissions` - Property permissions.1562 #[transactional]1563 pub fn set_token_property_permissions(1564 collection: &CollectionHandle<T>,1565 sender: &T::CrossAccountId,1566 property_permissions: Vec<PropertyKeyPermission>,1567 ) -> DispatchResult {1568 Self::set_scoped_token_property_permissions(1569 collection,1570 sender,1571 PropertyScope::None,1572 property_permissions,1573 )1574 }15751576 /// Set token property permission with scope.1577 ///1578 /// * `collection` - Collection handler.1579 /// * `sender` - The owner or administrator of the collection.1580 /// * `scope` - Property scope.1581 /// * `property_permissions` - Property permissions.1582 #[transactional]1583 pub fn set_scoped_token_property_permissions(1584 collection: &CollectionHandle<T>,1585 sender: &T::CrossAccountId,1586 scope: PropertyScope,1587 property_permissions: Vec<PropertyKeyPermission>,1588 ) -> DispatchResult {1589 for prop_pemission in property_permissions {1590 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1591 }15921593 Ok(())1594 }15951596 /// Get collection property.1597 pub fn get_collection_property(1598 collection_id: CollectionId,1599 key: &PropertyKey,1600 ) -> Option<PropertyValue> {1601 Self::collection_properties(collection_id).get(key).cloned()1602 }16031604 /// Convert byte vector to property key vector.1605 pub fn bytes_keys_to_property_keys(1606 keys: Vec<Vec<u8>>,1607 ) -> Result<Vec<PropertyKey>, DispatchError> {1608 keys.into_iter()1609 .map(|key| -> Result<PropertyKey, DispatchError> {1610 key.try_into()1611 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1612 })1613 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1614 }16151616 /// Get properties according to given keys.1617 pub fn filter_collection_properties(1618 collection_id: CollectionId,1619 keys: Option<Vec<PropertyKey>>,1620 ) -> Result<Vec<Property>, DispatchError> {1621 let properties = Self::collection_properties(collection_id);16221623 let properties = keys1624 .map(|keys| {1625 keys.into_iter()1626 .filter_map(|key| {1627 properties.get(&key).map(|value| Property {1628 key,1629 value: value.clone(),1630 })1631 })1632 .collect()1633 })1634 .unwrap_or_else(|| {1635 properties1636 .into_iter()1637 .map(|(key, value)| Property { key, value })1638 .collect()1639 });16401641 Ok(properties)1642 }16431644 /// Get property permissions according to given keys.1645 pub fn filter_property_permissions(1646 collection_id: CollectionId,1647 keys: Option<Vec<PropertyKey>>,1648 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1649 let permissions = Self::property_permissions(collection_id);16501651 let key_permissions = keys1652 .map(|keys| {1653 keys.into_iter()1654 .filter_map(|key| {1655 permissions1656 .get(&key)1657 .map(|permission| PropertyKeyPermission {1658 key,1659 permission: permission.clone(),1660 })1661 })1662 .collect()1663 })1664 .unwrap_or_else(|| {1665 permissions1666 .into_iter()1667 .map(|(key, permission)| PropertyKeyPermission { key, permission })1668 .collect()1669 });16701671 Ok(key_permissions)1672 }16731674 /// Toggle `user` participation in the `collection`'s allow list.1675 /// #### Store read/writes1676 /// 1 writes1677 pub fn toggle_allowlist(1678 collection: &CollectionHandle<T>,1679 sender: &T::CrossAccountId,1680 user: &T::CrossAccountId,1681 allowed: bool,1682 ) -> DispatchResult {1683 collection.check_is_owner_or_admin(sender)?;16841685 // =========16861687 if allowed {1688 <Allowlist<T>>::insert((collection.id, user), true);1689 Self::deposit_event(Event::<T>::AllowListAddressAdded(1690 collection.id,1691 user.clone(),1692 ));1693 } else {1694 <Allowlist<T>>::remove((collection.id, user));1695 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1696 collection.id,1697 user.clone(),1698 ));1699 }17001701 <PalletEvm<T>>::deposit_log(1702 erc::CollectionHelpersEvents::CollectionChanged {1703 collection_id: eth::collection_id_to_address(collection.id),1704 }1705 .to_log(T::ContractAddress::get()),1706 );17071708 Ok(())1709 }17101711 /// Toggle `user` participation in the `collection`'s admin list.1712 /// #### Store read/writes1713 /// 2 reads, 2 writes1714 pub fn toggle_admin(1715 collection: &CollectionHandle<T>,1716 sender: &T::CrossAccountId,1717 user: &T::CrossAccountId,1718 admin: bool,1719 ) -> DispatchResult {1720 collection.check_is_internal()?;1721 collection.check_is_owner(sender)?;17221723 let is_admin = <IsAdmin<T>>::get((collection.id, user));1724 if is_admin == admin {1725 if admin {1726 return Ok(());1727 } else {1728 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1729 }1730 }1731 let amount = <AdminAmount<T>>::get(collection.id);17321733 // =========17341735 if admin {1736 let amount = amount1737 .checked_add(1)1738 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1739 ensure!(1740 amount <= Self::collection_admins_limit(),1741 <Error<T>>::CollectionAdminCountExceeded,1742 );17431744 <AdminAmount<T>>::insert(collection.id, amount);1745 <IsAdmin<T>>::insert((collection.id, user), true);17461747 Self::deposit_event(Event::<T>::CollectionAdminAdded(1748 collection.id,1749 user.clone(),1750 ));1751 } else {1752 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1753 <IsAdmin<T>>::remove((collection.id, user));17541755 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1756 collection.id,1757 user.clone(),1758 ));1759 }17601761 <PalletEvm<T>>::deposit_log(1762 erc::CollectionHelpersEvents::CollectionChanged {1763 collection_id: eth::collection_id_to_address(collection.id),1764 }1765 .to_log(T::ContractAddress::get()),1766 );17671768 Ok(())1769 }17701771 /// Update collection limits.1772 pub fn update_limits(1773 user: &T::CrossAccountId,1774 collection: &mut CollectionHandle<T>,1775 new_limit: CollectionLimits,1776 ) -> DispatchResult {1777 collection.check_is_internal()?;1778 collection.check_is_owner_or_admin(user)?;17791780 collection.limits =1781 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17821783 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1784 <PalletEvm<T>>::deposit_log(1785 erc::CollectionHelpersEvents::CollectionChanged {1786 collection_id: eth::collection_id_to_address(collection.id),1787 }1788 .to_log(T::ContractAddress::get()),1789 );17901791 collection.save()1792 }17931794 /// Merge set fields from `new_limit` to `old_limit`.1795 fn clamp_limits(1796 mode: CollectionMode,1797 old_limit: &CollectionLimits,1798 mut new_limit: CollectionLimits,1799 ) -> Result<CollectionLimits, DispatchError> {1800 let limits = old_limit;1801 limit_default!(old_limit, new_limit,1802 account_token_ownership_limit => ensure!(1803 new_limit <= MAX_TOKEN_OWNERSHIP,1804 <Error<T>>::CollectionLimitBoundsExceeded,1805 ),1806 sponsored_data_size => ensure!(1807 new_limit <= CUSTOM_DATA_LIMIT,1808 <Error<T>>::CollectionLimitBoundsExceeded,1809 ),18101811 sponsored_data_rate_limit => {},1812 token_limit => ensure!(1813 old_limit >= new_limit && new_limit > 0,1814 <Error<T>>::CollectionTokenLimitExceeded1815 ),18161817 sponsor_transfer_timeout(match mode {1818 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1819 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1820 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1821 }) => ensure!(1822 new_limit <= MAX_SPONSOR_TIMEOUT,1823 <Error<T>>::CollectionLimitBoundsExceeded,1824 ),1825 sponsor_approve_timeout => {},1826 owner_can_transfer => ensure!(1827 !limits.owner_can_transfer_instaled() ||1828 old_limit || !new_limit,1829 <Error<T>>::OwnerPermissionsCantBeReverted,1830 ),1831 owner_can_destroy => ensure!(1832 old_limit || !new_limit,1833 <Error<T>>::OwnerPermissionsCantBeReverted,1834 ),1835 transfers_enabled => {},1836 );1837 Ok(new_limit)1838 }18391840 /// Update collection permissions.1841 pub fn update_permissions(1842 user: &T::CrossAccountId,1843 collection: &mut CollectionHandle<T>,1844 new_permission: CollectionPermissions,1845 ) -> DispatchResult {1846 collection.check_is_internal()?;1847 collection.check_is_owner_or_admin(user)?;1848 collection.permissions = Self::clamp_permissions(1849 collection.mode.clone(),1850 &collection.permissions,1851 new_permission,1852 )?;18531854 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1855 <PalletEvm<T>>::deposit_log(1856 erc::CollectionHelpersEvents::CollectionChanged {1857 collection_id: eth::collection_id_to_address(collection.id),1858 }1859 .to_log(T::ContractAddress::get()),1860 );18611862 collection.save()1863 }18641865 /// Merge set fields from `new_permission` to `old_permission`.1866 fn clamp_permissions(1867 _mode: CollectionMode,1868 old_permission: &CollectionPermissions,1869 mut new_permission: CollectionPermissions,1870 ) -> Result<CollectionPermissions, DispatchError> {1871 limit_default_clone!(old_permission, new_permission,1872 access => {},1873 mint_mode => {},1874 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1875 );1876 Ok(new_permission)1877 }18781879 /// Repair possibly broken properties of a collection.1880 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1881 CollectionProperties::<T>::mutate(collection_id, |properties| {1882 properties.recompute_consumed_space();1883 });18841885 Ok(())1886 }1887}18881889/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1890#[macro_export]1891macro_rules! unsupported {1892 ($runtime:path) => {1893 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1894 };1895}18961897/// Return weights for various worst-case operations.1898pub trait CommonWeightInfo<CrossAccountId> {1899 /// Weight of item creation.1900 fn create_item(data: &CreateItemData) -> Weight {1901 Self::create_multiple_items(from_ref(data))1902 }19031904 /// Weight of items creation.1905 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19061907 /// Weight of items creation.1908 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19091910 /// The weight of the burning item.1911 fn burn_item() -> Weight;19121913 /// Property setting weight.1914 ///1915 /// * `amount`- The number of properties to set.1916 fn set_collection_properties(amount: u32) -> Weight;19171918 /// Collection property deletion weight.1919 ///1920 /// * `amount`- The number of properties to set.1921 fn delete_collection_properties(amount: u32) -> Weight {1922 Self::set_collection_properties(amount)1923 }19241925 /// Token property setting weight.1926 ///1927 /// * `amount`- The number of properties to set.1928 fn set_token_properties(amount: u32) -> Weight;19291930 /// Token property deletion weight.1931 ///1932 /// * `amount`- The number of properties to delete.1933 fn delete_token_properties(amount: u32) -> Weight {1934 Self::set_token_properties(amount)1935 }19361937 /// Token property permissions set weight.1938 ///1939 /// * `amount`- The number of property permissions to set.1940 fn set_token_property_permissions(amount: u32) -> Weight;19411942 /// Transfer price of the token or its parts.1943 fn transfer() -> Weight;19441945 /// The price of setting the permission of the operation from another user.1946 fn approve() -> Weight;19471948 /// The price of setting the permission of the operation from another user for eth mirror.1949 fn approve_from() -> Weight;19501951 /// Transfer price from another user.1952 fn transfer_from() -> Weight;19531954 /// The price of burning a token from another user.1955 fn burn_from() -> Weight;19561957 /// The price of setting approval for all1958 fn set_allowance_for_all() -> Weight;19591960 /// The price of repairing an item.1961 fn force_repair_item() -> Weight;1962}19631964/// Weight info extension trait for refungible pallet.1965pub trait RefungibleExtensionsWeightInfo {1966 /// Weight of token repartition.1967 fn repartition() -> Weight;1968}19691970/// Common collection operations.1971///1972/// It wraps methods in Fungible, Nonfungible and Refungible pallets1973/// and adds weight info.1974pub trait CommonCollectionOperations<T: Config> {1975 /// Create token.1976 ///1977 /// * `sender` - The user who mint the token and pays for the transaction.1978 /// * `to` - The user who will own the token.1979 /// * `data` - Token data.1980 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1981 fn create_item(1982 &self,1983 sender: T::CrossAccountId,1984 to: T::CrossAccountId,1985 data: CreateItemData,1986 nesting_budget: &dyn Budget,1987 ) -> DispatchResultWithPostInfo;19881989 /// Create multiple tokens.1990 ///1991 /// * `sender` - The user who mint the token and pays for the transaction.1992 /// * `to` - The user who will own the token.1993 /// * `data` - Token data.1994 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1995 fn create_multiple_items(1996 &self,1997 sender: T::CrossAccountId,1998 to: T::CrossAccountId,1999 data: Vec<CreateItemData>,2000 nesting_budget: &dyn Budget,2001 ) -> DispatchResultWithPostInfo;20022003 /// Create multiple tokens.2004 ///2005 /// * `sender` - The user who mint the token and pays for the transaction.2006 /// * `to` - The user who will own the token.2007 /// * `data` - Token data.2008 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2009 fn create_multiple_items_ex(2010 &self,2011 sender: T::CrossAccountId,2012 data: CreateItemExData<T::CrossAccountId>,2013 nesting_budget: &dyn Budget,2014 ) -> DispatchResultWithPostInfo;20152016 /// Burn token.2017 ///2018 /// * `sender` - The user who owns the token.2019 /// * `token` - Token id that will burned.2020 /// * `amount` - The number of parts of the token that will be burned.2021 fn burn_item(2022 &self,2023 sender: T::CrossAccountId,2024 token: TokenId,2025 amount: u128,2026 ) -> DispatchResultWithPostInfo;20272028 /// Set collection properties.2029 ///2030 /// * `sender` - Must be either the owner of the collection or its admin.2031 /// * `properties` - Properties to be set.2032 fn set_collection_properties(2033 &self,2034 sender: T::CrossAccountId,2035 properties: Vec<Property>,2036 ) -> DispatchResultWithPostInfo;20372038 /// Delete collection properties.2039 ///2040 /// * `sender` - Must be either the owner of the collection or its admin.2041 /// * `properties` - The properties to be removed.2042 fn delete_collection_properties(2043 &self,2044 sender: &T::CrossAccountId,2045 property_keys: Vec<PropertyKey>,2046 ) -> DispatchResultWithPostInfo;20472048 /// Set token properties.2049 ///2050 /// The appropriate [`PropertyPermission`] for the token property2051 /// must be set with [`Self::set_token_property_permissions`].2052 ///2053 /// * `sender` - Must be either the owner of the token or its admin.2054 /// * `token_id` - The token for which the properties are being set.2055 /// * `properties` - Properties to be set.2056 /// * `budget` - Budget for setting properties.2057 fn set_token_properties(2058 &self,2059 sender: T::CrossAccountId,2060 token_id: TokenId,2061 properties: Vec<Property>,2062 budget: &dyn Budget,2063 ) -> DispatchResultWithPostInfo;20642065 /// Remove token properties.2066 ///2067 /// The appropriate [`PropertyPermission`] for the token property2068 /// must be set with [`Self::set_token_property_permissions`].2069 ///2070 /// * `sender` - Must be either the owner of the token or its admin.2071 /// * `token_id` - The token for which the properties are being remove.2072 /// * `property_keys` - Keys to remove corresponding properties.2073 /// * `budget` - Budget for removing properties.2074 fn delete_token_properties(2075 &self,2076 sender: T::CrossAccountId,2077 token_id: TokenId,2078 property_keys: Vec<PropertyKey>,2079 budget: &dyn Budget,2080 ) -> DispatchResultWithPostInfo;20812082 /// Get token properties raw map.2083 ///2084 /// * `token_id` - The token which properties are needed.2085 fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;20862087 /// Set token properties raw map.2088 ///2089 /// * `token_id` - The token for which the properties are being set.2090 /// * `map` - The raw map containing the token's properties.2091 fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);20922093 /// Set token property permissions.2094 ///2095 /// * `sender` - Must be either the owner of the token or its admin.2096 /// * `token_id` - The token for which the properties are being set.2097 /// * `property_permissions` - Property permissions to be set.2098 /// * `budget` - Budget for setting properties.2099 fn set_token_property_permissions(2100 &self,2101 sender: &T::CrossAccountId,2102 property_permissions: Vec<PropertyKeyPermission>,2103 ) -> DispatchResultWithPostInfo;21042105 /// Transfer amount of token pieces.2106 ///2107 /// * `sender` - Donor user.2108 /// * `to` - Recepient user.2109 /// * `token` - The token of which parts are being sent.2110 /// * `amount` - The number of parts of the token that will be transferred.2111 /// * `budget` - The maximum budget that can be spent on the transfer.2112 fn transfer(2113 &self,2114 sender: T::CrossAccountId,2115 to: T::CrossAccountId,2116 token: TokenId,2117 amount: u128,2118 budget: &dyn Budget,2119 ) -> DispatchResultWithPostInfo;21202121 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2122 ///2123 /// * `sender` - The user who grants access to the token.2124 /// * `spender` - The user to whom the rights are granted.2125 /// * `token` - The token to which access is granted.2126 /// * `amount` - The amount of pieces that another user can dispose of.2127 fn approve(2128 &self,2129 sender: T::CrossAccountId,2130 spender: T::CrossAccountId,2131 token: TokenId,2132 amount: u128,2133 ) -> DispatchResultWithPostInfo;21342135 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2136 ///2137 /// * `sender` - The user who grants access to the token.2138 /// * `from` - Spender's eth mirror.2139 /// * `to` - The user to whom the rights are granted.2140 /// * `token` - The token to which access is granted.2141 /// * `amount` - The amount of pieces that another user can dispose of.2142 fn approve_from(2143 &self,2144 sender: T::CrossAccountId,2145 from: T::CrossAccountId,2146 to: T::CrossAccountId,2147 token: TokenId,2148 amount: u128,2149 ) -> DispatchResultWithPostInfo;21502151 /// Send parts of a token owned by another user.2152 ///2153 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2154 ///2155 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2156 /// * `from` - The user who owns the token.2157 /// * `to` - Recepient user.2158 /// * `token` - The token of which parts are being sent.2159 /// * `amount` - The number of parts of the token that will be transferred.2160 /// * `budget` - The maximum budget that can be spent on the transfer.2161 fn transfer_from(2162 &self,2163 sender: T::CrossAccountId,2164 from: T::CrossAccountId,2165 to: T::CrossAccountId,2166 token: TokenId,2167 amount: u128,2168 budget: &dyn Budget,2169 ) -> DispatchResultWithPostInfo;21702171 /// Burn parts of a token owned by another user.2172 ///2173 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2174 ///2175 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2176 /// * `from` - The user who owns the token.2177 /// * `token` - The token of which parts are being sent.2178 /// * `amount` - The number of parts of the token that will be transferred.2179 /// * `budget` - The maximum budget that can be spent on the burn.2180 fn burn_from(2181 &self,2182 sender: T::CrossAccountId,2183 from: T::CrossAccountId,2184 token: TokenId,2185 amount: u128,2186 budget: &dyn Budget,2187 ) -> DispatchResultWithPostInfo;21882189 /// Check permission to nest token.2190 ///2191 /// * `sender` - The user who initiated the check.2192 /// * `from` - The token that is checked for embedding.2193 /// * `under` - Token under which to check.2194 /// * `budget` - The maximum budget that can be spent on the check.2195 fn check_nesting(2196 &self,2197 sender: &T::CrossAccountId,2198 from: (CollectionId, TokenId),2199 under: TokenId,2200 budget: &dyn Budget,2201 ) -> DispatchResult;22022203 /// Nest one token into another.2204 ///2205 /// * `under` - Token holder.2206 /// * `to_nest` - Nested token.2207 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22082209 /// Unnest token.2210 ///2211 /// * `under` - Token holder.2212 /// * `to_nest` - Token to unnest.2213 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22142215 /// Get all user tokens.2216 ///2217 /// * `account` - Account for which you need to get tokens.2218 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22192220 /// Get all the tokens in the collection.2221 fn collection_tokens(&self) -> Vec<TokenId>;22222223 /// Check if the token exists.2224 ///2225 /// * `token` - Id token to check.2226 fn token_exists(&self, token: TokenId) -> bool;22272228 /// Get the id of the last minted token.2229 fn last_token_id(&self) -> TokenId;22302231 /// Get the owner of the token.2232 ///2233 /// * `token` - The token for which you need to find out the owner.2234 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22352236 /// Checks if the `maybe_owner` is the indirect owner of the `token`.2237 ///2238 /// * `token` - Id token to check.2239 /// * `maybe_owner` - The account to check.2240 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2241 fn check_token_indirect_owner(2242 &self,2243 token: TokenId,2244 maybe_owner: &T::CrossAccountId,2245 nesting_budget: &dyn Budget,2246 ) -> Result<bool, DispatchError>;22472248 /// Returns 10 tokens owners in no particular order.2249 ///2250 /// * `token` - The token for which you need to find out the owners.2251 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22522253 /// Get the value of the token property by key.2254 ///2255 /// * `token` - Token with the property to get.2256 /// * `key` - Property name.2257 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22582259 /// Get a set of token properties by key vector.2260 ///2261 /// * `token` - Token with the property to get.2262 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2263 /// then all properties are returned.2264 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22652266 /// Amount of unique collection tokens2267 fn total_supply(&self) -> u32;22682269 /// Amount of different tokens account has.2270 ///2271 /// * `account` - The account for which need to get the balance.2272 fn account_balance(&self, account: T::CrossAccountId) -> u32;22732274 /// Amount of specific token account have.2275 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22762277 /// Amount of token pieces2278 fn total_pieces(&self, token: TokenId) -> Option<u128>;22792280 /// Get the number of parts of the token that a trusted user can manage.2281 ///2282 /// * `sender` - Trusted user.2283 /// * `spender` - Owner of the token.2284 /// * `token` - The token for which to get the value.2285 fn allowance(2286 &self,2287 sender: T::CrossAccountId,2288 spender: T::CrossAccountId,2289 token: TokenId,2290 ) -> u128;22912292 /// Get extension for RFT collection.2293 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>> {2294 None2295 }22962297 /// Get XCM extensions.2298 fn xcm_extensions(&self) -> Option<&dyn XcmExtensions<T>> {2299 None2300 }23012302 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2303 /// * `owner` - Token owner2304 /// * `operator` - Operator2305 /// * `approve` - Should operator status be granted or revoked?2306 fn set_allowance_for_all(2307 &self,2308 owner: T::CrossAccountId,2309 operator: T::CrossAccountId,2310 approve: bool,2311 ) -> DispatchResultWithPostInfo;23122313 /// Tells whether the given `owner` approves the `operator`.2314 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23152316 /// Repairs a possibly broken item.2317 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2318}23192320/// Extension for RFT collection.2321pub trait RefungibleExtensions<T>2322where2323 T: Config,2324{2325 /// Change the number of parts of the token.2326 ///2327 /// When the value changes down, this function is equivalent to burning parts of the token.2328 ///2329 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2330 /// * `token` - The token for which you want to change the number of parts.2331 /// * `amount` - The new value of the parts of the token.2332 fn repartition(2333 &self,2334 sender: &T::CrossAccountId,2335 token: TokenId,2336 amount: u128,2337 ) -> DispatchResultWithPostInfo;2338}23392340/// XCM extensions for fungible and NFT collections2341pub trait XcmExtensions<T>2342where2343 T: Config,2344{2345 /// Does the token have children?2346 fn token_has_children(&self, _token: TokenId) -> bool {2347 false2348 }23492350 /// Create a collection's item using a transaction.2351 ///2352 /// This function performs additional XCM-related checks before the actual creation.2353 #[transactional]2354 fn create_item(2355 &self,2356 depositor: &T::CrossAccountId,2357 to: T::CrossAccountId,2358 data: CreateItemData,2359 nesting_budget: &dyn Budget,2360 ) -> Result<TokenId, DispatchError> {2361 if T::CrossTokenAddressMapping::is_token_address(&to) {2362 return unsupported!(T);2363 }23642365 self.create_item_internal(depositor, to, data, nesting_budget)2366 }23672368 /// Create a collection's item.2369 fn create_item_internal(2370 &self,2371 depositor: &T::CrossAccountId,2372 to: T::CrossAccountId,2373 data: CreateItemData,2374 nesting_budget: &dyn Budget,2375 ) -> Result<TokenId, DispatchError>;23762377 /// Transfer an item from the `from` account to the `to` account using a transaction.2378 ///2379 /// This function performs additional XCM-related checks before the actual transfer.2380 #[transactional]2381 fn transfer_item(2382 &self,2383 depositor: &T::CrossAccountId,2384 from: &T::CrossAccountId,2385 to: &T::CrossAccountId,2386 token: TokenId,2387 amount: u128,2388 nesting_budget: &dyn Budget,2389 ) -> DispatchResult {2390 if T::CrossTokenAddressMapping::is_token_address(to) {2391 return unsupported!(T);2392 }23932394 self.transfer_item_internal(depositor, from, to, token, amount, nesting_budget)2395 }23962397 /// Transfer an item from the `from` account to the `to` account.2398 fn transfer_item_internal(2399 &self,2400 depositor: &T::CrossAccountId,2401 from: &T::CrossAccountId,2402 to: &T::CrossAccountId,2403 token: TokenId,2404 amount: u128,2405 nesting_budget: &dyn Budget,2406 ) -> DispatchResult;24072408 /// Burn a collection's item using a transaction.2409 #[transactional]2410 fn burn_item(&self, from: T::CrossAccountId, token: TokenId, amount: u128) -> DispatchResult {2411 self.burn_item_internal(from, token, amount)2412 }24132414 /// Burn a collection's item.2415 fn burn_item_internal(2416 &self,2417 from: T::CrossAccountId,2418 token: TokenId,2419 amount: u128,2420 ) -> DispatchResult;2421}24222423/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2424///2425/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2426pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2427 let post_info = PostDispatchInfo {2428 actual_weight: Some(weight),2429 pays_fee: Pays::Yes,2430 };2431 match res {2432 Ok(()) => Ok(post_info),2433 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2434 }2435}24362437impl<T: Config> From<PropertiesError> for Error<T> {2438 fn from(error: PropertiesError) -> Self {2439 match error {2440 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2441 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2442 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2443 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2444 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2445 }2446 }2447}24482449/// The type-safe interface for writing properties (setting or deleting) to tokens.2450/// It has two distinct implementations for newly created tokens and existing ones.2451///2452/// This type utilizes the lazy evaluation to avoid repeating the computation2453/// of several performance-heavy or PoV-heavy tasks,2454/// such as checking the indirect ownership or reading the token property permissions.2455pub struct PropertyWriter<'a, WriterVariant, T, Handle> {2456 collection: &'a Handle,2457 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2458 _phantom: PhantomData<(T, WriterVariant)>,2459}24602461impl<'a, T, Handle, WriterVariant> PropertyWriter<'a, WriterVariant, T, Handle>2462where2463 T: Config,2464 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2465{2466 fn internal_write_token_properties(2467 &mut self,2468 token_id: TokenId,2469 mut token_lazy_info: PropertyWriterLazyTokenInfo,2470 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2471 log: evm_coder::ethereum::Log,2472 ) -> DispatchResult {2473 for (key, value) in properties_updates {2474 let permission = self2475 .collection_lazy_info2476 .property_permissions2477 .value()2478 .get(&key)2479 .cloned()2480 .unwrap_or_else(PropertyPermission::none);24812482 match permission {2483 PropertyPermission { mutable: false, .. }2484 if token_lazy_info2485 .stored_properties2486 .value()2487 .get(&key)2488 .is_some() =>2489 {2490 return Err(<Error<T>>::NoPermission.into());2491 }24922493 PropertyPermission {2494 collection_admin,2495 token_owner,2496 ..2497 } => check_token_permissions::<T>(2498 collection_admin,2499 token_owner,2500 &mut self.collection_lazy_info.is_collection_admin,2501 &mut token_lazy_info.is_token_owner,2502 &mut token_lazy_info.is_token_exist,2503 )?,2504 }25052506 match value {2507 Some(value) => {2508 token_lazy_info2509 .stored_properties2510 .value_mut()2511 .try_set(key.clone(), value)2512 .map_err(<Error<T>>::from)?;25132514 <Pallet<T>>::deposit_event(Event::TokenPropertySet(2515 self.collection.id,2516 token_id,2517 key,2518 ));2519 }2520 None => {2521 token_lazy_info2522 .stored_properties2523 .value_mut()2524 .remove(&key)2525 .map_err(<Error<T>>::from)?;25262527 <Pallet<T>>::deposit_event(Event::TokenPropertyDeleted(2528 self.collection.id,2529 token_id,2530 key,2531 ));2532 }2533 }2534 }25352536 let properties_changed = token_lazy_info.stored_properties.has_value();2537 if properties_changed {2538 <PalletEvm<T>>::deposit_log(log);25392540 self.collection2541 .set_token_properties_raw(token_id, token_lazy_info.stored_properties.into_inner());2542 }25432544 Ok(())2545 }2546}25472548/// A helper structure for the [`PropertyWriter`] that holds2549/// the collection-related info. The info is loaded using lazy evaluation.2550/// This info is common for any token for which we write properties.2551pub struct PropertyWriterLazyCollectionInfo<'a> {2552 is_collection_admin: LazyValue<'a, bool>,2553 property_permissions: LazyValue<'a, PropertiesPermissionMap>,2554}25552556/// A helper structure for the [`PropertyWriter`] that holds2557/// the token-related info. The info is loaded using lazy evaluation.2558pub struct PropertyWriterLazyTokenInfo<'a> {2559 is_token_exist: LazyValue<'a, bool>,2560 is_token_owner: LazyValue<'a, Result<bool, DispatchError>>,2561 stored_properties: LazyValue<'a, TokenProperties>,2562}25632564impl<'a> PropertyWriterLazyTokenInfo<'a> {2565 /// Create a lazy token info.2566 pub fn new(2567 check_token_exist: impl FnOnce() -> bool + 'a,2568 check_token_owner: impl FnOnce() -> Result<bool, DispatchError> + 'a,2569 get_token_properties: impl FnOnce() -> TokenProperties + 'a,2570 ) -> Self {2571 Self {2572 is_token_exist: LazyValue::new(check_token_exist),2573 is_token_owner: LazyValue::new(check_token_owner),2574 stored_properties: LazyValue::new(get_token_properties),2575 }2576 }2577}25782579/// A marker structure that enables the writer implementation2580/// to provide the interface to write properties to **newly created** tokens.2581pub struct NewTokenPropertyWriter<T>(PhantomData<T>);2582impl<T: Config> NewTokenPropertyWriter<T> {2583 /// Creates a [`PropertyWriter`] for **newly created** tokens.2584 pub fn new<'a, Handle>(2585 collection: &'a Handle,2586 sender: &'a T::CrossAccountId,2587 ) -> PropertyWriter<'a, Self, T, Handle>2588 where2589 T: Config,2590 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2591 {2592 PropertyWriter {2593 collection,2594 collection_lazy_info: PropertyWriterLazyCollectionInfo {2595 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2596 property_permissions: LazyValue::new(|| {2597 <Pallet<T>>::property_permissions(collection.id)2598 }),2599 },2600 _phantom: PhantomData,2601 }2602 }2603}26042605impl<'a, T, Handle> PropertyWriter<'a, NewTokenPropertyWriter<T>, T, Handle>2606where2607 T: Config,2608 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2609{2610 /// A function to write properties to a **newly created** token.2611 pub fn write_token_properties(2612 &mut self,2613 mint_target_is_sender: bool,2614 token_id: TokenId,2615 properties_updates: impl Iterator<Item = Property>,2616 log: evm_coder::ethereum::Log,2617 ) -> DispatchResult {2618 let check_token_exist = || {2619 debug_assert!(self.collection.token_exists(token_id));2620 true2621 };26222623 let check_token_owner = || Ok(mint_target_is_sender);26242625 let get_token_properties = || {2626 debug_assert!(self.collection.get_token_properties_raw(token_id).is_none());2627 TokenProperties::new()2628 };26292630 self.internal_write_token_properties(2631 token_id,2632 PropertyWriterLazyTokenInfo::new(2633 check_token_exist,2634 check_token_owner,2635 get_token_properties,2636 ),2637 properties_updates.map(|p| (p.key, Some(p.value))),2638 log,2639 )2640 }2641}26422643/// A marker structure that enables the writer implementation2644/// to provide the interface to write properties to **already existing** tokens.2645pub struct ExistingTokenPropertyWriter<T>(PhantomData<T>);2646impl<T: Config> ExistingTokenPropertyWriter<T> {2647 /// Creates a [`PropertyWriter`] for **already existing** tokens.2648 pub fn new<'a, Handle>(2649 collection: &'a Handle,2650 sender: &'a T::CrossAccountId,2651 ) -> PropertyWriter<'a, Self, T, Handle>2652 where2653 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2654 {2655 PropertyWriter {2656 collection,2657 collection_lazy_info: PropertyWriterLazyCollectionInfo {2658 is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),2659 property_permissions: LazyValue::new(|| {2660 <Pallet<T>>::property_permissions(collection.id)2661 }),2662 },2663 _phantom: PhantomData,2664 }2665 }2666}26672668impl<'a, T, Handle> PropertyWriter<'a, ExistingTokenPropertyWriter<T>, T, Handle>2669where2670 T: Config,2671 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2672{2673 /// A function to write properties to an **already existing** token.2674 pub fn write_token_properties(2675 &mut self,2676 sender: &T::CrossAccountId,2677 token_id: TokenId,2678 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,2679 nesting_budget: &dyn Budget,2680 log: evm_coder::ethereum::Log,2681 ) -> DispatchResult {2682 let check_token_exist = || self.collection.token_exists(token_id);2683 let check_token_owner = || {2684 self.collection2685 .check_token_indirect_owner(token_id, sender, nesting_budget)2686 };2687 let get_token_properties = || {2688 self.collection2689 .get_token_properties_raw(token_id)2690 .unwrap_or_default()2691 };26922693 self.internal_write_token_properties(2694 token_id,2695 PropertyWriterLazyTokenInfo::new(2696 check_token_exist,2697 check_token_owner,2698 get_token_properties,2699 ),2700 properties_updates,2701 log,2702 )2703 }2704}27052706/// A marker structure that enables the writer implementation2707/// to benchmark the token properties writing.2708#[cfg(feature = "runtime-benchmarks")]2709pub struct BenchmarkPropertyWriter<T>(PhantomData<T>);27102711#[cfg(feature = "runtime-benchmarks")]2712impl<T: Config> BenchmarkPropertyWriter<T> {2713 /// Creates a [`PropertyWriter`] for benchmarking tokens properties writing.2714 pub fn new<'a, Handle>(2715 collection: &'a Handle,2716 collection_lazy_info: PropertyWriterLazyCollectionInfo<'a>,2717 ) -> PropertyWriter<'a, Self, T, Handle>2718 where2719 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2720 {2721 PropertyWriter {2722 collection,2723 collection_lazy_info,2724 _phantom: PhantomData,2725 }2726 }27272728 /// Load the [`PropertyWriterLazyCollectionInfo`] from the storage.2729 pub fn load_collection_info<Handle>(2730 collection_handle: &Handle,2731 sender: &T::CrossAccountId,2732 ) -> PropertyWriterLazyCollectionInfo<'static>2733 where2734 Handle: Deref<Target = CollectionHandle<T>>,2735 {2736 let is_collection_admin = collection_handle.is_owner_or_admin(sender);2737 let property_permissions = <Pallet<T>>::property_permissions(collection_handle.id);27382739 PropertyWriterLazyCollectionInfo {2740 is_collection_admin: LazyValue::new(move || is_collection_admin),2741 property_permissions: LazyValue::new(move || property_permissions),2742 }2743 }27442745 /// Load the [`PropertyWriterLazyTokenInfo`] with token properties from the storage.2746 pub fn load_token_properties<Handle>(2747 collection: &Handle,2748 token_id: TokenId,2749 ) -> PropertyWriterLazyTokenInfo2750 where2751 Handle: CommonCollectionOperations<T>,2752 {2753 let stored_properties = collection2754 .get_token_properties_raw(token_id)2755 .unwrap_or_default();27562757 PropertyWriterLazyTokenInfo {2758 is_token_exist: LazyValue::new(|| true),2759 is_token_owner: LazyValue::new(|| Ok(true)),2760 stored_properties: LazyValue::new(move || stored_properties),2761 }2762 }2763}27642765#[cfg(feature = "runtime-benchmarks")]2766impl<'a, T, Handle> PropertyWriter<'a, BenchmarkPropertyWriter<T>, T, Handle>2767where2768 T: Config,2769 Handle: CommonCollectionOperations<T> + Deref<Target = CollectionHandle<T>>,2770{2771 /// A function to benchmark the writing of token properties.2772 pub fn write_token_properties(2773 &mut self,2774 token_id: TokenId,2775 properties_updates: impl Iterator<Item = Property>,2776 log: evm_coder::ethereum::Log,2777 ) -> DispatchResult {2778 let check_token_exist = || true;2779 let check_token_owner = || Ok(true);2780 let get_token_properties = TokenProperties::new;27812782 self.internal_write_token_properties(2783 token_id,2784 PropertyWriterLazyTokenInfo::new(2785 check_token_exist,2786 check_token_owner,2787 get_token_properties,2788 ),2789 properties_updates.map(|p| (p.key, Some(p.value))),2790 log,2791 )2792 }2793}27942795/// Computes the weight of writing properties to tokens.2796/// * `properties_nums` - The properties num of each created token.2797/// * `per_token_weight_weight` - The function to obtain the weight2798/// of writing properties from a token's properties num.2799pub fn write_token_properties_total_weight<T: Config, I: Fn(u32) -> Weight>(2800 properties_nums: impl Iterator<Item = u32>,2801 per_token_weight: I,2802) -> Weight {2803 let mut weight = properties_nums2804 .filter_map(|properties_num| {2805 if properties_num > 0 {2806 Some(per_token_weight(properties_num))2807 } else {2808 None2809 }2810 })2811 .fold(Weight::zero(), |a, b| a.saturating_add(b));28122813 if !weight.is_zero() {2814 // If we are here, it means the token properties were written at least once.2815 // Because of that, some common collection data was also loaded; we must add this weight.2816 // However, this common data was loaded only once, which is guaranteed by the `PropertyWriter`.28172818 weight = weight.saturating_add(<SelfWeightOf<T>>::property_writer_load_collection_info());2819 }28202821 weight2822}28232824#[cfg(any(feature = "tests", test))]2825#[allow(missing_docs)]2826pub mod tests {2827 use crate::{Config, DispatchError, DispatchResult, LazyValue};28282829 const fn to_bool(u: u8) -> bool {2830 u != 02831 }28322833 #[derive(Debug)]2834 pub struct TestCase {2835 pub collection_admin: bool,2836 pub is_collection_admin: bool,2837 pub token_owner: bool,2838 pub is_token_owner: bool,2839 pub no_permission: bool,2840 }28412842 impl TestCase {2843 const fn new(2844 collection_admin: u8,2845 is_collection_admin: u8,2846 token_owner: u8,2847 is_token_owner: u8,2848 no_permission: u8,2849 ) -> Self {2850 Self {2851 collection_admin: to_bool(collection_admin),2852 is_collection_admin: to_bool(is_collection_admin),2853 token_owner: to_bool(token_owner),2854 is_token_owner: to_bool(is_token_owner),2855 no_permission: to_bool(no_permission),2856 }2857 }2858 }28592860 #[rustfmt::skip]2861 pub const TABLE: [TestCase; 16] = [2862 // ┌╴collection_admin2863 // │ ┌╴is_collection_admin2864 // │ │ ┌╴token_owner2865 // │ │ │ ┌╴is_token_ownership2866 // │ │ │ │ ┌╴no_permission2867 /* 0*/ TestCase::new(0, 0, 0, 0, 1),2868 /* 1*/ TestCase::new(0, 0, 0, 1, 1),2869 /* 2*/ TestCase::new(0, 0, 1, 0, 1),2870 /* 3*/ TestCase::new(0, 0, 1, 1, 0),2871 /* 4*/ TestCase::new(0, 1, 0, 0, 1),2872 /* 5*/ TestCase::new(0, 1, 0, 1, 1),2873 /* 6*/ TestCase::new(0, 1, 1, 0, 1),2874 /* 7*/ TestCase::new(0, 1, 1, 1, 0),2875 /* 8*/ TestCase::new(1, 0, 0, 0, 1),2876 /* 9*/ TestCase::new(1, 0, 0, 1, 1),2877 /* 10*/ TestCase::new(1, 0, 1, 0, 1),2878 /* 11*/ TestCase::new(1, 0, 1, 1, 0),2879 /* 12*/ TestCase::new(1, 1, 0, 0, 0),2880 /* 13*/ TestCase::new(1, 1, 0, 1, 0),2881 /* 14*/ TestCase::new(1, 1, 1, 0, 0),2882 /* 15*/ TestCase::new(1, 1, 1, 1, 0),2883 ];28842885 pub fn check_token_permissions<T: Config>(2886 collection_admin_permitted: bool,2887 token_owner_permitted: bool,2888 is_collection_admin: &mut LazyValue<bool>,2889 check_token_ownership: &mut LazyValue<Result<bool, DispatchError>>,2890 check_token_existence: &mut LazyValue<bool>,2891 ) -> DispatchResult {2892 crate::check_token_permissions::<T>(2893 collection_admin_permitted,2894 token_owner_permitted,2895 is_collection_admin,2896 check_token_ownership,2897 check_token_existence,2898 )2899 }2900}pallets/foreign-assets/src/lib.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -240,9 +240,7 @@
) -> Result<Option<CollectionId>, XcmError> {
let self_location = T::SelfLocation::get();
- if *asset_location == Here.into() {
- Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))
- } else if *asset_location == self_location {
+ if *asset_location == Here.into() || *asset_location == self_location {
Ok(Some(NATIVE_FUNGIBLE_COLLECTION_ID))
} else if asset_location.parents == self_location.parents {
match asset_location
@@ -395,7 +393,7 @@
asset_instance: &AssetInstance,
from: T::CrossAccountId,
) -> XcmResult {
- let token_id = Self::asset_instance_to_token_id(collection_id, &asset_instance)?
+ let token_id = Self::asset_instance_to_token_id(collection_id, asset_instance)?
.ok_or(XcmError::AssetNotFound)?;
if xcm_ext.token_has_children(token_id) {
@@ -569,11 +567,11 @@
Fungible(u8),
}
-impl Into<CollectionMode> for ForeignCollectionMode {
- fn into(self) -> CollectionMode {
- match self {
- Self::NFT => CollectionMode::NFT,
- Self::Fungible(decimals) => CollectionMode::Fungible(decimals),
+impl From<ForeignCollectionMode> for CollectionMode {
+ fn from(value: ForeignCollectionMode) -> Self {
+ match value {
+ ForeignCollectionMode::NFT => Self::NFT,
+ ForeignCollectionMode::Fungible(decimals) => Self::Fungible(decimals),
}
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -470,7 +470,7 @@
up_data_structs::CreateItemData::Fungible(fungible_data) => {
<Pallet<T>>::create_multiple_items(
self,
- &depositor,
+ depositor,
[(to, fungible_data.value)].into_iter().collect(),
nesting_budget,
)?
@@ -495,7 +495,7 @@
<CommonError<T>>::FungibleItemsHaveNoId
);
- <Pallet<T>>::transfer_internal(self, &depositor, &from, &to, amount, nesting_budget)
+ <Pallet<T>>::transfer_internal(self, depositor, from, to, amount, nesting_budget)
.map(|_| ())
.map_err(|post_info| post_info.error)
}
@@ -506,7 +506,7 @@
token: TokenId,
amount: u128,
) -> sp_runtime::DispatchResult {
- <Self as CommonCollectionOperations<T>>::burn_item(&self, from, token, amount)
+ <Self as CommonCollectionOperations<T>>::burn_item(self, from, token, amount)
.map(|_| ())
.map_err(|post_info| post_info.error)
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -585,7 +585,7 @@
) -> Result<TokenId, sp_runtime::DispatchError> {
<Pallet<T>>::create_multiple_items(
self,
- &depositor,
+ depositor,
vec![map_create_data::<T>(data, &to)?],
nesting_budget,
)?;
@@ -604,7 +604,7 @@
) -> sp_runtime::DispatchResult {
ensure!(amount == 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
- <Pallet<T>>::transfer_internal(self, &depositor, &from, &to, token, nesting_budget)
+ <Pallet<T>>::transfer_internal(self, depositor, from, to, token, nesting_budget)
.map(|_| ())
.map_err(|post_info| post_info.error)
}
runtime/common/config/pallets/foreign_asset.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/foreign_asset.rs
+++ b/runtime/common/config/pallets/foreign_asset.rs
@@ -26,7 +26,7 @@
{
fn convert_location(location: &MultiLocation) -> Option<ConfigCrossAccountId> {
LocationToAccountId::convert_location(location)
- .map(|sub| ConfigCrossAccountId::from_sub(sub))
+ .map(ConfigCrossAccountId::from_sub)
.or_else(|| {
let eth_address =
AccountKey20Aliases::<RelayNetwork, H160>::convert_location(location)?;