difftreelog
fix owner/admin ignores token restrictions
in: master
4 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 core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118use up_pov_estimate_rpc::PovInfo;119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135///136/// CollectionHandle is used as a generic wrapper for collections of all types.137/// It allows to perform common operations and queries on any collection type,138/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].139#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]140pub struct CollectionHandle<T: Config> {141 /// Collection id142 pub id: CollectionId,143 collection: Collection<T::AccountId>,144 /// Substrate recorder for counting consumed gas145 pub recorder: SubstrateRecorder<T>,146}147148impl<T: Config> WithRecorder<T> for CollectionHandle<T> {149 fn recorder(&self) -> &SubstrateRecorder<T> {150 &self.recorder151 }152 fn into_recorder(self) -> SubstrateRecorder<T> {153 self.recorder154 }155}156157impl<T: Config> CollectionHandle<T> {158 /// Same as [CollectionHandle::new] but with an explicit gas limit.159 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {160 <CollectionById<T>>::get(id).map(|collection| Self {161 id,162 collection,163 recorder: SubstrateRecorder::new(gas_limit),164 })165 }166167 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].168 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {169 <CollectionById<T>>::get(id).map(|collection| Self {170 id,171 collection,172 recorder,173 })174 }175176 /// Retrives collection data from storage and creates collection handle with default parameters.177 /// If collection not found return `None`178 pub fn new(id: CollectionId) -> Option<Self> {179 Self::new_with_gas_limit(id, u64::MAX)180 }181182 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.183 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {184 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)185 }186187 /// Consume gas for reading.188 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 <T as frame_system::Config>::DbWeight::get()192 .read193 .saturating_mul(reads),194 )))195 }196197 /// Consume gas for writing.198 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199 self.recorder200 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(201 <T as frame_system::Config>::DbWeight::get()202 .write203 .saturating_mul(writes),204 )))205 }206207 /// Consume gas for reading and writing.208 pub fn consume_store_reads_and_writes(209 &self,210 reads: u64,211 writes: u64,212 ) -> evm_coder::execution::Result<()> {213 let weight = <T as frame_system::Config>::DbWeight::get();214 let reads = weight.read.saturating_mul(reads);215 let writes = weight.read.saturating_mul(writes);216 self.recorder217 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(218 reads.saturating_add(writes),219 )))220 }221222 /// Save collection to storage.223 pub fn save(&self) -> DispatchResult {224 <CollectionById<T>>::insert(self.id, &self.collection);225 Ok(())226 }227228 /// Set collection sponsor.229 ///230 /// Unique collections allows sponsoring for certain actions.231 /// This method allows you to set the sponsor of the collection.232 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].233 pub fn set_sponsor(234 &mut self,235 sender: &T::CrossAccountId,236 sponsor: T::AccountId,237 ) -> DispatchResult {238 self.check_is_internal()?;239 self.check_is_owner_or_admin(sender)?;240241 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());242243 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));244 <PalletEvm<T>>::deposit_log(245 erc::CollectionHelpersEvents::CollectionChanged {246 collection_id: eth::collection_id_to_address(self.id),247 }248 .to_log(T::ContractAddress::get()),249 );250251 self.save()252 }253254 /// Force set `sponsor`.255 ///256 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation257 /// from the `sponsor` is not required.258 ///259 /// # Arguments260 ///261 /// * `sender`: Caller's account.262 /// * `sponsor`: ID of the account of the sponsor-to-be.263 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {264 self.check_is_internal()?;265266 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());267268 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));269 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));270 <PalletEvm<T>>::deposit_log(271 erc::CollectionHelpersEvents::CollectionChanged {272 collection_id: eth::collection_id_to_address(self.id),273 }274 .to_log(T::ContractAddress::get()),275 );276277 self.save()278 }279280 /// Confirm sponsorship281 ///282 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.283 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].284 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {285 self.check_is_internal()?;286 ensure!(287 self.collection.sponsorship.pending_sponsor() == Some(sender),288 Error::<T>::ConfirmSponsorshipFail289 );290291 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());292293 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));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 );300301 self.save()302 }303304 /// Remove collection sponsor.305 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {306 self.check_is_internal()?;307 self.check_is_owner_or_admin(sender)?;308309 self.collection.sponsorship = SponsorshipState::Disabled;310311 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));312 <PalletEvm<T>>::deposit_log(313 erc::CollectionHelpersEvents::CollectionChanged {314 collection_id: eth::collection_id_to_address(self.id),315 }316 .to_log(T::ContractAddress::get()),317 );318 self.save()319 }320321 /// Force remove `sponsor`.322 ///323 /// Differs from `remove_sponsor` in that324 /// it doesn't require consent from the `owner` of the collection.325 pub fn force_remove_sponsor(&mut self) -> DispatchResult {326 self.check_is_internal()?;327328 self.collection.sponsorship = SponsorshipState::Disabled;329330 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));331 <PalletEvm<T>>::deposit_log(332 erc::CollectionHelpersEvents::CollectionChanged {333 collection_id: eth::collection_id_to_address(self.id),334 }335 .to_log(T::ContractAddress::get()),336 );337 self.save()338 }339340 /// Checks that the collection was created with, and must be operated upon through **Unique API**.341 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.342 pub fn check_is_internal(&self) -> DispatchResult {343 if self.flags.external {344 return Err(<Error<T>>::CollectionIsExternal)?;345 }346347 Ok(())348 }349350 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.351 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.352 pub fn check_is_external(&self) -> DispatchResult {353 if !self.flags.external {354 return Err(<Error<T>>::CollectionIsInternal)?;355 }356357 Ok(())358 }359}360361impl<T: Config> Deref for CollectionHandle<T> {362 type Target = Collection<T::AccountId>;363364 fn deref(&self) -> &Self::Target {365 &self.collection366 }367}368369impl<T: Config> DerefMut for CollectionHandle<T> {370 fn deref_mut(&mut self) -> &mut Self::Target {371 &mut self.collection372 }373}374375impl<T: Config> CollectionHandle<T> {376 /// Checks if the `user` is the owner of the collection.377 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {378 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);379 Ok(())380 }381382 /// Returns **true** if the `user` is the owner or administrator of the collection.383 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {384 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))385 }386387 /// Checks if the `user` is the owner or administrator of the collection.388 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {389 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);390 Ok(())391 }392393 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.394 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {395 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)396 }397398 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.399 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {400 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)401 }402403 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.404 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {405 ensure!(406 <Allowlist<T>>::get((self.id, user)),407 <Error<T>>::AddressNotInAllowlist408 );409 Ok(())410 }411412 /// Changes collection owner to another account413 /// #### Store read/writes414 /// 1 writes415 pub fn change_owner(416 &mut self,417 caller: T::CrossAccountId,418 new_owner: T::CrossAccountId,419 ) -> DispatchResult {420 self.check_is_internal()?;421 self.check_is_owner(&caller)?;422 self.collection.owner = new_owner.as_sub().clone();423424 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(425 self.id,426 new_owner.as_sub().clone(),427 ));428 <PalletEvm<T>>::deposit_log(429 erc::CollectionHelpersEvents::CollectionChanged {430 collection_id: eth::collection_id_to_address(self.id),431 }432 .to_log(T::ContractAddress::get()),433 );434435 self.save()436 }437}438439#[frame_support::pallet]440pub mod pallet {441 use super::*;442 use dispatch::CollectionDispatch;443 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};444 use frame_system::pallet_prelude::*;445 use frame_support::traits::Currency;446 use up_data_structs::{TokenId, mapping::TokenAddressMapping};447 use scale_info::TypeInfo;448 use weights::WeightInfo;449450 #[pallet::config]451 pub trait Config:452 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo453 {454 /// Weight information for functions of this pallet.455 type WeightInfo: WeightInfo;456457 /// Events compatible with [`frame_system::Config::Event`].458 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;459460 /// Handler of accounts and payment.461 type Currency: Currency<Self::AccountId>;462463 /// Set price to create a collection.464 #[pallet::constant]465 type CollectionCreationPrice: Get<466 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,467 >;468469 /// Dispatcher of operations on collections.470 type CollectionDispatch: CollectionDispatch<Self>;471472 /// Account which holds the chain's treasury.473 type TreasuryAccountId: Get<Self::AccountId>;474475 /// Address under which the CollectionHelper contract would be available.476 #[pallet::constant]477 type ContractAddress: Get<H160>;478479 /// Mapper for token addresses to Ethereum addresses.480 type EvmTokenAddressMapping: TokenAddressMapping<H160>;481482 /// Mapper for token addresses to [`CrossAccountId`].483 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;484 }485486 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);487488 #[pallet::pallet]489 #[pallet::storage_version(STORAGE_VERSION)]490 #[pallet::generate_store(pub(super) trait Store)]491 pub struct Pallet<T>(_);492493 #[pallet::extra_constants]494 impl<T: Config> Pallet<T> {495 /// Maximum admins per collection.496 pub fn collection_admins_limit() -> u32 {497 COLLECTION_ADMINS_LIMIT498 }499 }500501 #[pallet::event]502 #[pallet::generate_deposit(pub fn deposit_event)]503 pub enum Event<T: Config> {504 /// New collection was created505 CollectionCreated(506 /// Globally unique identifier of newly created collection.507 CollectionId,508 /// [`CollectionMode`] converted into _u8_.509 u8,510 /// Collection owner.511 T::AccountId,512 ),513514 /// New collection was destroyed515 CollectionDestroyed(516 /// Globally unique identifier of collection.517 CollectionId,518 ),519520 /// New item was created.521 ItemCreated(522 /// Id of the collection where item was created.523 CollectionId,524 /// Id of an item. Unique within the collection.525 TokenId,526 /// Owner of newly created item527 T::CrossAccountId,528 /// Always 1 for NFT529 u128,530 ),531532 /// Collection item was burned.533 ItemDestroyed(534 /// Id of the collection where item was destroyed.535 CollectionId,536 /// Identifier of burned NFT.537 TokenId,538 /// Which user has destroyed its tokens.539 T::CrossAccountId,540 /// Amount of token pieces destroed. Always 1 for NFT.541 u128,542 ),543544 /// Item was transferred545 Transfer(546 /// Id of collection to which item is belong.547 CollectionId,548 /// Id of an item.549 TokenId,550 /// Original owner of item.551 T::CrossAccountId,552 /// New owner of item.553 T::CrossAccountId,554 /// Amount of token pieces transfered. Always 1 for NFT.555 u128,556 ),557558 /// Amount pieces of token owned by `sender` was approved for `spender`.559 Approved(560 /// Id of collection to which item is belong.561 CollectionId,562 /// Id of an item.563 TokenId,564 /// Original owner of item.565 T::CrossAccountId,566 /// Id for which the approval was granted.567 T::CrossAccountId,568 /// Amount of token pieces transfered. Always 1 for NFT.569 u128,570 ),571572 /// A `sender` approves operations on all owned tokens for `spender`.573 ApprovedForAll(574 /// Id of collection to which item is belong.575 CollectionId,576 /// Owner of a wallet.577 T::CrossAccountId,578 /// Id for which operator status was granted or rewoked.579 T::CrossAccountId,580 /// Is operator status granted or revoked?581 bool,582 ),583584 /// The colletion property has been added or edited.585 CollectionPropertySet(586 /// Id of collection to which property has been set.587 CollectionId,588 /// The property that was set.589 PropertyKey,590 ),591592 /// The property has been deleted.593 CollectionPropertyDeleted(594 /// Id of collection to which property has been deleted.595 CollectionId,596 /// The property that was deleted.597 PropertyKey,598 ),599600 /// The token property has been added or edited.601 TokenPropertySet(602 /// Identifier of the collection whose token has the property set.603 CollectionId,604 /// The token for which the property was set.605 TokenId,606 /// The property that was set.607 PropertyKey,608 ),609610 /// The token property has been deleted.611 TokenPropertyDeleted(612 /// Identifier of the collection whose token has the property deleted.613 CollectionId,614 /// The token for which the property was deleted.615 TokenId,616 /// The property that was deleted.617 PropertyKey,618 ),619620 /// The token property permission of a collection has been set.621 PropertyPermissionSet(622 /// ID of collection to which property permission has been set.623 CollectionId,624 /// The property permission that was set.625 PropertyKey,626 ),627628 /// Address was added to the allow list.629 AllowListAddressAdded(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the added account.633 T::CrossAccountId,634 ),635636 /// Address was removed from the allow list.637 AllowListAddressRemoved(638 /// ID of the affected collection.639 CollectionId,640 /// Address of the removed account.641 T::CrossAccountId,642 ),643644 /// Collection admin was added.645 CollectionAdminAdded(646 /// ID of the affected collection.647 CollectionId,648 /// Admin address.649 T::CrossAccountId,650 ),651652 /// Collection admin was removed.653 CollectionAdminRemoved(654 /// ID of the affected collection.655 CollectionId,656 /// Removed admin address.657 T::CrossAccountId,658 ),659660 /// Collection limits were set.661 CollectionLimitSet(662 /// ID of the affected collection.663 CollectionId,664 ),665666 /// Collection owned was changed.667 CollectionOwnerChanged(668 /// ID of the affected collection.669 CollectionId,670 /// New owner address.671 T::AccountId,672 ),673674 /// Collection permissions were set.675 CollectionPermissionSet(676 /// ID of the affected collection.677 CollectionId,678 ),679680 /// Collection sponsor was set.681 CollectionSponsorSet(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// New sponsor was confirm.689 SponsorshipConfirmed(690 /// ID of the affected collection.691 CollectionId,692 /// New sponsor address.693 T::AccountId,694 ),695696 /// Collection sponsor was removed.697 CollectionSponsorRemoved(698 /// ID of the affected collection.699 CollectionId,700 ),701 }702703 #[pallet::error]704 pub enum Error<T> {705 /// This collection does not exist.706 CollectionNotFound,707 /// Sender parameter and item owner must be equal.708 MustBeTokenOwner,709 /// No permission to perform action710 NoPermission,711 /// Destroying only empty collections is allowed712 CantDestroyNotEmptyCollection,713 /// Collection is not in mint mode.714 PublicMintingNotAllowed,715 /// Address is not in allow list.716 AddressNotInAllowlist,717718 /// Collection name can not be longer than 63 char.719 CollectionNameLimitExceeded,720 /// Collection description can not be longer than 255 char.721 CollectionDescriptionLimitExceeded,722 /// Token prefix can not be longer than 15 char.723 CollectionTokenPrefixLimitExceeded,724 /// Total collections bound exceeded.725 TotalCollectionsLimitExceeded,726 /// Exceeded max admin count727 CollectionAdminCountExceeded,728 /// Collection limit bounds per collection exceeded729 CollectionLimitBoundsExceeded,730 /// Tried to enable permissions which are only permitted to be disabled731 OwnerPermissionsCantBeReverted,732 /// Collection settings not allowing items transferring733 TransferNotAllowed,734 /// Account token limit exceeded per collection735 AccountTokenLimitExceeded,736 /// Collection token limit exceeded737 CollectionTokenLimitExceeded,738 /// Metadata flag frozen739 MetadataFlagFrozen,740741 /// Item does not exist742 TokenNotFound,743 /// Item is balance not enough744 TokenValueTooLow,745 /// Requested value is more than the approved746 ApprovedValueTooLow,747 /// Tried to approve more than owned748 CantApproveMoreThanOwned,749 /// Only spending from eth mirror could be approved750 AddressIsNotEthMirror,751752 /// Can't transfer tokens to ethereum zero address753 AddressIsZero,754755 /// The operation is not supported756 UnsupportedOperation,757758 /// Insufficient funds to perform an action759 NotSufficientFounds,760761 /// User does not satisfy the nesting rule762 UserIsNotAllowedToNest,763 /// Only tokens from specific collections may nest tokens under this one764 SourceCollectionIsNotAllowedToNest,765766 /// Tried to store more data than allowed in collection field767 CollectionFieldSizeExceeded,768769 /// Tried to store more property data than allowed770 NoSpaceForProperty,771772 /// Tried to store more property keys than allowed773 PropertyLimitReached,774775 /// Property key is too long776 PropertyKeyIsTooLong,777778 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed779 InvalidCharacterInPropertyKey,780781 /// Empty property keys are forbidden782 EmptyPropertyKey,783784 /// Tried to access an external collection with an internal API785 CollectionIsExternal,786787 /// Tried to access an internal collection with an external API788 CollectionIsInternal,789790 /// This address is not set as sponsor, use setCollectionSponsor first.791 ConfirmSponsorshipFail,792793 /// The user is not an administrator.794 UserIsNotCollectionAdmin,795 }796797 /// Storage of the count of created collections. Essentially contains the last collection ID.798 #[pallet::storage]799 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;800801 /// Storage of the count of deleted collections.802 #[pallet::storage]803 pub type DestroyedCollectionCount<T> =804 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;805806 /// Storage of collection info.807 #[pallet::storage]808 pub type CollectionById<T> = StorageMap<809 Hasher = Blake2_128Concat,810 Key = CollectionId,811 Value = Collection<<T as frame_system::Config>::AccountId>,812 QueryKind = OptionQuery,813 >;814815 /// Storage of collection properties.816 #[pallet::storage]817 #[pallet::getter(fn collection_properties)]818 pub type CollectionProperties<T> = StorageMap<819 Hasher = Blake2_128Concat,820 Key = CollectionId,821 Value = Properties,822 QueryKind = ValueQuery,823 OnEmpty = up_data_structs::CollectionProperties,824 >;825826 /// Storage of token property permissions of a collection.827 #[pallet::storage]828 #[pallet::getter(fn property_permissions)]829 pub type CollectionPropertyPermissions<T> = StorageMap<830 Hasher = Blake2_128Concat,831 Key = CollectionId,832 Value = PropertiesPermissionMap,833 QueryKind = ValueQuery,834 >;835836 /// Storage of the amount of collection admins.837 #[pallet::storage]838 pub type AdminAmount<T> = StorageMap<839 Hasher = Blake2_128Concat,840 Key = CollectionId,841 Value = u32,842 QueryKind = ValueQuery,843 >;844845 /// List of collection admins.846 #[pallet::storage]847 pub type IsAdmin<T: Config> = StorageNMap<848 Key = (849 Key<Blake2_128Concat, CollectionId>,850 Key<Blake2_128Concat, T::CrossAccountId>,851 ),852 Value = bool,853 QueryKind = ValueQuery,854 >;855856 /// Allowlisted collection users.857 #[pallet::storage]858 pub type Allowlist<T: Config> = StorageNMap<859 Key = (860 Key<Blake2_128Concat, CollectionId>,861 Key<Blake2_128Concat, T::CrossAccountId>,862 ),863 Value = bool,864 QueryKind = ValueQuery,865 >;866867 /// Not used by code, exists only to provide some types to metadata.868 #[pallet::storage]869 pub type DummyStorageValue<T: Config> = StorageValue<870 Value = (871 CollectionStats,872 CollectionId,873 TokenId,874 TokenChild,875 PhantomType<(876 TokenData<T::CrossAccountId>,877 RpcCollection<T::AccountId>,878 // RMRK879 RmrkCollectionInfo<T::AccountId>,880 RmrkInstanceInfo<T::AccountId>,881 RmrkResourceInfo,882 RmrkPropertyInfo,883 RmrkBaseInfo<T::AccountId>,884 RmrkPartType,885 RmrkBoundedTheme,886 RmrkNftChild,887 // PoV Estimate Info888 PovInfo,889 )>,890 ),891 QueryKind = OptionQuery,892 >;893894 #[pallet::hooks]895 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {896 fn on_runtime_upgrade() -> Weight {897 StorageVersion::new(1).put::<Pallet<T>>();898899 Weight::zero()900 }901 }902}903904impl<T: Config> Pallet<T> {905 /// Enshure that receiver address is correct.906 ///907 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.908 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {909 ensure!(910 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,911 <Error<T>>::AddressIsZero912 );913 Ok(())914 }915916 /// Get a vector of collection admins.917 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {918 <IsAdmin<T>>::iter_prefix((collection,))919 .map(|(a, _)| a)920 .collect()921 }922923 /// Get a vector of users allowed to mint tokens.924 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {925 <Allowlist<T>>::iter_prefix((collection,))926 .map(|(a, _)| a)927 .collect()928 }929930 /// Is `user` allowed to mint token in `collection`.931 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {932 <Allowlist<T>>::get((collection, user))933 }934935 /// Get statistics of collections.936 pub fn collection_stats() -> CollectionStats {937 let created = <CreatedCollectionCount<T>>::get();938 let destroyed = <DestroyedCollectionCount<T>>::get();939 CollectionStats {940 created: created.0,941 destroyed: destroyed.0,942 alive: created.0 - destroyed.0,943 }944 }945946 /// Get the effective limits for the collection.947 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {948 let collection = <CollectionById<T>>::get(collection)?;949 let limits = collection.limits;950 let effective_limits = CollectionLimits {951 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),952 sponsored_data_size: Some(limits.sponsored_data_size()),953 sponsored_data_rate_limit: Some(954 limits955 .sponsored_data_rate_limit956 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),957 ),958 token_limit: Some(limits.token_limit()),959 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(960 match collection.mode {961 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,962 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,963 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,964 },965 )),966 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),967 owner_can_transfer: Some(limits.owner_can_transfer()),968 owner_can_destroy: Some(limits.owner_can_destroy()),969 transfers_enabled: Some(limits.transfers_enabled()),970 };971972 Some(effective_limits)973 }974975 /// Returns information about the `collection` adapted for rpc.976 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {977 let Collection {978 name,979 description,980 owner,981 mode,982 token_prefix,983 sponsorship,984 limits,985 permissions,986 flags,987 } = <CollectionById<T>>::get(collection)?;988989 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)990 .into_iter()991 .map(|(key, permission)| PropertyKeyPermission { key, permission })992 .collect();993994 let properties = <CollectionProperties<T>>::get(collection)995 .into_iter()996 .map(|(key, value)| Property { key, value })997 .collect();998999 let permissions = CollectionPermissions {1000 access: Some(permissions.access()),1001 mint_mode: Some(permissions.mint_mode()),1002 nesting: Some(permissions.nesting().clone()),1003 };10041005 Some(RpcCollection {1006 name: name.into_inner(),1007 description: description.into_inner(),1008 owner,1009 mode,1010 token_prefix: token_prefix.into_inner(),1011 sponsorship,1012 limits,1013 permissions,1014 token_property_permissions,1015 properties,1016 read_only: flags.external,10171018 flags: RpcCollectionFlags {1019 foreign: flags.foreign,1020 erc721metadata: flags.erc721metadata,1021 },1022 })1023 }1024}10251026macro_rules! limit_default {1027 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1028 $(1029 if let Some($new) = $new.$field {1030 let $old = $old.$field($($arg)?);1031 let _ = $new;1032 let _ = $old;1033 $check1034 } else {1035 $new.$field = $old.$field1036 }1037 )*1038 }};1039}1040macro_rules! limit_default_clone {1041 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1042 $(1043 if let Some($new) = $new.$field.clone() {1044 let $old = $old.$field($($arg)?);1045 let _ = $new;1046 let _ = $old;1047 $check1048 } else {1049 $new.$field = $old.$field.clone()1050 }1051 )*1052 }};1053}10541055impl<T: Config> Pallet<T> {1056 /// Create new collection.1057 ///1058 /// * `owner` - The owner of the collection.1059 /// * `data` - Description of the created collection.1060 /// * `flags` - Extra flags to store.1061 pub fn init_collection(1062 owner: T::CrossAccountId,1063 payer: T::CrossAccountId,1064 data: CreateCollectionData<T::AccountId>,1065 flags: CollectionFlags,1066 ) -> Result<CollectionId, DispatchError> {1067 {1068 ensure!(1069 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1070 Error::<T>::CollectionTokenPrefixLimitExceeded1071 );1072 }10731074 let created_count = <CreatedCollectionCount<T>>::get()1075 .01076 .checked_add(1)1077 .ok_or(ArithmeticError::Overflow)?;1078 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1079 let id = CollectionId(created_count);10801081 // bound Total number of collections1082 ensure!(1083 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1084 <Error<T>>::TotalCollectionsLimitExceeded1085 );10861087 // =========10881089 let collection = Collection {1090 owner: owner.as_sub().clone(),1091 name: data.name,1092 mode: data.mode.clone(),1093 description: data.description,1094 token_prefix: data.token_prefix,1095 sponsorship: data1096 .pending_sponsor1097 .map(SponsorshipState::Unconfirmed)1098 .unwrap_or_default(),1099 limits: data1100 .limits1101 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1102 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1103 permissions: data1104 .permissions1105 .map(|permissions| {1106 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1107 })1108 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1109 flags,1110 };11111112 let mut collection_properties = up_data_structs::CollectionProperties::get();1113 collection_properties1114 .try_set_from_iter(data.properties.into_iter())1115 .map_err(<Error<T>>::from)?;11161117 CollectionProperties::<T>::insert(id, collection_properties);11181119 let mut token_props_permissions = PropertiesPermissionMap::new();1120 token_props_permissions1121 .try_set_from_iter(data.token_property_permissions.into_iter())1122 .map_err(<Error<T>>::from)?;11231124 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11251126 // Take a (non-refundable) deposit of collection creation1127 {1128 let mut imbalance =1129 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1130 imbalance.subsume(1131 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1132 &T::TreasuryAccountId::get(),1133 T::CollectionCreationPrice::get(),1134 ),1135 );1136 <T as Config>::Currency::settle(1137 payer.as_sub(),1138 imbalance,1139 WithdrawReasons::TRANSFER,1140 ExistenceRequirement::KeepAlive,1141 )1142 .map_err(|_| Error::<T>::NotSufficientFounds)?;1143 }11441145 <CreatedCollectionCount<T>>::put(created_count);1146 <Pallet<T>>::deposit_event(Event::CollectionCreated(1147 id,1148 data.mode.id(),1149 owner.as_sub().clone(),1150 ));1151 <PalletEvm<T>>::deposit_log(1152 erc::CollectionHelpersEvents::CollectionCreated {1153 owner: *owner.as_eth(),1154 collection_id: eth::collection_id_to_address(id),1155 }1156 .to_log(T::ContractAddress::get()),1157 );1158 <CollectionById<T>>::insert(id, collection);1159 Ok(id)1160 }11611162 /// Destroy collection.1163 ///1164 /// * `collection` - Collection handler.1165 /// * `sender` - The owner or administrator of the collection.1166 pub fn destroy_collection(1167 collection: CollectionHandle<T>,1168 sender: &T::CrossAccountId,1169 ) -> DispatchResult {1170 ensure!(1171 collection.limits.owner_can_destroy(),1172 <Error<T>>::NoPermission,1173 );1174 collection.check_is_owner(sender)?;11751176 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1177 .01178 .checked_add(1)1179 .ok_or(ArithmeticError::Overflow)?;11801181 // =========11821183 <DestroyedCollectionCount<T>>::put(destroyed_collections);1184 <CollectionById<T>>::remove(collection.id);1185 <AdminAmount<T>>::remove(collection.id);1186 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1187 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1188 <CollectionProperties<T>>::remove(collection.id);11891190 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11911192 <PalletEvm<T>>::deposit_log(1193 erc::CollectionHelpersEvents::CollectionDestroyed {1194 collection_id: eth::collection_id_to_address(collection.id),1195 }1196 .to_log(T::ContractAddress::get()),1197 );1198 Ok(())1199 }12001201 /// This function sets or removes a collection properties according to1202 /// `properties_updates` contents:1203 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1204 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1205 ///1206 /// This function fires an event for each property change.1207 /// In case of an error, all the changes (including the events) will be reverted1208 /// since the function is transactional.1209 #[transactional]1210 fn modify_collection_properties(1211 collection: &CollectionHandle<T>,1212 sender: &T::CrossAccountId,1213 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1214 ) -> DispatchResult {1215 collection.check_is_owner_or_admin(sender)?;12161217 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12181219 for (key, value) in properties_updates {1220 match value {1221 Some(value) => {1222 stored_properties1223 .try_set(key.clone(), value)1224 .map_err(<Error<T>>::from)?;12251226 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1227 <PalletEvm<T>>::deposit_log(1228 erc::CollectionHelpersEvents::CollectionChanged {1229 collection_id: eth::collection_id_to_address(collection.id),1230 }1231 .to_log(T::ContractAddress::get()),1232 );1233 }1234 None => {1235 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12361237 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1238 <PalletEvm<T>>::deposit_log(1239 erc::CollectionHelpersEvents::CollectionChanged {1240 collection_id: eth::collection_id_to_address(collection.id),1241 }1242 .to_log(T::ContractAddress::get()),1243 );1244 }1245 }1246 }12471248 <CollectionProperties<T>>::set(collection.id, stored_properties);12491250 Ok(())1251 }12521253 /// Set collection property.1254 ///1255 /// * `collection` - Collection handler.1256 /// * `sender` - The owner or administrator of the collection.1257 /// * `property` - The property to set.1258 pub fn set_collection_property(1259 collection: &CollectionHandle<T>,1260 sender: &T::CrossAccountId,1261 property: Property,1262 ) -> DispatchResult {1263 Self::set_collection_properties(collection, sender, [property].into_iter())1264 }12651266 /// Set a scoped collection property, where the scope is a special prefix1267 /// prohibiting a user access to change the property directly.1268 ///1269 /// * `collection_id` - ID of the collection for which the property is being set.1270 /// * `scope` - Property scope.1271 /// * `property` - The property to set.1272 pub fn set_scoped_collection_property(1273 collection_id: CollectionId,1274 scope: PropertyScope,1275 property: Property,1276 ) -> DispatchResult {1277 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1278 properties.try_scoped_set(scope, property.key, property.value)1279 })1280 .map_err(<Error<T>>::from)?;12811282 Ok(())1283 }12841285 /// Set scoped collection properties, where the scope is a special prefix1286 /// prohibiting a user access to change the properties directly.1287 ///1288 /// * `collection_id` - ID of the collection for which the properties is being set.1289 /// * `scope` - Property scope.1290 /// * `properties` - The properties to set.1291 pub fn set_scoped_collection_properties(1292 collection_id: CollectionId,1293 scope: PropertyScope,1294 properties: impl Iterator<Item = Property>,1295 ) -> DispatchResult {1296 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1297 stored_properties.try_scoped_set_from_iter(scope, properties)1298 })1299 .map_err(<Error<T>>::from)?;13001301 Ok(())1302 }13031304 /// Set collection properties.1305 ///1306 /// * `collection` - Collection handler.1307 /// * `sender` - The owner or administrator of the collection.1308 /// * `properties` - The properties to set.1309 pub fn set_collection_properties(1310 collection: &CollectionHandle<T>,1311 sender: &T::CrossAccountId,1312 properties: impl Iterator<Item = Property>,1313 ) -> DispatchResult {1314 Self::modify_collection_properties(1315 collection,1316 sender,1317 properties.map(|property| (property.key, Some(property.value))),1318 )1319 }13201321 /// Delete collection property.1322 ///1323 /// * `collection` - Collection handler.1324 /// * `sender` - The owner or administrator of the collection.1325 /// * `property` - The property to delete.1326 pub fn delete_collection_property(1327 collection: &CollectionHandle<T>,1328 sender: &T::CrossAccountId,1329 property_key: PropertyKey,1330 ) -> DispatchResult {1331 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1332 }13331334 /// Delete collection properties.1335 ///1336 /// * `collection` - Collection handler.1337 /// * `sender` - The owner or administrator of the collection.1338 /// * `properties` - The properties to delete.1339 pub fn delete_collection_properties(1340 collection: &CollectionHandle<T>,1341 sender: &T::CrossAccountId,1342 property_keys: impl Iterator<Item = PropertyKey>,1343 ) -> DispatchResult {1344 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1345 }13461347 /// Set collection propetry permission without any checks.1348 ///1349 /// Used for migrations.1350 ///1351 /// * `collection` - Collection handler.1352 /// * `property_permissions` - Property permissions.1353 pub fn set_property_permission_unchecked(1354 collection: CollectionId,1355 property_permission: PropertyKeyPermission,1356 ) -> DispatchResult {1357 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1358 permissions.try_set(property_permission.key, property_permission.permission)1359 })1360 .map_err(<Error<T>>::from)?;1361 Ok(())1362 }13631364 /// Set collection property permission.1365 ///1366 /// * `collection` - Collection handler.1367 /// * `sender` - The owner or administrator of the collection.1368 /// * `property_permission` - Property permission.1369 pub fn set_property_permission(1370 collection: &CollectionHandle<T>,1371 sender: &T::CrossAccountId,1372 property_permission: PropertyKeyPermission,1373 ) -> DispatchResult {1374 Self::set_scoped_property_permission(1375 collection,1376 sender,1377 PropertyScope::None,1378 property_permission,1379 )1380 }13811382 /// Set collection property permission with scope.1383 ///1384 /// * `collection` - Collection handler.1385 /// * `sender` - The owner or administrator of the collection.1386 /// * `scope` - Property scope.1387 /// * `property_permission` - Property permission.1388 pub fn set_scoped_property_permission(1389 collection: &CollectionHandle<T>,1390 sender: &T::CrossAccountId,1391 scope: PropertyScope,1392 property_permission: PropertyKeyPermission,1393 ) -> DispatchResult {1394 collection.check_is_owner_or_admin(sender)?;13951396 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1397 let current_permission = all_permissions.get(&property_permission.key);1398 if matches![1399 current_permission,1400 Some(PropertyPermission { mutable: false, .. })1401 ] {1402 return Err(<Error<T>>::NoPermission.into());1403 }14041405 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1406 let property_permission = property_permission.clone();1407 permissions.try_scoped_set(1408 scope,1409 property_permission.key,1410 property_permission.permission,1411 )1412 })1413 .map_err(<Error<T>>::from)?;14141415 Self::deposit_event(Event::PropertyPermissionSet(1416 collection.id,1417 property_permission.key,1418 ));1419 <PalletEvm<T>>::deposit_log(1420 erc::CollectionHelpersEvents::CollectionChanged {1421 collection_id: eth::collection_id_to_address(collection.id),1422 }1423 .to_log(T::ContractAddress::get()),1424 );14251426 Ok(())1427 }14281429 /// Set token property permission.1430 ///1431 /// * `collection` - Collection handler.1432 /// * `sender` - The owner or administrator of the collection.1433 /// * `property_permissions` - Property permissions.1434 #[transactional]1435 pub fn set_token_property_permissions(1436 collection: &CollectionHandle<T>,1437 sender: &T::CrossAccountId,1438 property_permissions: Vec<PropertyKeyPermission>,1439 ) -> DispatchResult {1440 Self::set_scoped_token_property_permissions(1441 collection,1442 sender,1443 PropertyScope::None,1444 property_permissions,1445 )1446 }14471448 /// Set token property permission with scope.1449 ///1450 /// * `collection` - Collection handler.1451 /// * `sender` - The owner or administrator of the collection.1452 /// * `scope` - Property scope.1453 /// * `property_permissions` - Property permissions.1454 #[transactional]1455 pub fn set_scoped_token_property_permissions(1456 collection: &CollectionHandle<T>,1457 sender: &T::CrossAccountId,1458 scope: PropertyScope,1459 property_permissions: Vec<PropertyKeyPermission>,1460 ) -> DispatchResult {1461 for prop_pemission in property_permissions {1462 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1463 }14641465 Ok(())1466 }14671468 /// Get collection property.1469 pub fn get_collection_property(1470 collection_id: CollectionId,1471 key: &PropertyKey,1472 ) -> Option<PropertyValue> {1473 Self::collection_properties(collection_id).get(key).cloned()1474 }14751476 /// Convert byte vector to property key vector.1477 pub fn bytes_keys_to_property_keys(1478 keys: Vec<Vec<u8>>,1479 ) -> Result<Vec<PropertyKey>, DispatchError> {1480 keys.into_iter()1481 .map(|key| -> Result<PropertyKey, DispatchError> {1482 key.try_into()1483 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1484 })1485 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1486 }14871488 /// Get properties according to given keys.1489 pub fn filter_collection_properties(1490 collection_id: CollectionId,1491 keys: Option<Vec<PropertyKey>>,1492 ) -> Result<Vec<Property>, DispatchError> {1493 let properties = Self::collection_properties(collection_id);14941495 let properties = keys1496 .map(|keys| {1497 keys.into_iter()1498 .filter_map(|key| {1499 properties.get(&key).map(|value| Property {1500 key,1501 value: value.clone(),1502 })1503 })1504 .collect()1505 })1506 .unwrap_or_else(|| {1507 properties1508 .into_iter()1509 .map(|(key, value)| Property { key, value })1510 .collect()1511 });15121513 Ok(properties)1514 }15151516 /// Get property permissions according to given keys.1517 pub fn filter_property_permissions(1518 collection_id: CollectionId,1519 keys: Option<Vec<PropertyKey>>,1520 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1521 let permissions = Self::property_permissions(collection_id);15221523 let key_permissions = keys1524 .map(|keys| {1525 keys.into_iter()1526 .filter_map(|key| {1527 permissions1528 .get(&key)1529 .map(|permission| PropertyKeyPermission {1530 key,1531 permission: permission.clone(),1532 })1533 })1534 .collect()1535 })1536 .unwrap_or_else(|| {1537 permissions1538 .into_iter()1539 .map(|(key, permission)| PropertyKeyPermission { key, permission })1540 .collect()1541 });15421543 Ok(key_permissions)1544 }15451546 /// Toggle `user` participation in the `collection`'s allow list.1547 /// #### Store read/writes1548 /// 1 writes1549 pub fn toggle_allowlist(1550 collection: &CollectionHandle<T>,1551 sender: &T::CrossAccountId,1552 user: &T::CrossAccountId,1553 allowed: bool,1554 ) -> DispatchResult {1555 collection.check_is_owner_or_admin(sender)?;15561557 // =========15581559 if allowed {1560 <Allowlist<T>>::insert((collection.id, user), true);1561 Self::deposit_event(Event::<T>::AllowListAddressAdded(1562 collection.id,1563 user.clone(),1564 ));1565 } else {1566 <Allowlist<T>>::remove((collection.id, user));1567 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1568 collection.id,1569 user.clone(),1570 ));1571 }15721573 <PalletEvm<T>>::deposit_log(1574 erc::CollectionHelpersEvents::CollectionChanged {1575 collection_id: eth::collection_id_to_address(collection.id),1576 }1577 .to_log(T::ContractAddress::get()),1578 );15791580 Ok(())1581 }15821583 /// Toggle `user` participation in the `collection`'s admin list.1584 /// #### Store read/writes1585 /// 2 reads, 2 writes1586 pub fn toggle_admin(1587 collection: &CollectionHandle<T>,1588 sender: &T::CrossAccountId,1589 user: &T::CrossAccountId,1590 admin: bool,1591 ) -> DispatchResult {1592 collection.check_is_internal()?;1593 collection.check_is_owner(sender)?;15941595 let is_admin = <IsAdmin<T>>::get((collection.id, user));1596 if is_admin == admin {1597 if admin {1598 return Ok(());1599 } else {1600 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1601 }1602 }1603 let amount = <AdminAmount<T>>::get(collection.id);16041605 // =========16061607 if admin {1608 let amount = amount1609 .checked_add(1)1610 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1611 ensure!(1612 amount <= Self::collection_admins_limit(),1613 <Error<T>>::CollectionAdminCountExceeded,1614 );16151616 <AdminAmount<T>>::insert(collection.id, amount);1617 <IsAdmin<T>>::insert((collection.id, user), true);16181619 Self::deposit_event(Event::<T>::CollectionAdminAdded(1620 collection.id,1621 user.clone(),1622 ));1623 } else {1624 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1625 <IsAdmin<T>>::remove((collection.id, user));16261627 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1628 collection.id,1629 user.clone(),1630 ));1631 }16321633 <PalletEvm<T>>::deposit_log(1634 erc::CollectionHelpersEvents::CollectionChanged {1635 collection_id: eth::collection_id_to_address(collection.id),1636 }1637 .to_log(T::ContractAddress::get()),1638 );16391640 Ok(())1641 }16421643 /// Update collection limits.1644 pub fn update_limits(1645 user: &T::CrossAccountId,1646 collection: &mut CollectionHandle<T>,1647 new_limit: CollectionLimits,1648 ) -> DispatchResult {1649 collection.check_is_internal()?;1650 collection.check_is_owner_or_admin(user)?;16511652 collection.limits =1653 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16541655 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1656 <PalletEvm<T>>::deposit_log(1657 erc::CollectionHelpersEvents::CollectionChanged {1658 collection_id: eth::collection_id_to_address(collection.id),1659 }1660 .to_log(T::ContractAddress::get()),1661 );16621663 collection.save()1664 }16651666 /// Merge set fields from `new_limit` to `old_limit`.1667 fn clamp_limits(1668 mode: CollectionMode,1669 old_limit: &CollectionLimits,1670 mut new_limit: CollectionLimits,1671 ) -> Result<CollectionLimits, DispatchError> {1672 let limits = old_limit;1673 limit_default!(old_limit, new_limit,1674 account_token_ownership_limit => ensure!(1675 new_limit <= MAX_TOKEN_OWNERSHIP,1676 <Error<T>>::CollectionLimitBoundsExceeded,1677 ),1678 sponsored_data_size => ensure!(1679 new_limit <= CUSTOM_DATA_LIMIT,1680 <Error<T>>::CollectionLimitBoundsExceeded,1681 ),16821683 sponsored_data_rate_limit => {},1684 token_limit => ensure!(1685 old_limit >= new_limit && new_limit > 0,1686 <Error<T>>::CollectionTokenLimitExceeded1687 ),16881689 sponsor_transfer_timeout(match mode {1690 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1691 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1692 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1693 }) => ensure!(1694 new_limit <= MAX_SPONSOR_TIMEOUT,1695 <Error<T>>::CollectionLimitBoundsExceeded,1696 ),1697 sponsor_approve_timeout => {},1698 owner_can_transfer => ensure!(1699 !limits.owner_can_transfer_instaled() ||1700 old_limit || !new_limit,1701 <Error<T>>::OwnerPermissionsCantBeReverted,1702 ),1703 owner_can_destroy => ensure!(1704 old_limit || !new_limit,1705 <Error<T>>::OwnerPermissionsCantBeReverted,1706 ),1707 transfers_enabled => {},1708 );1709 Ok(new_limit)1710 }17111712 /// Update collection permissions.1713 pub fn update_permissions(1714 user: &T::CrossAccountId,1715 collection: &mut CollectionHandle<T>,1716 new_permission: CollectionPermissions,1717 ) -> DispatchResult {1718 collection.check_is_internal()?;1719 collection.check_is_owner_or_admin(user)?;1720 collection.permissions = Self::clamp_permissions(1721 collection.mode.clone(),1722 &collection.permissions,1723 new_permission,1724 )?;17251726 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1727 <PalletEvm<T>>::deposit_log(1728 erc::CollectionHelpersEvents::CollectionChanged {1729 collection_id: eth::collection_id_to_address(collection.id),1730 }1731 .to_log(T::ContractAddress::get()),1732 );17331734 collection.save()1735 }17361737 /// Merge set fields from `new_permission` to `old_permission`.1738 fn clamp_permissions(1739 _mode: CollectionMode,1740 old_permission: &CollectionPermissions,1741 mut new_permission: CollectionPermissions,1742 ) -> Result<CollectionPermissions, DispatchError> {1743 limit_default_clone!(old_permission, new_permission,1744 access => {},1745 mint_mode => {},1746 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1747 );1748 Ok(new_permission)1749 }17501751 /// Repair possibly broken properties of a collection.1752 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1753 CollectionProperties::<T>::mutate(collection_id, |properties| {1754 properties.recompute_consumed_space();1755 });17561757 Ok(())1758 }1759}17601761/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1762#[macro_export]1763macro_rules! unsupported {1764 ($runtime:path) => {1765 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1766 };1767}17681769/// Return weights for various worst-case operations.1770pub trait CommonWeightInfo<CrossAccountId> {1771 /// Weight of item creation.1772 fn create_item() -> Weight;17731774 /// Weight of items creation.1775 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17761777 /// Weight of items creation.1778 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17791780 /// The weight of the burning item.1781 fn burn_item() -> Weight;17821783 /// Property setting weight.1784 ///1785 /// * `amount`- The number of properties to set.1786 fn set_collection_properties(amount: u32) -> Weight;17871788 /// Collection property deletion weight.1789 ///1790 /// * `amount`- The number of properties to set.1791 fn delete_collection_properties(amount: u32) -> Weight;17921793 /// Token property setting weight.1794 ///1795 /// * `amount`- The number of properties to set.1796 fn set_token_properties(amount: u32) -> Weight;17971798 /// Token property deletion weight.1799 ///1800 /// * `amount`- The number of properties to delete.1801 fn delete_token_properties(amount: u32) -> Weight;18021803 /// Token property permissions set weight.1804 ///1805 /// * `amount`- The number of property permissions to set.1806 fn set_token_property_permissions(amount: u32) -> Weight;18071808 /// Transfer price of the token or its parts.1809 fn transfer() -> Weight;18101811 /// The price of setting the permission of the operation from another user.1812 fn approve() -> Weight;18131814 /// The price of setting the permission of the operation from another user for eth mirror.1815 fn approve_from() -> Weight;18161817 /// Transfer price from another user.1818 fn transfer_from() -> Weight;18191820 /// The price of burning a token from another user.1821 fn burn_from() -> Weight;18221823 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1824 /// whole users's balance.1825 ///1826 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1827 fn burn_recursively_self_raw() -> Weight;18281829 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1830 ///1831 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1832 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18331834 /// The price of recursive burning a token.1835 ///1836 /// `max_selfs` - The maximum burning weight of the token itself.1837 /// `max_breadth` - The maximum number of nested tokens to burn.1838 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1839 Self::burn_recursively_self_raw()1840 .saturating_mul(max_selfs.max(1) as u64)1841 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1842 }18431844 /// The price of retrieving token owner1845 fn token_owner() -> Weight;18461847 /// The price of setting approval for all1848 fn set_allowance_for_all() -> Weight;18491850 /// The price of repairing an item.1851 fn force_repair_item() -> Weight;1852}18531854/// Weight info extension trait for refungible pallet.1855pub trait RefungibleExtensionsWeightInfo {1856 /// Weight of token repartition.1857 fn repartition() -> Weight;1858}18591860/// Common collection operations.1861///1862/// It wraps methods in Fungible, Nonfungible and Refungible pallets1863/// and adds weight info.1864pub trait CommonCollectionOperations<T: Config> {1865 /// Create token.1866 ///1867 /// * `sender` - The user who mint the token and pays for the transaction.1868 /// * `to` - The user who will own the token.1869 /// * `data` - Token data.1870 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1871 fn create_item(1872 &self,1873 sender: T::CrossAccountId,1874 to: T::CrossAccountId,1875 data: CreateItemData,1876 nesting_budget: &dyn Budget,1877 ) -> DispatchResultWithPostInfo;18781879 /// Create multiple tokens.1880 ///1881 /// * `sender` - The user who mint the token and pays for the transaction.1882 /// * `to` - The user who will own the token.1883 /// * `data` - Token data.1884 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1885 fn create_multiple_items(1886 &self,1887 sender: T::CrossAccountId,1888 to: T::CrossAccountId,1889 data: Vec<CreateItemData>,1890 nesting_budget: &dyn Budget,1891 ) -> DispatchResultWithPostInfo;18921893 /// Create multiple tokens.1894 ///1895 /// * `sender` - The user who mint the token and pays for the transaction.1896 /// * `to` - The user who will own the token.1897 /// * `data` - Token data.1898 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1899 fn create_multiple_items_ex(1900 &self,1901 sender: T::CrossAccountId,1902 data: CreateItemExData<T::CrossAccountId>,1903 nesting_budget: &dyn Budget,1904 ) -> DispatchResultWithPostInfo;19051906 /// Burn token.1907 ///1908 /// * `sender` - The user who owns the token.1909 /// * `token` - Token id that will burned.1910 /// * `amount` - The number of parts of the token that will be burned.1911 fn burn_item(1912 &self,1913 sender: T::CrossAccountId,1914 token: TokenId,1915 amount: u128,1916 ) -> DispatchResultWithPostInfo;19171918 /// Burn token and all nested tokens recursievly.1919 ///1920 /// * `sender` - The user who owns the token.1921 /// * `token` - Token id that will burned.1922 /// * `self_budget` - The budget that can be spent on burning tokens.1923 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1924 fn burn_item_recursively(1925 &self,1926 sender: T::CrossAccountId,1927 token: TokenId,1928 self_budget: &dyn Budget,1929 breadth_budget: &dyn Budget,1930 ) -> DispatchResultWithPostInfo;19311932 /// Set collection properties.1933 ///1934 /// * `sender` - Must be either the owner of the collection or its admin.1935 /// * `properties` - Properties to be set.1936 fn set_collection_properties(1937 &self,1938 sender: T::CrossAccountId,1939 properties: Vec<Property>,1940 ) -> DispatchResultWithPostInfo;19411942 /// Delete collection properties.1943 ///1944 /// * `sender` - Must be either the owner of the collection or its admin.1945 /// * `properties` - The properties to be removed.1946 fn delete_collection_properties(1947 &self,1948 sender: &T::CrossAccountId,1949 property_keys: Vec<PropertyKey>,1950 ) -> DispatchResultWithPostInfo;19511952 /// Set token properties.1953 ///1954 /// The appropriate [`PropertyPermission`] for the token property1955 /// must be set with [`Self::set_token_property_permissions`].1956 ///1957 /// * `sender` - Must be either the owner of the token or its admin.1958 /// * `token_id` - The token for which the properties are being set.1959 /// * `properties` - Properties to be set.1960 /// * `budget` - Budget for setting properties.1961 fn set_token_properties(1962 &self,1963 sender: T::CrossAccountId,1964 token_id: TokenId,1965 properties: Vec<Property>,1966 budget: &dyn Budget,1967 ) -> DispatchResultWithPostInfo;19681969 /// Remove token properties.1970 ///1971 /// The appropriate [`PropertyPermission`] for the token property1972 /// must be set with [`Self::set_token_property_permissions`].1973 ///1974 /// * `sender` - Must be either the owner of the token or its admin.1975 /// * `token_id` - The token for which the properties are being remove.1976 /// * `property_keys` - Keys to remove corresponding properties.1977 /// * `budget` - Budget for removing properties.1978 fn delete_token_properties(1979 &self,1980 sender: T::CrossAccountId,1981 token_id: TokenId,1982 property_keys: Vec<PropertyKey>,1983 budget: &dyn Budget,1984 ) -> DispatchResultWithPostInfo;19851986 /// Set token property permissions.1987 ///1988 /// * `sender` - Must be either the owner of the token or its admin.1989 /// * `token_id` - The token for which the properties are being set.1990 /// * `property_permissions` - Property permissions to be set.1991 /// * `budget` - Budget for setting properties.1992 fn set_token_property_permissions(1993 &self,1994 sender: &T::CrossAccountId,1995 property_permissions: Vec<PropertyKeyPermission>,1996 ) -> DispatchResultWithPostInfo;19971998 /// Transfer amount of token pieces.1999 ///2000 /// * `sender` - Donor user.2001 /// * `to` - Recepient user.2002 /// * `token` - The token of which parts are being sent.2003 /// * `amount` - The number of parts of the token that will be transferred.2004 /// * `budget` - The maximum budget that can be spent on the transfer.2005 fn transfer(2006 &self,2007 sender: T::CrossAccountId,2008 to: T::CrossAccountId,2009 token: TokenId,2010 amount: u128,2011 budget: &dyn Budget,2012 ) -> DispatchResultWithPostInfo;20132014 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2015 ///2016 /// * `sender` - The user who grants access to the token.2017 /// * `spender` - The user to whom the rights are granted.2018 /// * `token` - The token to which access is granted.2019 /// * `amount` - The amount of pieces that another user can dispose of.2020 fn approve(2021 &self,2022 sender: T::CrossAccountId,2023 spender: T::CrossAccountId,2024 token: TokenId,2025 amount: u128,2026 ) -> DispatchResultWithPostInfo;20272028 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2029 ///2030 /// * `sender` - The user who grants access to the token.2031 /// * `from` - Spender's eth mirror.2032 /// * `to` - The user to whom the rights are granted.2033 /// * `token` - The token to which access is granted.2034 /// * `amount` - The amount of pieces that another user can dispose of.2035 fn approve_from(2036 &self,2037 sender: T::CrossAccountId,2038 from: T::CrossAccountId,2039 to: T::CrossAccountId,2040 token: TokenId,2041 amount: u128,2042 ) -> DispatchResultWithPostInfo;20432044 /// Send parts of a token owned by another user.2045 ///2046 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2047 ///2048 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2049 /// * `from` - The user who owns the token.2050 /// * `to` - Recepient user.2051 /// * `token` - The token of which parts are being sent.2052 /// * `amount` - The number of parts of the token that will be transferred.2053 /// * `budget` - The maximum budget that can be spent on the transfer.2054 fn transfer_from(2055 &self,2056 sender: T::CrossAccountId,2057 from: T::CrossAccountId,2058 to: T::CrossAccountId,2059 token: TokenId,2060 amount: u128,2061 budget: &dyn Budget,2062 ) -> DispatchResultWithPostInfo;20632064 /// Burn parts of a token owned by another user.2065 ///2066 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2067 ///2068 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2069 /// * `from` - The user who owns the token.2070 /// * `token` - The token of which parts are being sent.2071 /// * `amount` - The number of parts of the token that will be transferred.2072 /// * `budget` - The maximum budget that can be spent on the burn.2073 fn burn_from(2074 &self,2075 sender: T::CrossAccountId,2076 from: T::CrossAccountId,2077 token: TokenId,2078 amount: u128,2079 budget: &dyn Budget,2080 ) -> DispatchResultWithPostInfo;20812082 /// Check permission to nest token.2083 ///2084 /// * `sender` - The user who initiated the check.2085 /// * `from` - The token that is checked for embedding.2086 /// * `under` - Token under which to check.2087 /// * `budget` - The maximum budget that can be spent on the check.2088 fn check_nesting(2089 &self,2090 sender: T::CrossAccountId,2091 from: (CollectionId, TokenId),2092 under: TokenId,2093 budget: &dyn Budget,2094 ) -> DispatchResult;20952096 /// Nest one token into another.2097 ///2098 /// * `under` - Token holder.2099 /// * `to_nest` - Nested token.2100 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21012102 /// Unnest token.2103 ///2104 /// * `under` - Token holder.2105 /// * `to_nest` - Token to unnest.2106 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21072108 /// Get all user tokens.2109 ///2110 /// * `account` - Account for which you need to get tokens.2111 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;21122113 /// Get all the tokens in the collection.2114 fn collection_tokens(&self) -> Vec<TokenId>;21152116 /// Check if the token exists.2117 ///2118 /// * `token` - Id token to check.2119 fn token_exists(&self, token: TokenId) -> bool;21202121 /// Get the id of the last minted token.2122 fn last_token_id(&self) -> TokenId;21232124 /// Get the owner of the token.2125 ///2126 /// * `token` - The token for which you need to find out the owner.2127 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;21282129 /// Returns 10 tokens owners in no particular order.2130 ///2131 /// * `token` - The token for which you need to find out the owners.2132 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21332134 /// Get the value of the token property by key.2135 ///2136 /// * `token` - Token with the property to get.2137 /// * `key` - Property name.2138 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21392140 /// Get a set of token properties by key vector.2141 ///2142 /// * `token` - Token with the property to get.2143 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2144 /// then all properties are returned.2145 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21462147 /// Amount of unique collection tokens2148 fn total_supply(&self) -> u32;21492150 /// Amount of different tokens account has.2151 ///2152 /// * `account` - The account for which need to get the balance.2153 fn account_balance(&self, account: T::CrossAccountId) -> u32;21542155 /// Amount of specific token account have.2156 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21572158 /// Amount of token pieces2159 fn total_pieces(&self, token: TokenId) -> Option<u128>;21602161 /// Get the number of parts of the token that a trusted user can manage.2162 ///2163 /// * `sender` - Trusted user.2164 /// * `spender` - Owner of the token.2165 /// * `token` - The token for which to get the value.2166 fn allowance(2167 &self,2168 sender: T::CrossAccountId,2169 spender: T::CrossAccountId,2170 token: TokenId,2171 ) -> u128;21722173 /// Get extension for RFT collection.2174 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21752176 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2177 /// * `owner` - Token owner2178 /// * `operator` - Operator2179 /// * `approve` - Should operator status be granted or revoked?2180 fn set_allowance_for_all(2181 &self,2182 owner: T::CrossAccountId,2183 operator: T::CrossAccountId,2184 approve: bool,2185 ) -> DispatchResultWithPostInfo;21862187 /// Tells whether the given `owner` approves the `operator`.2188 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21892190 /// Repairs a possibly broken item.2191 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2192}21932194/// Extension for RFT collection.2195pub trait RefungibleExtensions<T>2196where2197 T: Config,2198{2199 /// Change the number of parts of the token.2200 ///2201 /// When the value changes down, this function is equivalent to burning parts of the token.2202 ///2203 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2204 /// * `token` - The token for which you want to change the number of parts.2205 /// * `amount` - The new value of the parts of the token.2206 fn repartition(2207 &self,2208 sender: &T::CrossAccountId,2209 token: TokenId,2210 amount: u128,2211 ) -> DispatchResultWithPostInfo;2212}22132214/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2215///2216/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2217pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2218 let post_info = PostDispatchInfo {2219 actual_weight: Some(weight),2220 pays_fee: Pays::Yes,2221 };2222 match res {2223 Ok(()) => Ok(post_info),2224 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2225 }2226}22272228impl<T: Config> From<PropertiesError> for Error<T> {2229 fn from(error: PropertiesError) -> Self {2230 match error {2231 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2232 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2233 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2234 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2235 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2236 }2237 }2238}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118use up_pov_estimate_rpc::PovInfo;119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135///136/// CollectionHandle is used as a generic wrapper for collections of all types.137/// It allows to perform common operations and queries on any collection type,138/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].139#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]140pub struct CollectionHandle<T: Config> {141 /// Collection id142 pub id: CollectionId,143 collection: Collection<T::AccountId>,144 /// Substrate recorder for counting consumed gas145 pub recorder: SubstrateRecorder<T>,146}147148impl<T: Config> WithRecorder<T> for CollectionHandle<T> {149 fn recorder(&self) -> &SubstrateRecorder<T> {150 &self.recorder151 }152 fn into_recorder(self) -> SubstrateRecorder<T> {153 self.recorder154 }155}156157impl<T: Config> CollectionHandle<T> {158 /// Same as [CollectionHandle::new] but with an explicit gas limit.159 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {160 <CollectionById<T>>::get(id).map(|collection| Self {161 id,162 collection,163 recorder: SubstrateRecorder::new(gas_limit),164 })165 }166167 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].168 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {169 <CollectionById<T>>::get(id).map(|collection| Self {170 id,171 collection,172 recorder,173 })174 }175176 /// Retrives collection data from storage and creates collection handle with default parameters.177 /// If collection not found return `None`178 pub fn new(id: CollectionId) -> Option<Self> {179 Self::new_with_gas_limit(id, u64::MAX)180 }181182 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.183 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {184 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)185 }186187 /// Consume gas for reading.188 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 <T as frame_system::Config>::DbWeight::get()192 .read193 .saturating_mul(reads),194 )))195 }196197 /// Consume gas for writing.198 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199 self.recorder200 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(201 <T as frame_system::Config>::DbWeight::get()202 .write203 .saturating_mul(writes),204 )))205 }206207 /// Consume gas for reading and writing.208 pub fn consume_store_reads_and_writes(209 &self,210 reads: u64,211 writes: u64,212 ) -> evm_coder::execution::Result<()> {213 let weight = <T as frame_system::Config>::DbWeight::get();214 let reads = weight.read.saturating_mul(reads);215 let writes = weight.read.saturating_mul(writes);216 self.recorder217 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(218 reads.saturating_add(writes),219 )))220 }221222 /// Save collection to storage.223 pub fn save(&self) -> DispatchResult {224 <CollectionById<T>>::insert(self.id, &self.collection);225 Ok(())226 }227228 /// Set collection sponsor.229 ///230 /// Unique collections allows sponsoring for certain actions.231 /// This method allows you to set the sponsor of the collection.232 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].233 pub fn set_sponsor(234 &mut self,235 sender: &T::CrossAccountId,236 sponsor: T::AccountId,237 ) -> DispatchResult {238 self.check_is_internal()?;239 self.check_is_owner_or_admin(sender)?;240241 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());242243 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));244 <PalletEvm<T>>::deposit_log(245 erc::CollectionHelpersEvents::CollectionChanged {246 collection_id: eth::collection_id_to_address(self.id),247 }248 .to_log(T::ContractAddress::get()),249 );250251 self.save()252 }253254 /// Force set `sponsor`.255 ///256 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation257 /// from the `sponsor` is not required.258 ///259 /// # Arguments260 ///261 /// * `sender`: Caller's account.262 /// * `sponsor`: ID of the account of the sponsor-to-be.263 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {264 self.check_is_internal()?;265266 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());267268 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));269 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));270 <PalletEvm<T>>::deposit_log(271 erc::CollectionHelpersEvents::CollectionChanged {272 collection_id: eth::collection_id_to_address(self.id),273 }274 .to_log(T::ContractAddress::get()),275 );276277 self.save()278 }279280 /// Confirm sponsorship281 ///282 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.283 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].284 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {285 self.check_is_internal()?;286 ensure!(287 self.collection.sponsorship.pending_sponsor() == Some(sender),288 Error::<T>::ConfirmSponsorshipFail289 );290291 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());292293 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));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 );300301 self.save()302 }303304 /// Remove collection sponsor.305 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {306 self.check_is_internal()?;307 self.check_is_owner_or_admin(sender)?;308309 self.collection.sponsorship = SponsorshipState::Disabled;310311 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));312 <PalletEvm<T>>::deposit_log(313 erc::CollectionHelpersEvents::CollectionChanged {314 collection_id: eth::collection_id_to_address(self.id),315 }316 .to_log(T::ContractAddress::get()),317 );318 self.save()319 }320321 /// Force remove `sponsor`.322 ///323 /// Differs from `remove_sponsor` in that324 /// it doesn't require consent from the `owner` of the collection.325 pub fn force_remove_sponsor(&mut self) -> DispatchResult {326 self.check_is_internal()?;327328 self.collection.sponsorship = SponsorshipState::Disabled;329330 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));331 <PalletEvm<T>>::deposit_log(332 erc::CollectionHelpersEvents::CollectionChanged {333 collection_id: eth::collection_id_to_address(self.id),334 }335 .to_log(T::ContractAddress::get()),336 );337 self.save()338 }339340 /// Checks that the collection was created with, and must be operated upon through **Unique API**.341 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.342 pub fn check_is_internal(&self) -> DispatchResult {343 if self.flags.external {344 return Err(<Error<T>>::CollectionIsExternal)?;345 }346347 Ok(())348 }349350 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.351 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.352 pub fn check_is_external(&self) -> DispatchResult {353 if !self.flags.external {354 return Err(<Error<T>>::CollectionIsInternal)?;355 }356357 Ok(())358 }359}360361impl<T: Config> Deref for CollectionHandle<T> {362 type Target = Collection<T::AccountId>;363364 fn deref(&self) -> &Self::Target {365 &self.collection366 }367}368369impl<T: Config> DerefMut for CollectionHandle<T> {370 fn deref_mut(&mut self) -> &mut Self::Target {371 &mut self.collection372 }373}374375impl<T: Config> CollectionHandle<T> {376 /// Checks if the `user` is the owner of the collection.377 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {378 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);379 Ok(())380 }381382 /// Returns **true** if the `user` is the owner or administrator of the collection.383 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {384 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))385 }386387 /// Checks if the `user` is the owner or administrator of the collection.388 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {389 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);390 Ok(())391 }392393 /// Returns **true** if394 /// * the `user`is a collection owner or admin395 /// * the collection limits allow the owner/admins to transfer/burn any collection token396 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {397 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)398 }399400 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.401 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {402 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)403 }404405 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.406 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {407 ensure!(408 <Allowlist<T>>::get((self.id, user)),409 <Error<T>>::AddressNotInAllowlist410 );411 Ok(())412 }413414 /// Changes collection owner to another account415 /// #### Store read/writes416 /// 1 writes417 pub fn change_owner(418 &mut self,419 caller: T::CrossAccountId,420 new_owner: T::CrossAccountId,421 ) -> DispatchResult {422 self.check_is_internal()?;423 self.check_is_owner(&caller)?;424 self.collection.owner = new_owner.as_sub().clone();425426 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(427 self.id,428 new_owner.as_sub().clone(),429 ));430 <PalletEvm<T>>::deposit_log(431 erc::CollectionHelpersEvents::CollectionChanged {432 collection_id: eth::collection_id_to_address(self.id),433 }434 .to_log(T::ContractAddress::get()),435 );436437 self.save()438 }439}440441#[frame_support::pallet]442pub mod pallet {443 use super::*;444 use dispatch::CollectionDispatch;445 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};446 use frame_system::pallet_prelude::*;447 use frame_support::traits::Currency;448 use up_data_structs::{TokenId, mapping::TokenAddressMapping};449 use scale_info::TypeInfo;450 use weights::WeightInfo;451452 #[pallet::config]453 pub trait Config:454 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo455 {456 /// Weight information for functions of this pallet.457 type WeightInfo: WeightInfo;458459 /// Events compatible with [`frame_system::Config::Event`].460 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;461462 /// Handler of accounts and payment.463 type Currency: Currency<Self::AccountId>;464465 /// Set price to create a collection.466 #[pallet::constant]467 type CollectionCreationPrice: Get<468 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,469 >;470471 /// Dispatcher of operations on collections.472 type CollectionDispatch: CollectionDispatch<Self>;473474 /// Account which holds the chain's treasury.475 type TreasuryAccountId: Get<Self::AccountId>;476477 /// Address under which the CollectionHelper contract would be available.478 #[pallet::constant]479 type ContractAddress: Get<H160>;480481 /// Mapper for token addresses to Ethereum addresses.482 type EvmTokenAddressMapping: TokenAddressMapping<H160>;483484 /// Mapper for token addresses to [`CrossAccountId`].485 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;486 }487488 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);489490 #[pallet::pallet]491 #[pallet::storage_version(STORAGE_VERSION)]492 #[pallet::generate_store(pub(super) trait Store)]493 pub struct Pallet<T>(_);494495 #[pallet::extra_constants]496 impl<T: Config> Pallet<T> {497 /// Maximum admins per collection.498 pub fn collection_admins_limit() -> u32 {499 COLLECTION_ADMINS_LIMIT500 }501 }502503 #[pallet::event]504 #[pallet::generate_deposit(pub fn deposit_event)]505 pub enum Event<T: Config> {506 /// New collection was created507 CollectionCreated(508 /// Globally unique identifier of newly created collection.509 CollectionId,510 /// [`CollectionMode`] converted into _u8_.511 u8,512 /// Collection owner.513 T::AccountId,514 ),515516 /// New collection was destroyed517 CollectionDestroyed(518 /// Globally unique identifier of collection.519 CollectionId,520 ),521522 /// New item was created.523 ItemCreated(524 /// Id of the collection where item was created.525 CollectionId,526 /// Id of an item. Unique within the collection.527 TokenId,528 /// Owner of newly created item529 T::CrossAccountId,530 /// Always 1 for NFT531 u128,532 ),533534 /// Collection item was burned.535 ItemDestroyed(536 /// Id of the collection where item was destroyed.537 CollectionId,538 /// Identifier of burned NFT.539 TokenId,540 /// Which user has destroyed its tokens.541 T::CrossAccountId,542 /// Amount of token pieces destroed. Always 1 for NFT.543 u128,544 ),545546 /// Item was transferred547 Transfer(548 /// Id of collection to which item is belong.549 CollectionId,550 /// Id of an item.551 TokenId,552 /// Original owner of item.553 T::CrossAccountId,554 /// New owner of item.555 T::CrossAccountId,556 /// Amount of token pieces transfered. Always 1 for NFT.557 u128,558 ),559560 /// Amount pieces of token owned by `sender` was approved for `spender`.561 Approved(562 /// Id of collection to which item is belong.563 CollectionId,564 /// Id of an item.565 TokenId,566 /// Original owner of item.567 T::CrossAccountId,568 /// Id for which the approval was granted.569 T::CrossAccountId,570 /// Amount of token pieces transfered. Always 1 for NFT.571 u128,572 ),573574 /// A `sender` approves operations on all owned tokens for `spender`.575 ApprovedForAll(576 /// Id of collection to which item is belong.577 CollectionId,578 /// Owner of a wallet.579 T::CrossAccountId,580 /// Id for which operator status was granted or rewoked.581 T::CrossAccountId,582 /// Is operator status granted or revoked?583 bool,584 ),585586 /// The colletion property has been added or edited.587 CollectionPropertySet(588 /// Id of collection to which property has been set.589 CollectionId,590 /// The property that was set.591 PropertyKey,592 ),593594 /// The property has been deleted.595 CollectionPropertyDeleted(596 /// Id of collection to which property has been deleted.597 CollectionId,598 /// The property that was deleted.599 PropertyKey,600 ),601602 /// The token property has been added or edited.603 TokenPropertySet(604 /// Identifier of the collection whose token has the property set.605 CollectionId,606 /// The token for which the property was set.607 TokenId,608 /// The property that was set.609 PropertyKey,610 ),611612 /// The token property has been deleted.613 TokenPropertyDeleted(614 /// Identifier of the collection whose token has the property deleted.615 CollectionId,616 /// The token for which the property was deleted.617 TokenId,618 /// The property that was deleted.619 PropertyKey,620 ),621622 /// The token property permission of a collection has been set.623 PropertyPermissionSet(624 /// ID of collection to which property permission has been set.625 CollectionId,626 /// The property permission that was set.627 PropertyKey,628 ),629630 /// Address was added to the allow list.631 AllowListAddressAdded(632 /// ID of the affected collection.633 CollectionId,634 /// Address of the added account.635 T::CrossAccountId,636 ),637638 /// Address was removed from the allow list.639 AllowListAddressRemoved(640 /// ID of the affected collection.641 CollectionId,642 /// Address of the removed account.643 T::CrossAccountId,644 ),645646 /// Collection admin was added.647 CollectionAdminAdded(648 /// ID of the affected collection.649 CollectionId,650 /// Admin address.651 T::CrossAccountId,652 ),653654 /// Collection admin was removed.655 CollectionAdminRemoved(656 /// ID of the affected collection.657 CollectionId,658 /// Removed admin address.659 T::CrossAccountId,660 ),661662 /// Collection limits were set.663 CollectionLimitSet(664 /// ID of the affected collection.665 CollectionId,666 ),667668 /// Collection owned was changed.669 CollectionOwnerChanged(670 /// ID of the affected collection.671 CollectionId,672 /// New owner address.673 T::AccountId,674 ),675676 /// Collection permissions were set.677 CollectionPermissionSet(678 /// ID of the affected collection.679 CollectionId,680 ),681682 /// Collection sponsor was set.683 CollectionSponsorSet(684 /// ID of the affected collection.685 CollectionId,686 /// New sponsor address.687 T::AccountId,688 ),689690 /// New sponsor was confirm.691 SponsorshipConfirmed(692 /// ID of the affected collection.693 CollectionId,694 /// New sponsor address.695 T::AccountId,696 ),697698 /// Collection sponsor was removed.699 CollectionSponsorRemoved(700 /// ID of the affected collection.701 CollectionId,702 ),703 }704705 #[pallet::error]706 pub enum Error<T> {707 /// This collection does not exist.708 CollectionNotFound,709 /// Sender parameter and item owner must be equal.710 MustBeTokenOwner,711 /// No permission to perform action712 NoPermission,713 /// Destroying only empty collections is allowed714 CantDestroyNotEmptyCollection,715 /// Collection is not in mint mode.716 PublicMintingNotAllowed,717 /// Address is not in allow list.718 AddressNotInAllowlist,719720 /// Collection name can not be longer than 63 char.721 CollectionNameLimitExceeded,722 /// Collection description can not be longer than 255 char.723 CollectionDescriptionLimitExceeded,724 /// Token prefix can not be longer than 15 char.725 CollectionTokenPrefixLimitExceeded,726 /// Total collections bound exceeded.727 TotalCollectionsLimitExceeded,728 /// Exceeded max admin count729 CollectionAdminCountExceeded,730 /// Collection limit bounds per collection exceeded731 CollectionLimitBoundsExceeded,732 /// Tried to enable permissions which are only permitted to be disabled733 OwnerPermissionsCantBeReverted,734 /// Collection settings not allowing items transferring735 TransferNotAllowed,736 /// Account token limit exceeded per collection737 AccountTokenLimitExceeded,738 /// Collection token limit exceeded739 CollectionTokenLimitExceeded,740 /// Metadata flag frozen741 MetadataFlagFrozen,742743 /// Item does not exist744 TokenNotFound,745 /// Item is balance not enough746 TokenValueTooLow,747 /// Requested value is more than the approved748 ApprovedValueTooLow,749 /// Tried to approve more than owned750 CantApproveMoreThanOwned,751 /// Only spending from eth mirror could be approved752 AddressIsNotEthMirror,753754 /// Can't transfer tokens to ethereum zero address755 AddressIsZero,756757 /// The operation is not supported758 UnsupportedOperation,759760 /// Insufficient funds to perform an action761 NotSufficientFounds,762763 /// User does not satisfy the nesting rule764 UserIsNotAllowedToNest,765 /// Only tokens from specific collections may nest tokens under this one766 SourceCollectionIsNotAllowedToNest,767768 /// Tried to store more data than allowed in collection field769 CollectionFieldSizeExceeded,770771 /// Tried to store more property data than allowed772 NoSpaceForProperty,773774 /// Tried to store more property keys than allowed775 PropertyLimitReached,776777 /// Property key is too long778 PropertyKeyIsTooLong,779780 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed781 InvalidCharacterInPropertyKey,782783 /// Empty property keys are forbidden784 EmptyPropertyKey,785786 /// Tried to access an external collection with an internal API787 CollectionIsExternal,788789 /// Tried to access an internal collection with an external API790 CollectionIsInternal,791792 /// This address is not set as sponsor, use setCollectionSponsor first.793 ConfirmSponsorshipFail,794795 /// The user is not an administrator.796 UserIsNotCollectionAdmin,797 }798799 /// Storage of the count of created collections. Essentially contains the last collection ID.800 #[pallet::storage]801 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;802803 /// Storage of the count of deleted collections.804 #[pallet::storage]805 pub type DestroyedCollectionCount<T> =806 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;807808 /// Storage of collection info.809 #[pallet::storage]810 pub type CollectionById<T> = StorageMap<811 Hasher = Blake2_128Concat,812 Key = CollectionId,813 Value = Collection<<T as frame_system::Config>::AccountId>,814 QueryKind = OptionQuery,815 >;816817 /// Storage of collection properties.818 #[pallet::storage]819 #[pallet::getter(fn collection_properties)]820 pub type CollectionProperties<T> = StorageMap<821 Hasher = Blake2_128Concat,822 Key = CollectionId,823 Value = Properties,824 QueryKind = ValueQuery,825 OnEmpty = up_data_structs::CollectionProperties,826 >;827828 /// Storage of token property permissions of a collection.829 #[pallet::storage]830 #[pallet::getter(fn property_permissions)]831 pub type CollectionPropertyPermissions<T> = StorageMap<832 Hasher = Blake2_128Concat,833 Key = CollectionId,834 Value = PropertiesPermissionMap,835 QueryKind = ValueQuery,836 >;837838 /// Storage of the amount of collection admins.839 #[pallet::storage]840 pub type AdminAmount<T> = StorageMap<841 Hasher = Blake2_128Concat,842 Key = CollectionId,843 Value = u32,844 QueryKind = ValueQuery,845 >;846847 /// List of collection admins.848 #[pallet::storage]849 pub type IsAdmin<T: Config> = StorageNMap<850 Key = (851 Key<Blake2_128Concat, CollectionId>,852 Key<Blake2_128Concat, T::CrossAccountId>,853 ),854 Value = bool,855 QueryKind = ValueQuery,856 >;857858 /// Allowlisted collection users.859 #[pallet::storage]860 pub type Allowlist<T: Config> = StorageNMap<861 Key = (862 Key<Blake2_128Concat, CollectionId>,863 Key<Blake2_128Concat, T::CrossAccountId>,864 ),865 Value = bool,866 QueryKind = ValueQuery,867 >;868869 /// Not used by code, exists only to provide some types to metadata.870 #[pallet::storage]871 pub type DummyStorageValue<T: Config> = StorageValue<872 Value = (873 CollectionStats,874 CollectionId,875 TokenId,876 TokenChild,877 PhantomType<(878 TokenData<T::CrossAccountId>,879 RpcCollection<T::AccountId>,880 // RMRK881 RmrkCollectionInfo<T::AccountId>,882 RmrkInstanceInfo<T::AccountId>,883 RmrkResourceInfo,884 RmrkPropertyInfo,885 RmrkBaseInfo<T::AccountId>,886 RmrkPartType,887 RmrkBoundedTheme,888 RmrkNftChild,889 // PoV Estimate Info890 PovInfo,891 )>,892 ),893 QueryKind = OptionQuery,894 >;895896 #[pallet::hooks]897 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {898 fn on_runtime_upgrade() -> Weight {899 StorageVersion::new(1).put::<Pallet<T>>();900901 Weight::zero()902 }903 }904}905906impl<T: Config> Pallet<T> {907 /// Enshure that receiver address is correct.908 ///909 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.910 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {911 ensure!(912 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,913 <Error<T>>::AddressIsZero914 );915 Ok(())916 }917918 /// Get a vector of collection admins.919 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {920 <IsAdmin<T>>::iter_prefix((collection,))921 .map(|(a, _)| a)922 .collect()923 }924925 /// Get a vector of users allowed to mint tokens.926 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {927 <Allowlist<T>>::iter_prefix((collection,))928 .map(|(a, _)| a)929 .collect()930 }931932 /// Is `user` allowed to mint token in `collection`.933 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {934 <Allowlist<T>>::get((collection, user))935 }936937 /// Get statistics of collections.938 pub fn collection_stats() -> CollectionStats {939 let created = <CreatedCollectionCount<T>>::get();940 let destroyed = <DestroyedCollectionCount<T>>::get();941 CollectionStats {942 created: created.0,943 destroyed: destroyed.0,944 alive: created.0 - destroyed.0,945 }946 }947948 /// Get the effective limits for the collection.949 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {950 let collection = <CollectionById<T>>::get(collection)?;951 let limits = collection.limits;952 let effective_limits = CollectionLimits {953 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),954 sponsored_data_size: Some(limits.sponsored_data_size()),955 sponsored_data_rate_limit: Some(956 limits957 .sponsored_data_rate_limit958 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),959 ),960 token_limit: Some(limits.token_limit()),961 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(962 match collection.mode {963 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,964 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,965 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,966 },967 )),968 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),969 owner_can_transfer: Some(limits.owner_can_transfer()),970 owner_can_destroy: Some(limits.owner_can_destroy()),971 transfers_enabled: Some(limits.transfers_enabled()),972 };973974 Some(effective_limits)975 }976977 /// Returns information about the `collection` adapted for rpc.978 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {979 let Collection {980 name,981 description,982 owner,983 mode,984 token_prefix,985 sponsorship,986 limits,987 permissions,988 flags,989 } = <CollectionById<T>>::get(collection)?;990991 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)992 .into_iter()993 .map(|(key, permission)| PropertyKeyPermission { key, permission })994 .collect();995996 let properties = <CollectionProperties<T>>::get(collection)997 .into_iter()998 .map(|(key, value)| Property { key, value })999 .collect();10001001 let permissions = CollectionPermissions {1002 access: Some(permissions.access()),1003 mint_mode: Some(permissions.mint_mode()),1004 nesting: Some(permissions.nesting().clone()),1005 };10061007 Some(RpcCollection {1008 name: name.into_inner(),1009 description: description.into_inner(),1010 owner,1011 mode,1012 token_prefix: token_prefix.into_inner(),1013 sponsorship,1014 limits,1015 permissions,1016 token_property_permissions,1017 properties,1018 read_only: flags.external,10191020 flags: RpcCollectionFlags {1021 foreign: flags.foreign,1022 erc721metadata: flags.erc721metadata,1023 },1024 })1025 }1026}10271028macro_rules! limit_default {1029 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1030 $(1031 if let Some($new) = $new.$field {1032 let $old = $old.$field($($arg)?);1033 let _ = $new;1034 let _ = $old;1035 $check1036 } else {1037 $new.$field = $old.$field1038 }1039 )*1040 }};1041}1042macro_rules! limit_default_clone {1043 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1044 $(1045 if let Some($new) = $new.$field.clone() {1046 let $old = $old.$field($($arg)?);1047 let _ = $new;1048 let _ = $old;1049 $check1050 } else {1051 $new.$field = $old.$field.clone()1052 }1053 )*1054 }};1055}10561057impl<T: Config> Pallet<T> {1058 /// Create new collection.1059 ///1060 /// * `owner` - The owner of the collection.1061 /// * `data` - Description of the created collection.1062 /// * `flags` - Extra flags to store.1063 pub fn init_collection(1064 owner: T::CrossAccountId,1065 payer: T::CrossAccountId,1066 data: CreateCollectionData<T::AccountId>,1067 flags: CollectionFlags,1068 ) -> Result<CollectionId, DispatchError> {1069 {1070 ensure!(1071 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1072 Error::<T>::CollectionTokenPrefixLimitExceeded1073 );1074 }10751076 let created_count = <CreatedCollectionCount<T>>::get()1077 .01078 .checked_add(1)1079 .ok_or(ArithmeticError::Overflow)?;1080 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1081 let id = CollectionId(created_count);10821083 // bound Total number of collections1084 ensure!(1085 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1086 <Error<T>>::TotalCollectionsLimitExceeded1087 );10881089 // =========10901091 let collection = Collection {1092 owner: owner.as_sub().clone(),1093 name: data.name,1094 mode: data.mode.clone(),1095 description: data.description,1096 token_prefix: data.token_prefix,1097 sponsorship: data1098 .pending_sponsor1099 .map(SponsorshipState::Unconfirmed)1100 .unwrap_or_default(),1101 limits: data1102 .limits1103 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1104 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1105 permissions: data1106 .permissions1107 .map(|permissions| {1108 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1109 })1110 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1111 flags,1112 };11131114 let mut collection_properties = up_data_structs::CollectionProperties::get();1115 collection_properties1116 .try_set_from_iter(data.properties.into_iter())1117 .map_err(<Error<T>>::from)?;11181119 CollectionProperties::<T>::insert(id, collection_properties);11201121 let mut token_props_permissions = PropertiesPermissionMap::new();1122 token_props_permissions1123 .try_set_from_iter(data.token_property_permissions.into_iter())1124 .map_err(<Error<T>>::from)?;11251126 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11271128 // Take a (non-refundable) deposit of collection creation1129 {1130 let mut imbalance =1131 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1132 imbalance.subsume(1133 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1134 &T::TreasuryAccountId::get(),1135 T::CollectionCreationPrice::get(),1136 ),1137 );1138 <T as Config>::Currency::settle(1139 payer.as_sub(),1140 imbalance,1141 WithdrawReasons::TRANSFER,1142 ExistenceRequirement::KeepAlive,1143 )1144 .map_err(|_| Error::<T>::NotSufficientFounds)?;1145 }11461147 <CreatedCollectionCount<T>>::put(created_count);1148 <Pallet<T>>::deposit_event(Event::CollectionCreated(1149 id,1150 data.mode.id(),1151 owner.as_sub().clone(),1152 ));1153 <PalletEvm<T>>::deposit_log(1154 erc::CollectionHelpersEvents::CollectionCreated {1155 owner: *owner.as_eth(),1156 collection_id: eth::collection_id_to_address(id),1157 }1158 .to_log(T::ContractAddress::get()),1159 );1160 <CollectionById<T>>::insert(id, collection);1161 Ok(id)1162 }11631164 /// Destroy collection.1165 ///1166 /// * `collection` - Collection handler.1167 /// * `sender` - The owner or administrator of the collection.1168 pub fn destroy_collection(1169 collection: CollectionHandle<T>,1170 sender: &T::CrossAccountId,1171 ) -> DispatchResult {1172 ensure!(1173 collection.limits.owner_can_destroy(),1174 <Error<T>>::NoPermission,1175 );1176 collection.check_is_owner(sender)?;11771178 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1179 .01180 .checked_add(1)1181 .ok_or(ArithmeticError::Overflow)?;11821183 // =========11841185 <DestroyedCollectionCount<T>>::put(destroyed_collections);1186 <CollectionById<T>>::remove(collection.id);1187 <AdminAmount<T>>::remove(collection.id);1188 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1189 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1190 <CollectionProperties<T>>::remove(collection.id);11911192 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11931194 <PalletEvm<T>>::deposit_log(1195 erc::CollectionHelpersEvents::CollectionDestroyed {1196 collection_id: eth::collection_id_to_address(collection.id),1197 }1198 .to_log(T::ContractAddress::get()),1199 );1200 Ok(())1201 }12021203 /// This function sets or removes a collection properties according to1204 /// `properties_updates` contents:1205 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1206 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1207 ///1208 /// This function fires an event for each property change.1209 /// In case of an error, all the changes (including the events) will be reverted1210 /// since the function is transactional.1211 #[transactional]1212 fn modify_collection_properties(1213 collection: &CollectionHandle<T>,1214 sender: &T::CrossAccountId,1215 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1216 ) -> DispatchResult {1217 collection.check_is_owner_or_admin(sender)?;12181219 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12201221 for (key, value) in properties_updates {1222 match value {1223 Some(value) => {1224 stored_properties1225 .try_set(key.clone(), value)1226 .map_err(<Error<T>>::from)?;12271228 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1229 <PalletEvm<T>>::deposit_log(1230 erc::CollectionHelpersEvents::CollectionChanged {1231 collection_id: eth::collection_id_to_address(collection.id),1232 }1233 .to_log(T::ContractAddress::get()),1234 );1235 }1236 None => {1237 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12381239 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1240 <PalletEvm<T>>::deposit_log(1241 erc::CollectionHelpersEvents::CollectionChanged {1242 collection_id: eth::collection_id_to_address(collection.id),1243 }1244 .to_log(T::ContractAddress::get()),1245 );1246 }1247 }1248 }12491250 <CollectionProperties<T>>::set(collection.id, stored_properties);12511252 Ok(())1253 }12541255 /// Set collection property.1256 ///1257 /// * `collection` - Collection handler.1258 /// * `sender` - The owner or administrator of the collection.1259 /// * `property` - The property to set.1260 pub fn set_collection_property(1261 collection: &CollectionHandle<T>,1262 sender: &T::CrossAccountId,1263 property: Property,1264 ) -> DispatchResult {1265 Self::set_collection_properties(collection, sender, [property].into_iter())1266 }12671268 /// Set a scoped collection property, where the scope is a special prefix1269 /// prohibiting a user access to change the property directly.1270 ///1271 /// * `collection_id` - ID of the collection for which the property is being set.1272 /// * `scope` - Property scope.1273 /// * `property` - The property to set.1274 pub fn set_scoped_collection_property(1275 collection_id: CollectionId,1276 scope: PropertyScope,1277 property: Property,1278 ) -> DispatchResult {1279 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1280 properties.try_scoped_set(scope, property.key, property.value)1281 })1282 .map_err(<Error<T>>::from)?;12831284 Ok(())1285 }12861287 /// Set scoped collection properties, where the scope is a special prefix1288 /// prohibiting a user access to change the properties directly.1289 ///1290 /// * `collection_id` - ID of the collection for which the properties is being set.1291 /// * `scope` - Property scope.1292 /// * `properties` - The properties to set.1293 pub fn set_scoped_collection_properties(1294 collection_id: CollectionId,1295 scope: PropertyScope,1296 properties: impl Iterator<Item = Property>,1297 ) -> DispatchResult {1298 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1299 stored_properties.try_scoped_set_from_iter(scope, properties)1300 })1301 .map_err(<Error<T>>::from)?;13021303 Ok(())1304 }13051306 /// Set collection properties.1307 ///1308 /// * `collection` - Collection handler.1309 /// * `sender` - The owner or administrator of the collection.1310 /// * `properties` - The properties to set.1311 pub fn set_collection_properties(1312 collection: &CollectionHandle<T>,1313 sender: &T::CrossAccountId,1314 properties: impl Iterator<Item = Property>,1315 ) -> DispatchResult {1316 Self::modify_collection_properties(1317 collection,1318 sender,1319 properties.map(|property| (property.key, Some(property.value))),1320 )1321 }13221323 /// Delete collection property.1324 ///1325 /// * `collection` - Collection handler.1326 /// * `sender` - The owner or administrator of the collection.1327 /// * `property` - The property to delete.1328 pub fn delete_collection_property(1329 collection: &CollectionHandle<T>,1330 sender: &T::CrossAccountId,1331 property_key: PropertyKey,1332 ) -> DispatchResult {1333 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1334 }13351336 /// Delete collection properties.1337 ///1338 /// * `collection` - Collection handler.1339 /// * `sender` - The owner or administrator of the collection.1340 /// * `properties` - The properties to delete.1341 pub fn delete_collection_properties(1342 collection: &CollectionHandle<T>,1343 sender: &T::CrossAccountId,1344 property_keys: impl Iterator<Item = PropertyKey>,1345 ) -> DispatchResult {1346 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1347 }13481349 /// Set collection propetry permission without any checks.1350 ///1351 /// Used for migrations.1352 ///1353 /// * `collection` - Collection handler.1354 /// * `property_permissions` - Property permissions.1355 pub fn set_property_permission_unchecked(1356 collection: CollectionId,1357 property_permission: PropertyKeyPermission,1358 ) -> DispatchResult {1359 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1360 permissions.try_set(property_permission.key, property_permission.permission)1361 })1362 .map_err(<Error<T>>::from)?;1363 Ok(())1364 }13651366 /// Set collection property permission.1367 ///1368 /// * `collection` - Collection handler.1369 /// * `sender` - The owner or administrator of the collection.1370 /// * `property_permission` - Property permission.1371 pub fn set_property_permission(1372 collection: &CollectionHandle<T>,1373 sender: &T::CrossAccountId,1374 property_permission: PropertyKeyPermission,1375 ) -> DispatchResult {1376 Self::set_scoped_property_permission(1377 collection,1378 sender,1379 PropertyScope::None,1380 property_permission,1381 )1382 }13831384 /// Set collection property permission with scope.1385 ///1386 /// * `collection` - Collection handler.1387 /// * `sender` - The owner or administrator of the collection.1388 /// * `scope` - Property scope.1389 /// * `property_permission` - Property permission.1390 pub fn set_scoped_property_permission(1391 collection: &CollectionHandle<T>,1392 sender: &T::CrossAccountId,1393 scope: PropertyScope,1394 property_permission: PropertyKeyPermission,1395 ) -> DispatchResult {1396 collection.check_is_owner_or_admin(sender)?;13971398 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1399 let current_permission = all_permissions.get(&property_permission.key);1400 if matches![1401 current_permission,1402 Some(PropertyPermission { mutable: false, .. })1403 ] {1404 return Err(<Error<T>>::NoPermission.into());1405 }14061407 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1408 let property_permission = property_permission.clone();1409 permissions.try_scoped_set(1410 scope,1411 property_permission.key,1412 property_permission.permission,1413 )1414 })1415 .map_err(<Error<T>>::from)?;14161417 Self::deposit_event(Event::PropertyPermissionSet(1418 collection.id,1419 property_permission.key,1420 ));1421 <PalletEvm<T>>::deposit_log(1422 erc::CollectionHelpersEvents::CollectionChanged {1423 collection_id: eth::collection_id_to_address(collection.id),1424 }1425 .to_log(T::ContractAddress::get()),1426 );14271428 Ok(())1429 }14301431 /// Set token property permission.1432 ///1433 /// * `collection` - Collection handler.1434 /// * `sender` - The owner or administrator of the collection.1435 /// * `property_permissions` - Property permissions.1436 #[transactional]1437 pub fn set_token_property_permissions(1438 collection: &CollectionHandle<T>,1439 sender: &T::CrossAccountId,1440 property_permissions: Vec<PropertyKeyPermission>,1441 ) -> DispatchResult {1442 Self::set_scoped_token_property_permissions(1443 collection,1444 sender,1445 PropertyScope::None,1446 property_permissions,1447 )1448 }14491450 /// Set token property permission with scope.1451 ///1452 /// * `collection` - Collection handler.1453 /// * `sender` - The owner or administrator of the collection.1454 /// * `scope` - Property scope.1455 /// * `property_permissions` - Property permissions.1456 #[transactional]1457 pub fn set_scoped_token_property_permissions(1458 collection: &CollectionHandle<T>,1459 sender: &T::CrossAccountId,1460 scope: PropertyScope,1461 property_permissions: Vec<PropertyKeyPermission>,1462 ) -> DispatchResult {1463 for prop_pemission in property_permissions {1464 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1465 }14661467 Ok(())1468 }14691470 /// Get collection property.1471 pub fn get_collection_property(1472 collection_id: CollectionId,1473 key: &PropertyKey,1474 ) -> Option<PropertyValue> {1475 Self::collection_properties(collection_id).get(key).cloned()1476 }14771478 /// Convert byte vector to property key vector.1479 pub fn bytes_keys_to_property_keys(1480 keys: Vec<Vec<u8>>,1481 ) -> Result<Vec<PropertyKey>, DispatchError> {1482 keys.into_iter()1483 .map(|key| -> Result<PropertyKey, DispatchError> {1484 key.try_into()1485 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1486 })1487 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1488 }14891490 /// Get properties according to given keys.1491 pub fn filter_collection_properties(1492 collection_id: CollectionId,1493 keys: Option<Vec<PropertyKey>>,1494 ) -> Result<Vec<Property>, DispatchError> {1495 let properties = Self::collection_properties(collection_id);14961497 let properties = keys1498 .map(|keys| {1499 keys.into_iter()1500 .filter_map(|key| {1501 properties.get(&key).map(|value| Property {1502 key,1503 value: value.clone(),1504 })1505 })1506 .collect()1507 })1508 .unwrap_or_else(|| {1509 properties1510 .into_iter()1511 .map(|(key, value)| Property { key, value })1512 .collect()1513 });15141515 Ok(properties)1516 }15171518 /// Get property permissions according to given keys.1519 pub fn filter_property_permissions(1520 collection_id: CollectionId,1521 keys: Option<Vec<PropertyKey>>,1522 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1523 let permissions = Self::property_permissions(collection_id);15241525 let key_permissions = keys1526 .map(|keys| {1527 keys.into_iter()1528 .filter_map(|key| {1529 permissions1530 .get(&key)1531 .map(|permission| PropertyKeyPermission {1532 key,1533 permission: permission.clone(),1534 })1535 })1536 .collect()1537 })1538 .unwrap_or_else(|| {1539 permissions1540 .into_iter()1541 .map(|(key, permission)| PropertyKeyPermission { key, permission })1542 .collect()1543 });15441545 Ok(key_permissions)1546 }15471548 /// Toggle `user` participation in the `collection`'s allow list.1549 /// #### Store read/writes1550 /// 1 writes1551 pub fn toggle_allowlist(1552 collection: &CollectionHandle<T>,1553 sender: &T::CrossAccountId,1554 user: &T::CrossAccountId,1555 allowed: bool,1556 ) -> DispatchResult {1557 collection.check_is_owner_or_admin(sender)?;15581559 // =========15601561 if allowed {1562 <Allowlist<T>>::insert((collection.id, user), true);1563 Self::deposit_event(Event::<T>::AllowListAddressAdded(1564 collection.id,1565 user.clone(),1566 ));1567 } else {1568 <Allowlist<T>>::remove((collection.id, user));1569 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1570 collection.id,1571 user.clone(),1572 ));1573 }15741575 <PalletEvm<T>>::deposit_log(1576 erc::CollectionHelpersEvents::CollectionChanged {1577 collection_id: eth::collection_id_to_address(collection.id),1578 }1579 .to_log(T::ContractAddress::get()),1580 );15811582 Ok(())1583 }15841585 /// Toggle `user` participation in the `collection`'s admin list.1586 /// #### Store read/writes1587 /// 2 reads, 2 writes1588 pub fn toggle_admin(1589 collection: &CollectionHandle<T>,1590 sender: &T::CrossAccountId,1591 user: &T::CrossAccountId,1592 admin: bool,1593 ) -> DispatchResult {1594 collection.check_is_internal()?;1595 collection.check_is_owner(sender)?;15961597 let is_admin = <IsAdmin<T>>::get((collection.id, user));1598 if is_admin == admin {1599 if admin {1600 return Ok(());1601 } else {1602 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1603 }1604 }1605 let amount = <AdminAmount<T>>::get(collection.id);16061607 // =========16081609 if admin {1610 let amount = amount1611 .checked_add(1)1612 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1613 ensure!(1614 amount <= Self::collection_admins_limit(),1615 <Error<T>>::CollectionAdminCountExceeded,1616 );16171618 <AdminAmount<T>>::insert(collection.id, amount);1619 <IsAdmin<T>>::insert((collection.id, user), true);16201621 Self::deposit_event(Event::<T>::CollectionAdminAdded(1622 collection.id,1623 user.clone(),1624 ));1625 } else {1626 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1627 <IsAdmin<T>>::remove((collection.id, user));16281629 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1630 collection.id,1631 user.clone(),1632 ));1633 }16341635 <PalletEvm<T>>::deposit_log(1636 erc::CollectionHelpersEvents::CollectionChanged {1637 collection_id: eth::collection_id_to_address(collection.id),1638 }1639 .to_log(T::ContractAddress::get()),1640 );16411642 Ok(())1643 }16441645 /// Update collection limits.1646 pub fn update_limits(1647 user: &T::CrossAccountId,1648 collection: &mut CollectionHandle<T>,1649 new_limit: CollectionLimits,1650 ) -> DispatchResult {1651 collection.check_is_internal()?;1652 collection.check_is_owner_or_admin(user)?;16531654 collection.limits =1655 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16561657 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1658 <PalletEvm<T>>::deposit_log(1659 erc::CollectionHelpersEvents::CollectionChanged {1660 collection_id: eth::collection_id_to_address(collection.id),1661 }1662 .to_log(T::ContractAddress::get()),1663 );16641665 collection.save()1666 }16671668 /// Merge set fields from `new_limit` to `old_limit`.1669 fn clamp_limits(1670 mode: CollectionMode,1671 old_limit: &CollectionLimits,1672 mut new_limit: CollectionLimits,1673 ) -> Result<CollectionLimits, DispatchError> {1674 let limits = old_limit;1675 limit_default!(old_limit, new_limit,1676 account_token_ownership_limit => ensure!(1677 new_limit <= MAX_TOKEN_OWNERSHIP,1678 <Error<T>>::CollectionLimitBoundsExceeded,1679 ),1680 sponsored_data_size => ensure!(1681 new_limit <= CUSTOM_DATA_LIMIT,1682 <Error<T>>::CollectionLimitBoundsExceeded,1683 ),16841685 sponsored_data_rate_limit => {},1686 token_limit => ensure!(1687 old_limit >= new_limit && new_limit > 0,1688 <Error<T>>::CollectionTokenLimitExceeded1689 ),16901691 sponsor_transfer_timeout(match mode {1692 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1693 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1694 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1695 }) => ensure!(1696 new_limit <= MAX_SPONSOR_TIMEOUT,1697 <Error<T>>::CollectionLimitBoundsExceeded,1698 ),1699 sponsor_approve_timeout => {},1700 owner_can_transfer => ensure!(1701 !limits.owner_can_transfer_instaled() ||1702 old_limit || !new_limit,1703 <Error<T>>::OwnerPermissionsCantBeReverted,1704 ),1705 owner_can_destroy => ensure!(1706 old_limit || !new_limit,1707 <Error<T>>::OwnerPermissionsCantBeReverted,1708 ),1709 transfers_enabled => {},1710 );1711 Ok(new_limit)1712 }17131714 /// Update collection permissions.1715 pub fn update_permissions(1716 user: &T::CrossAccountId,1717 collection: &mut CollectionHandle<T>,1718 new_permission: CollectionPermissions,1719 ) -> DispatchResult {1720 collection.check_is_internal()?;1721 collection.check_is_owner_or_admin(user)?;1722 collection.permissions = Self::clamp_permissions(1723 collection.mode.clone(),1724 &collection.permissions,1725 new_permission,1726 )?;17271728 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1729 <PalletEvm<T>>::deposit_log(1730 erc::CollectionHelpersEvents::CollectionChanged {1731 collection_id: eth::collection_id_to_address(collection.id),1732 }1733 .to_log(T::ContractAddress::get()),1734 );17351736 collection.save()1737 }17381739 /// Merge set fields from `new_permission` to `old_permission`.1740 fn clamp_permissions(1741 _mode: CollectionMode,1742 old_permission: &CollectionPermissions,1743 mut new_permission: CollectionPermissions,1744 ) -> Result<CollectionPermissions, DispatchError> {1745 limit_default_clone!(old_permission, new_permission,1746 access => {},1747 mint_mode => {},1748 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1749 );1750 Ok(new_permission)1751 }17521753 /// Repair possibly broken properties of a collection.1754 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1755 CollectionProperties::<T>::mutate(collection_id, |properties| {1756 properties.recompute_consumed_space();1757 });17581759 Ok(())1760 }1761}17621763/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1764#[macro_export]1765macro_rules! unsupported {1766 ($runtime:path) => {1767 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1768 };1769}17701771/// Return weights for various worst-case operations.1772pub trait CommonWeightInfo<CrossAccountId> {1773 /// Weight of item creation.1774 fn create_item() -> Weight;17751776 /// Weight of items creation.1777 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17781779 /// Weight of items creation.1780 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17811782 /// The weight of the burning item.1783 fn burn_item() -> Weight;17841785 /// Property setting weight.1786 ///1787 /// * `amount`- The number of properties to set.1788 fn set_collection_properties(amount: u32) -> Weight;17891790 /// Collection property deletion weight.1791 ///1792 /// * `amount`- The number of properties to set.1793 fn delete_collection_properties(amount: u32) -> Weight;17941795 /// Token property setting weight.1796 ///1797 /// * `amount`- The number of properties to set.1798 fn set_token_properties(amount: u32) -> Weight;17991800 /// Token property deletion weight.1801 ///1802 /// * `amount`- The number of properties to delete.1803 fn delete_token_properties(amount: u32) -> Weight;18041805 /// Token property permissions set weight.1806 ///1807 /// * `amount`- The number of property permissions to set.1808 fn set_token_property_permissions(amount: u32) -> Weight;18091810 /// Transfer price of the token or its parts.1811 fn transfer() -> Weight;18121813 /// The price of setting the permission of the operation from another user.1814 fn approve() -> Weight;18151816 /// The price of setting the permission of the operation from another user for eth mirror.1817 fn approve_from() -> Weight;18181819 /// Transfer price from another user.1820 fn transfer_from() -> Weight;18211822 /// The price of burning a token from another user.1823 fn burn_from() -> Weight;18241825 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1826 /// whole users's balance.1827 ///1828 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1829 fn burn_recursively_self_raw() -> Weight;18301831 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1832 ///1833 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1834 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18351836 /// The price of recursive burning a token.1837 ///1838 /// `max_selfs` - The maximum burning weight of the token itself.1839 /// `max_breadth` - The maximum number of nested tokens to burn.1840 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1841 Self::burn_recursively_self_raw()1842 .saturating_mul(max_selfs.max(1) as u64)1843 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1844 }18451846 /// The price of retrieving token owner1847 fn token_owner() -> Weight;18481849 /// The price of setting approval for all1850 fn set_allowance_for_all() -> Weight;18511852 /// The price of repairing an item.1853 fn force_repair_item() -> Weight;1854}18551856/// Weight info extension trait for refungible pallet.1857pub trait RefungibleExtensionsWeightInfo {1858 /// Weight of token repartition.1859 fn repartition() -> Weight;1860}18611862/// Common collection operations.1863///1864/// It wraps methods in Fungible, Nonfungible and Refungible pallets1865/// and adds weight info.1866pub trait CommonCollectionOperations<T: Config> {1867 /// Create token.1868 ///1869 /// * `sender` - The user who mint the token and pays for the transaction.1870 /// * `to` - The user who will own the token.1871 /// * `data` - Token data.1872 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1873 fn create_item(1874 &self,1875 sender: T::CrossAccountId,1876 to: T::CrossAccountId,1877 data: CreateItemData,1878 nesting_budget: &dyn Budget,1879 ) -> DispatchResultWithPostInfo;18801881 /// Create multiple tokens.1882 ///1883 /// * `sender` - The user who mint the token and pays for the transaction.1884 /// * `to` - The user who will own the token.1885 /// * `data` - Token data.1886 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1887 fn create_multiple_items(1888 &self,1889 sender: T::CrossAccountId,1890 to: T::CrossAccountId,1891 data: Vec<CreateItemData>,1892 nesting_budget: &dyn Budget,1893 ) -> DispatchResultWithPostInfo;18941895 /// Create multiple tokens.1896 ///1897 /// * `sender` - The user who mint the token and pays for the transaction.1898 /// * `to` - The user who will own the token.1899 /// * `data` - Token data.1900 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1901 fn create_multiple_items_ex(1902 &self,1903 sender: T::CrossAccountId,1904 data: CreateItemExData<T::CrossAccountId>,1905 nesting_budget: &dyn Budget,1906 ) -> DispatchResultWithPostInfo;19071908 /// Burn token.1909 ///1910 /// * `sender` - The user who owns the token.1911 /// * `token` - Token id that will burned.1912 /// * `amount` - The number of parts of the token that will be burned.1913 fn burn_item(1914 &self,1915 sender: T::CrossAccountId,1916 token: TokenId,1917 amount: u128,1918 ) -> DispatchResultWithPostInfo;19191920 /// Burn token and all nested tokens recursievly.1921 ///1922 /// * `sender` - The user who owns the token.1923 /// * `token` - Token id that will burned.1924 /// * `self_budget` - The budget that can be spent on burning tokens.1925 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1926 fn burn_item_recursively(1927 &self,1928 sender: T::CrossAccountId,1929 token: TokenId,1930 self_budget: &dyn Budget,1931 breadth_budget: &dyn Budget,1932 ) -> DispatchResultWithPostInfo;19331934 /// Set collection properties.1935 ///1936 /// * `sender` - Must be either the owner of the collection or its admin.1937 /// * `properties` - Properties to be set.1938 fn set_collection_properties(1939 &self,1940 sender: T::CrossAccountId,1941 properties: Vec<Property>,1942 ) -> DispatchResultWithPostInfo;19431944 /// Delete collection properties.1945 ///1946 /// * `sender` - Must be either the owner of the collection or its admin.1947 /// * `properties` - The properties to be removed.1948 fn delete_collection_properties(1949 &self,1950 sender: &T::CrossAccountId,1951 property_keys: Vec<PropertyKey>,1952 ) -> DispatchResultWithPostInfo;19531954 /// Set token properties.1955 ///1956 /// The appropriate [`PropertyPermission`] for the token property1957 /// must be set with [`Self::set_token_property_permissions`].1958 ///1959 /// * `sender` - Must be either the owner of the token or its admin.1960 /// * `token_id` - The token for which the properties are being set.1961 /// * `properties` - Properties to be set.1962 /// * `budget` - Budget for setting properties.1963 fn set_token_properties(1964 &self,1965 sender: T::CrossAccountId,1966 token_id: TokenId,1967 properties: Vec<Property>,1968 budget: &dyn Budget,1969 ) -> DispatchResultWithPostInfo;19701971 /// Remove token properties.1972 ///1973 /// The appropriate [`PropertyPermission`] for the token property1974 /// must be set with [`Self::set_token_property_permissions`].1975 ///1976 /// * `sender` - Must be either the owner of the token or its admin.1977 /// * `token_id` - The token for which the properties are being remove.1978 /// * `property_keys` - Keys to remove corresponding properties.1979 /// * `budget` - Budget for removing properties.1980 fn delete_token_properties(1981 &self,1982 sender: T::CrossAccountId,1983 token_id: TokenId,1984 property_keys: Vec<PropertyKey>,1985 budget: &dyn Budget,1986 ) -> DispatchResultWithPostInfo;19871988 /// Set token property permissions.1989 ///1990 /// * `sender` - Must be either the owner of the token or its admin.1991 /// * `token_id` - The token for which the properties are being set.1992 /// * `property_permissions` - Property permissions to be set.1993 /// * `budget` - Budget for setting properties.1994 fn set_token_property_permissions(1995 &self,1996 sender: &T::CrossAccountId,1997 property_permissions: Vec<PropertyKeyPermission>,1998 ) -> DispatchResultWithPostInfo;19992000 /// Transfer amount of token pieces.2001 ///2002 /// * `sender` - Donor user.2003 /// * `to` - Recepient user.2004 /// * `token` - The token of which parts are being sent.2005 /// * `amount` - The number of parts of the token that will be transferred.2006 /// * `budget` - The maximum budget that can be spent on the transfer.2007 fn transfer(2008 &self,2009 sender: T::CrossAccountId,2010 to: T::CrossAccountId,2011 token: TokenId,2012 amount: u128,2013 budget: &dyn Budget,2014 ) -> DispatchResultWithPostInfo;20152016 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2017 ///2018 /// * `sender` - The user who grants access to the token.2019 /// * `spender` - The user to whom the rights are granted.2020 /// * `token` - The token to which access is granted.2021 /// * `amount` - The amount of pieces that another user can dispose of.2022 fn approve(2023 &self,2024 sender: T::CrossAccountId,2025 spender: T::CrossAccountId,2026 token: TokenId,2027 amount: u128,2028 ) -> DispatchResultWithPostInfo;20292030 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2031 ///2032 /// * `sender` - The user who grants access to the token.2033 /// * `from` - Spender's eth mirror.2034 /// * `to` - The user to whom the rights are granted.2035 /// * `token` - The token to which access is granted.2036 /// * `amount` - The amount of pieces that another user can dispose of.2037 fn approve_from(2038 &self,2039 sender: T::CrossAccountId,2040 from: T::CrossAccountId,2041 to: T::CrossAccountId,2042 token: TokenId,2043 amount: u128,2044 ) -> DispatchResultWithPostInfo;20452046 /// Send parts of a token owned by another user.2047 ///2048 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2049 ///2050 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2051 /// * `from` - The user who owns the token.2052 /// * `to` - Recepient user.2053 /// * `token` - The token of which parts are being sent.2054 /// * `amount` - The number of parts of the token that will be transferred.2055 /// * `budget` - The maximum budget that can be spent on the transfer.2056 fn transfer_from(2057 &self,2058 sender: T::CrossAccountId,2059 from: T::CrossAccountId,2060 to: T::CrossAccountId,2061 token: TokenId,2062 amount: u128,2063 budget: &dyn Budget,2064 ) -> DispatchResultWithPostInfo;20652066 /// Burn parts of a token owned by another user.2067 ///2068 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2069 ///2070 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2071 /// * `from` - The user who owns the token.2072 /// * `token` - The token of which parts are being sent.2073 /// * `amount` - The number of parts of the token that will be transferred.2074 /// * `budget` - The maximum budget that can be spent on the burn.2075 fn burn_from(2076 &self,2077 sender: T::CrossAccountId,2078 from: T::CrossAccountId,2079 token: TokenId,2080 amount: u128,2081 budget: &dyn Budget,2082 ) -> DispatchResultWithPostInfo;20832084 /// Check permission to nest token.2085 ///2086 /// * `sender` - The user who initiated the check.2087 /// * `from` - The token that is checked for embedding.2088 /// * `under` - Token under which to check.2089 /// * `budget` - The maximum budget that can be spent on the check.2090 fn check_nesting(2091 &self,2092 sender: T::CrossAccountId,2093 from: (CollectionId, TokenId),2094 under: TokenId,2095 budget: &dyn Budget,2096 ) -> DispatchResult;20972098 /// Nest one token into another.2099 ///2100 /// * `under` - Token holder.2101 /// * `to_nest` - Nested token.2102 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21032104 /// Unnest token.2105 ///2106 /// * `under` - Token holder.2107 /// * `to_nest` - Token to unnest.2108 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21092110 /// Get all user tokens.2111 ///2112 /// * `account` - Account for which you need to get tokens.2113 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;21142115 /// Get all the tokens in the collection.2116 fn collection_tokens(&self) -> Vec<TokenId>;21172118 /// Check if the token exists.2119 ///2120 /// * `token` - Id token to check.2121 fn token_exists(&self, token: TokenId) -> bool;21222123 /// Get the id of the last minted token.2124 fn last_token_id(&self) -> TokenId;21252126 /// Get the owner of the token.2127 ///2128 /// * `token` - The token for which you need to find out the owner.2129 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;21302131 /// Returns 10 tokens owners in no particular order.2132 ///2133 /// * `token` - The token for which you need to find out the owners.2134 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21352136 /// Get the value of the token property by key.2137 ///2138 /// * `token` - Token with the property to get.2139 /// * `key` - Property name.2140 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21412142 /// Get a set of token properties by key vector.2143 ///2144 /// * `token` - Token with the property to get.2145 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2146 /// then all properties are returned.2147 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21482149 /// Amount of unique collection tokens2150 fn total_supply(&self) -> u32;21512152 /// Amount of different tokens account has.2153 ///2154 /// * `account` - The account for which need to get the balance.2155 fn account_balance(&self, account: T::CrossAccountId) -> u32;21562157 /// Amount of specific token account have.2158 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21592160 /// Amount of token pieces2161 fn total_pieces(&self, token: TokenId) -> Option<u128>;21622163 /// Get the number of parts of the token that a trusted user can manage.2164 ///2165 /// * `sender` - Trusted user.2166 /// * `spender` - Owner of the token.2167 /// * `token` - The token for which to get the value.2168 fn allowance(2169 &self,2170 sender: T::CrossAccountId,2171 spender: T::CrossAccountId,2172 token: TokenId,2173 ) -> u128;21742175 /// Get extension for RFT collection.2176 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21772178 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2179 /// * `owner` - Token owner2180 /// * `operator` - Operator2181 /// * `approve` - Should operator status be granted or revoked?2182 fn set_allowance_for_all(2183 &self,2184 owner: T::CrossAccountId,2185 operator: T::CrossAccountId,2186 approve: bool,2187 ) -> DispatchResultWithPostInfo;21882189 /// Tells whether the given `owner` approves the `operator`.2190 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21912192 /// Repairs a possibly broken item.2193 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2194}21952196/// Extension for RFT collection.2197pub trait RefungibleExtensions<T>2198where2199 T: Config,2200{2201 /// Change the number of parts of the token.2202 ///2203 /// When the value changes down, this function is equivalent to burning parts of the token.2204 ///2205 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2206 /// * `token` - The token for which you want to change the number of parts.2207 /// * `amount` - The new value of the parts of the token.2208 fn repartition(2209 &self,2210 sender: &T::CrossAccountId,2211 token: TokenId,2212 amount: u128,2213 ) -> DispatchResultWithPostInfo;2214}22152216/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2217///2218/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2219pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2220 let post_info = PostDispatchInfo {2221 actual_weight: Some(weight),2222 pays_fee: Pays::Yes,2223 };2224 match res {2225 Ok(()) => Ok(post_info),2226 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2227 }2228}22292230impl<T: Config> From<PropertiesError> for Error<T> {2231 fn from(error: PropertiesError) -> Self {2232 match error {2233 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2234 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2235 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2236 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2237 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2238 }2239 }2240}pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -677,8 +677,14 @@
// `from`, `to` checked in [`transfer`]
collection.check_allowlist(spender)?;
}
+
+ if collection.ignores_token_restrictions(spender) {
+ return Ok(Self::compute_allowance_decrease(
+ collection, from, spender, amount,
+ ));
+ }
+
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
- // TODO: should collection owner be allowed to perform this transfer?
ensure!(
<PalletStructure<T>>::check_indirectly_owned(
spender.clone(),
@@ -690,18 +696,25 @@
<CommonError<T>>::ApprovedValueTooLow,
);
return Ok(None);
- }
- let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);
- if allowance.is_none() {
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
}
+ let allowance = Self::compute_allowance_decrease(collection, from, spender, amount);
+ ensure!(allowance.is_some(), <CommonError<T>>::ApprovedValueTooLow);
+
Ok(allowance)
}
+ /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+ /// Otherwise, it returns `None`.
+ fn compute_allowance_decrease(
+ collection: &FungibleHandle<T>,
+ from: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) -> Option<u128> {
+ <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount)
+ }
+
/// Transfer fungible tokens from one account to another.
/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
/// The owner should set allowance for the spender to transfer pieces.
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1246,7 +1246,7 @@
collection.check_allowlist(spender)?;
}
- if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {
+ if collection.ignores_token_restrictions(spender) {
return Ok(());
}
@@ -1269,11 +1269,8 @@
if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
return Ok(());
}
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
- Ok(())
+
+ Err(<CommonError<T>>::ApprovedValueTooLow.into())
}
/// Transfer NFT token from one account to another.
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1178,8 +1178,10 @@
collection.check_allowlist(spender)?;
}
- if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {
- return Ok(None);
+ if collection.ignores_token_restrictions(spender) {
+ return Ok(Self::compute_allowance_decrease(
+ collection, token, from, &spender, amount,
+ ));
}
if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
@@ -1196,21 +1198,30 @@
);
return Ok(None);
}
- let allowance =
- <Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);
+ let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+ if allowance.is_some() {
+ return Ok(allowance);
+ }
+
// Allowance (if any) would be reduced if spender is also wallet operator
if <CollectionAllowance<T>>::get((collection.id, from, spender)) {
return Ok(allowance);
}
- if allowance.is_none() {
- ensure!(
- collection.ignores_allowance(spender),
- <CommonError<T>>::ApprovedValueTooLow
- );
- }
- Ok(allowance)
+ Err(<CommonError<T>>::ApprovedValueTooLow.into())
+ }
+
+ /// Returns `Some(amount)` if the `spender` have allowance to spend this amount.
+ /// Otherwise, it returns `None`.
+ fn compute_allowance_decrease(
+ collection: &RefungibleHandle<T>,
+ token: TokenId,
+ from: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
+ amount: u128,
+ ) -> Option<u128> {
+ <Allowance<T>>::get((collection.id, token, from, spender)).checked_sub(amount)
}
/// Transfer RFT token pieces from one account to another.