difftreelog
refactor unsupported! macro
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 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionId,74 CreateItemData,75 MAX_TOKEN_PREFIX_LENGTH,76 COLLECTION_ADMINS_LIMIT,77 TokenId,78 TokenChild,79 CollectionStats,80 MAX_TOKEN_OWNERSHIP,81 CollectionMode,82 NFT_SPONSOR_TRANSFER_TIMEOUT,83 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 MAX_SPONSOR_TIMEOUT,86 CUSTOM_DATA_LIMIT,87 CollectionLimits,88 CreateCollectionData,89 SponsorshipState,90 CreateItemExData,91 SponsoringRateLimit,92 budget::Budget,93 PhantomType,94 Property,95 Properties,96 PropertiesPermissionMap,97 PropertyKey,98 PropertyValue,99 PropertyPermission,100 PropertiesError,101 PropertyKeyPermission,102 TokenData,103 TrySetProperty,104 PropertyScope,105 // RMRK106 RmrkCollectionInfo,107 RmrkInstanceInfo,108 RmrkResourceInfo,109 RmrkPropertyInfo,110 RmrkBaseInfo,111 RmrkPartType,112 RmrkBoundedTheme,113 RmrkNftChild,114 CollectionPermissions,115 SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139 /// Collection id140 pub id: CollectionId,141 collection: Collection<T::AccountId>,142 /// Substrate recorder for counting consumed gas143 pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 &self.recorder149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.recorder152 }153}154155impl<T: Config> CollectionHandle<T> {156 /// Same as [CollectionHandle::new] but with an explicit gas limit.157 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158 <CollectionById<T>>::get(id).map(|collection| Self {159 id,160 collection,161 recorder: SubstrateRecorder::new(gas_limit),162 })163 }164165 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder,171 })172 }173174 /// Retrives collection data from storage and creates collection handle with default parameters.175 /// If collection not found return `None`176 pub fn new(id: CollectionId) -> Option<Self> {177 Self::new_with_gas_limit(id, u64::MAX)178 }179180 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183 }184185 /// Consume gas for reading.186 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187 self.recorder188 .consume_gas(T::GasWeightMapping::weight_to_gas(189 <T as frame_system::Config>::DbWeight::get()190 .read191 .saturating_mul(reads),192 ))193 }194195 /// Consume gas for writing.196 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197 self.recorder198 .consume_gas(T::GasWeightMapping::weight_to_gas(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 ))203 }204205 /// Save collection to storage.206 pub fn save(self) -> DispatchResult {207 <CollectionById<T>>::insert(self.id, self.collection);208 Ok(())209 }210211 /// Set collection sponsor.212 ///213 /// Unique collections allows sponsoring for certain actions.214 /// This method allows you to set the sponsor of the collection.215 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218 Ok(())219 }220221 /// Confirm sponsorship222 ///223 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226 if self.collection.sponsorship.pending_sponsor() != Some(sender) {227 return Ok(false);228 }229230 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231 Ok(true)232 }233234 /// Checks that the collection was created with, and must be operated upon through **Unique API**.235 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236 pub fn check_is_internal(&self) -> DispatchResult {237 if self.external_collection {238 return Err(<Error<T>>::CollectionIsExternal)?;239 }240241 Ok(())242 }243244 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246 pub fn check_is_external(&self) -> DispatchResult {247 if !self.external_collection {248 return Err(<Error<T>>::CollectionIsInternal)?;249 }250251 Ok(())252 }253}254255impl<T: Config> Deref for CollectionHandle<T> {256 type Target = Collection<T::AccountId>;257258 fn deref(&self) -> &Self::Target {259 &self.collection260 }261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264 fn deref_mut(&mut self) -> &mut Self::Target {265 &mut self.collection266 }267}268269impl<T: Config> CollectionHandle<T> {270 /// Checks if the `user` is the owner of the collection.271 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273 Ok(())274 }275276 /// Returns **true** if the `user` is the owner or administrator of the collection.277 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279 }280281 /// Checks if the `user` is the owner or administrator of the collection.282 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284 Ok(())285 }286287 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290 }291292 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295 }296297 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299 ensure!(300 <Allowlist<T>>::get((self.id, user)),301 <Error<T>>::AddressNotInAllowlist302 );303 Ok(())304 }305}306307#[frame_support::pallet]308pub mod pallet {309 use super::*;310 use pallet_evm::account;311 use dispatch::CollectionDispatch;312 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313 use frame_system::pallet_prelude::*;314 use frame_support::traits::Currency;315 use up_data_structs::{TokenId, mapping::TokenAddressMapping};316 use scale_info::TypeInfo;317 use weights::WeightInfo;318319 #[pallet::config]320 pub trait Config:321 frame_system::Config322 + pallet_evm_coder_substrate::Config323 + pallet_evm::Config324 + TypeInfo325 + account::Config326 {327 /// Weight information for functions of this pallet.328 type WeightInfo: WeightInfo;329330 /// Events compatible with [`frame_system::Config::Event`].331 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333 /// Handler of accounts and payment.334 type Currency: Currency<Self::AccountId>;335336 /// Set price to create a collection.337 #[pallet::constant]338 type CollectionCreationPrice: Get<339 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340 >;341342 /// Dispatcher of operations on collections.343 type CollectionDispatch: CollectionDispatch<Self>;344345 /// Account which holds the chain's treasury.346 type TreasuryAccountId: Get<Self::AccountId>;347348 /// Address under which the CollectionHelper contract would be available.349 type ContractAddress: Get<H160>;350351 /// Mapper for token addresses to Ethereum addresses.352 type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354 /// Mapper for token addresses to [`CrossAccountId`].355 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356 }357358 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360 #[pallet::pallet]361 #[pallet::storage_version(STORAGE_VERSION)]362 #[pallet::generate_store(pub(super) trait Store)]363 pub struct Pallet<T>(_);364365 #[pallet::extra_constants]366 impl<T: Config> Pallet<T> {367 /// Maximum admins per collection.368 pub fn collection_admins_limit() -> u32 {369 COLLECTION_ADMINS_LIMIT370 }371 }372373 #[pallet::event]374 #[pallet::generate_deposit(pub fn deposit_event)]375 pub enum Event<T: Config> {376 /// New collection was created377 CollectionCreated(378 /// Globally unique identifier of newly created collection.379 CollectionId,380 /// [`CollectionMode`] converted into _u8_.381 u8,382 /// Collection owner.383 T::AccountId,384 ),385386 /// New collection was destroyed387 CollectionDestroyed(388 /// Globally unique identifier of collection.389 CollectionId,390 ),391392 /// New item was created.393 ItemCreated(394 /// Id of the collection where item was created.395 CollectionId,396 /// Id of an item. Unique within the collection.397 TokenId,398 /// Owner of newly created item399 T::CrossAccountId,400 /// Always 1 for NFT401 u128,402 ),403404 /// Collection item was burned.405 ItemDestroyed(406 /// Id of the collection where item was destroyed.407 CollectionId,408 /// Identifier of burned NFT.409 TokenId,410 /// Which user has destroyed its tokens.411 T::CrossAccountId,412 /// Amount of token pieces destroed. Always 1 for NFT.413 u128,414 ),415416 /// Item was transferred417 Transfer(418 /// Id of collection to which item is belong.419 CollectionId,420 /// Id of an item.421 TokenId,422 /// Original owner of item.423 T::CrossAccountId,424 /// New owner of item.425 T::CrossAccountId,426 /// Amount of token pieces transfered. Always 1 for NFT.427 u128,428 ),429430 /// Amount pieces of token owned by `sender` was approved for `spender`.431 Approved(432 /// Id of collection to which item is belong.433 CollectionId,434 /// Id of an item.435 TokenId,436 /// Original owner of item.437 T::CrossAccountId,438 /// Id for which the approval was granted.439 T::CrossAccountId,440 /// Amount of token pieces transfered. Always 1 for NFT.441 u128,442 ),443444 /// The colletion property has been added or edited.445 CollectionPropertySet(446 /// Id of collection to which property has been set.447 CollectionId,448 /// The property that was set.449 PropertyKey,450 ),451452 /// The property has been deleted.453 CollectionPropertyDeleted(454 /// Id of collection to which property has been deleted.455 CollectionId,456 /// The property that was deleted.457 PropertyKey,458 ),459460 /// The token property has been added or edited.461 TokenPropertySet(462 /// Identifier of the collection whose token has the property set.463 CollectionId,464 /// The token for which the property was set.465 TokenId,466 /// The property that was set.467 PropertyKey,468 ),469470 /// The token property has been deleted.471 TokenPropertyDeleted(472 /// Identifier of the collection whose token has the property deleted.473 CollectionId,474 /// The token for which the property was deleted.475 TokenId,476 /// The property that was deleted.477 PropertyKey,478 ),479480 /// The token property permission of a collection has been set.481 PropertyPermissionSet(482 /// ID of collection to which property permission has been set.483 CollectionId,484 /// The property permission that was set.485 PropertyKey,486 ),487 }488489 #[pallet::error]490 pub enum Error<T> {491 /// This collection does not exist.492 CollectionNotFound,493 /// Sender parameter and item owner must be equal.494 MustBeTokenOwner,495 /// No permission to perform action496 NoPermission,497 /// Destroying only empty collections is allowed498 CantDestroyNotEmptyCollection,499 /// Collection is not in mint mode.500 PublicMintingNotAllowed,501 /// Address is not in allow list.502 AddressNotInAllowlist,503504 /// Collection name can not be longer than 63 char.505 CollectionNameLimitExceeded,506 /// Collection description can not be longer than 255 char.507 CollectionDescriptionLimitExceeded,508 /// Token prefix can not be longer than 15 char.509 CollectionTokenPrefixLimitExceeded,510 /// Total collections bound exceeded.511 TotalCollectionsLimitExceeded,512 /// Exceeded max admin count513 CollectionAdminCountExceeded,514 /// Collection limit bounds per collection exceeded515 CollectionLimitBoundsExceeded,516 /// Tried to enable permissions which are only permitted to be disabled517 OwnerPermissionsCantBeReverted,518 /// Collection settings not allowing items transferring519 TransferNotAllowed,520 /// Account token limit exceeded per collection521 AccountTokenLimitExceeded,522 /// Collection token limit exceeded523 CollectionTokenLimitExceeded,524 /// Metadata flag frozen525 MetadataFlagFrozen,526527 /// Item does not exist528 TokenNotFound,529 /// Item is balance not enough530 TokenValueTooLow,531 /// Requested value is more than the approved532 ApprovedValueTooLow,533 /// Tried to approve more than owned534 CantApproveMoreThanOwned,535536 /// Can't transfer tokens to ethereum zero address537 AddressIsZero,538 /// Target collection doesn't support this operation539 UnsupportedOperation,540541 /// Insufficient funds to perform an action542 NotSufficientFounds,543544 /// User does not satisfy the nesting rule545 UserIsNotAllowedToNest,546 /// Only tokens from specific collections may nest tokens under this one547 SourceCollectionIsNotAllowedToNest,548549 /// Tried to store more data than allowed in collection field550 CollectionFieldSizeExceeded,551552 /// Tried to store more property data than allowed553 NoSpaceForProperty,554555 /// Tried to store more property keys than allowed556 PropertyLimitReached,557558 /// Property key is too long559 PropertyKeyIsTooLong,560561 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed562 InvalidCharacterInPropertyKey,563564 /// Empty property keys are forbidden565 EmptyPropertyKey,566567 /// Tried to access an external collection with an internal API568 CollectionIsExternal,569570 /// Tried to access an internal collection with an external API571 CollectionIsInternal,572573 /// A method of an unsupported API was called574 UnsupportedRuntimeApi,575 }576577 /// Storage of the count of created collections. Essentially contains the last collection ID.578 #[pallet::storage]579 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;580581 /// Storage of the count of deleted collections.582 #[pallet::storage]583 pub type DestroyedCollectionCount<T> =584 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;585586 /// Storage of collection info.587 #[pallet::storage]588 pub type CollectionById<T> = StorageMap<589 Hasher = Blake2_128Concat,590 Key = CollectionId,591 Value = Collection<<T as frame_system::Config>::AccountId>,592 QueryKind = OptionQuery,593 >;594595 /// Storage of collection properties.596 #[pallet::storage]597 #[pallet::getter(fn collection_properties)]598 pub type CollectionProperties<T> = StorageMap<599 Hasher = Blake2_128Concat,600 Key = CollectionId,601 Value = Properties,602 QueryKind = ValueQuery,603 OnEmpty = up_data_structs::CollectionProperties,604 >;605606 /// Storage of token property permissions of a collection.607 #[pallet::storage]608 #[pallet::getter(fn property_permissions)]609 pub type CollectionPropertyPermissions<T> = StorageMap<610 Hasher = Blake2_128Concat,611 Key = CollectionId,612 Value = PropertiesPermissionMap,613 QueryKind = ValueQuery,614 >;615616 /// Storage of the amount of collection admins.617 #[pallet::storage]618 pub type AdminAmount<T> = StorageMap<619 Hasher = Blake2_128Concat,620 Key = CollectionId,621 Value = u32,622 QueryKind = ValueQuery,623 >;624625 /// List of collection admins.626 #[pallet::storage]627 pub type IsAdmin<T: Config> = StorageNMap<628 Key = (629 Key<Blake2_128Concat, CollectionId>,630 Key<Blake2_128Concat, T::CrossAccountId>,631 ),632 Value = bool,633 QueryKind = ValueQuery,634 >;635636 /// Allowlisted collection users.637 #[pallet::storage]638 pub type Allowlist<T: Config> = StorageNMap<639 Key = (640 Key<Blake2_128Concat, CollectionId>,641 Key<Blake2_128Concat, T::CrossAccountId>,642 ),643 Value = bool,644 QueryKind = ValueQuery,645 >;646647 /// Not used by code, exists only to provide some types to metadata.648 #[pallet::storage]649 pub type DummyStorageValue<T: Config> = StorageValue<650 Value = (651 CollectionStats,652 CollectionId,653 TokenId,654 TokenChild,655 PhantomType<(656 TokenData<T::CrossAccountId>,657 RpcCollection<T::AccountId>,658 // RMRK659 RmrkCollectionInfo<T::AccountId>,660 RmrkInstanceInfo<T::AccountId>,661 RmrkResourceInfo,662 RmrkPropertyInfo,663 RmrkBaseInfo<T::AccountId>,664 RmrkPartType,665 RmrkBoundedTheme,666 RmrkNftChild,667 )>,668 ),669 QueryKind = OptionQuery,670 >;671672 #[pallet::hooks]673 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {674 fn on_runtime_upgrade() -> Weight {675 StorageVersion::new(1).put::<Pallet<T>>();676677 0678 }679 }680}681682impl<T: Config> Pallet<T> {683 /// Enshure that receiver address is correct.684 ///685 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.686 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {687 ensure!(688 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,689 <Error<T>>::AddressIsZero690 );691 Ok(())692 }693694 /// Get a vector of collection admins.695 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {696 <IsAdmin<T>>::iter_prefix((collection,))697 .map(|(a, _)| a)698 .collect()699 }700701 /// Get a vector of users allowed to mint tokens.702 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {703 <Allowlist<T>>::iter_prefix((collection,))704 .map(|(a, _)| a)705 .collect()706 }707708 /// Is `user` allowed to mint token in `collection`.709 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {710 <Allowlist<T>>::get((collection, user))711 }712713 /// Get statistics of collections.714 pub fn collection_stats() -> CollectionStats {715 let created = <CreatedCollectionCount<T>>::get();716 let destroyed = <DestroyedCollectionCount<T>>::get();717 CollectionStats {718 created: created.0,719 destroyed: destroyed.0,720 alive: created.0 - destroyed.0,721 }722 }723724 /// Get the effective limits for the collection.725 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {726 let collection = <CollectionById<T>>::get(collection);727 if collection.is_none() {728 return None;729 }730731 let collection = collection.unwrap();732 let limits = collection.limits;733 let effective_limits = CollectionLimits {734 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),735 sponsored_data_size: Some(limits.sponsored_data_size()),736 sponsored_data_rate_limit: Some(737 limits738 .sponsored_data_rate_limit739 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),740 ),741 token_limit: Some(limits.token_limit()),742 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(743 match collection.mode {744 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,745 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,746 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,747 },748 )),749 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),750 owner_can_transfer: Some(limits.owner_can_transfer()),751 owner_can_destroy: Some(limits.owner_can_destroy()),752 transfers_enabled: Some(limits.transfers_enabled()),753 };754755 Some(effective_limits)756 }757758 /// Returns information about the `collection` adapted for rpc.759 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {760 let Collection {761 name,762 description,763 owner,764 mode,765 token_prefix,766 sponsorship,767 limits,768 permissions,769 external_collection,770 } = <CollectionById<T>>::get(collection)?;771772 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)773 .into_iter()774 .map(|(key, permission)| PropertyKeyPermission { key, permission })775 .collect();776777 let properties = <CollectionProperties<T>>::get(collection)778 .into_iter()779 .map(|(key, value)| Property { key, value })780 .collect();781782 let permissions = CollectionPermissions {783 access: Some(permissions.access()),784 mint_mode: Some(permissions.mint_mode()),785 nesting: Some(permissions.nesting().clone()),786 };787788 Some(RpcCollection {789 name: name.into_inner(),790 description: description.into_inner(),791 owner,792 mode,793 token_prefix: token_prefix.into_inner(),794 sponsorship,795 limits,796 permissions,797 token_property_permissions,798 properties,799 read_only: external_collection,800 })801 }802}803804macro_rules! limit_default {805 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{806 $(807 if let Some($new) = $new.$field {808 let $old = $old.$field($($arg)?);809 let _ = $new;810 let _ = $old;811 $check812 } else {813 $new.$field = $old.$field814 }815 )*816 }};817}818macro_rules! limit_default_clone {819 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{820 $(821 if let Some($new) = $new.$field.clone() {822 let $old = $old.$field($($arg)?);823 let _ = $new;824 let _ = $old;825 $check826 } else {827 $new.$field = $old.$field.clone()828 }829 )*830 }};831}832833impl<T: Config> Pallet<T> {834 /// Create new collection.835 ///836 /// * `owner` - The owner of the collection.837 /// * `data` - Description of the created collection.838 /// * `is_external` - Marks that collection managet by not "Unique network".839 pub fn init_collection(840 owner: T::CrossAccountId,841 data: CreateCollectionData<T::AccountId>,842 is_external: bool,843 ) -> Result<CollectionId, DispatchError> {844 {845 ensure!(846 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,847 Error::<T>::CollectionTokenPrefixLimitExceeded848 );849 }850851 let created_count = <CreatedCollectionCount<T>>::get()852 .0853 .checked_add(1)854 .ok_or(ArithmeticError::Overflow)?;855 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;856 let id = CollectionId(created_count);857858 // bound Total number of collections859 ensure!(860 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,861 <Error<T>>::TotalCollectionsLimitExceeded862 );863864 // =========865866 let collection = Collection {867 owner: owner.as_sub().clone(),868 name: data.name,869 mode: data.mode.clone(),870 description: data.description,871 token_prefix: data.token_prefix,872 sponsorship: data873 .pending_sponsor874 .map(SponsorshipState::Unconfirmed)875 .unwrap_or_default(),876 limits: data877 .limits878 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))879 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,880 permissions: data881 .permissions882 .map(|permissions| {883 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)884 })885 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,886 external_collection: is_external,887 };888889 let mut collection_properties = up_data_structs::CollectionProperties::get();890 collection_properties891 .try_set_from_iter(data.properties.into_iter())892 .map_err(<Error<T>>::from)?;893894 CollectionProperties::<T>::insert(id, collection_properties);895896 let mut token_props_permissions = PropertiesPermissionMap::new();897 token_props_permissions898 .try_set_from_iter(data.token_property_permissions.into_iter())899 .map_err(<Error<T>>::from)?;900901 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);902903 // Take a (non-refundable) deposit of collection creation904 {905 let mut imbalance =906 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();907 imbalance.subsume(908 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(909 &T::TreasuryAccountId::get(),910 T::CollectionCreationPrice::get(),911 ),912 );913 <T as Config>::Currency::settle(914 owner.as_sub(),915 imbalance,916 WithdrawReasons::TRANSFER,917 ExistenceRequirement::KeepAlive,918 )919 .map_err(|_| Error::<T>::NotSufficientFounds)?;920 }921922 <CreatedCollectionCount<T>>::put(created_count);923 <Pallet<T>>::deposit_event(Event::CollectionCreated(924 id,925 data.mode.id(),926 owner.as_sub().clone(),927 ));928 <PalletEvm<T>>::deposit_log(929 erc::CollectionHelpersEvents::CollectionCreated {930 owner: *owner.as_eth(),931 collection_id: eth::collection_id_to_address(id),932 }933 .to_log(T::ContractAddress::get()),934 );935 <CollectionById<T>>::insert(id, collection);936 Ok(id)937 }938939 /// Destroy collection.940 ///941 /// * `collection` - Collection handler.942 /// * `sender` - The owner or administrator of the collection.943 pub fn destroy_collection(944 collection: CollectionHandle<T>,945 sender: &T::CrossAccountId,946 ) -> DispatchResult {947 ensure!(948 collection.limits.owner_can_destroy(),949 <Error<T>>::NoPermission,950 );951 collection.check_is_owner(sender)?;952953 let destroyed_collections = <DestroyedCollectionCount<T>>::get()954 .0955 .checked_add(1)956 .ok_or(ArithmeticError::Overflow)?;957958 // =========959960 <DestroyedCollectionCount<T>>::put(destroyed_collections);961 <CollectionById<T>>::remove(collection.id);962 <AdminAmount<T>>::remove(collection.id);963 <IsAdmin<T>>::remove_prefix((collection.id,), None);964 <Allowlist<T>>::remove_prefix((collection.id,), None);965 <CollectionProperties<T>>::remove(collection.id);966967 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));968 Ok(())969 }970971 /// Set collection property.972 ///973 /// * `collection` - Collection handler.974 /// * `sender` - The owner or administrator of the collection.975 /// * `property` - The property to set.976 pub fn set_collection_property(977 collection: &CollectionHandle<T>,978 sender: &T::CrossAccountId,979 property: Property,980 ) -> DispatchResult {981 collection.check_is_owner_or_admin(sender)?;982983 CollectionProperties::<T>::try_mutate(collection.id, |properties| {984 let property = property.clone();985 properties.try_set(property.key, property.value)986 })987 .map_err(<Error<T>>::from)?;988989 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));990991 Ok(())992 }993994 /// Set scouped collection property.995 ///996 /// * `collection_id` - ID of the collection for which the property is being set.997 /// * `scope` - Property scope.998 /// * `property` - The property to set.999 pub fn set_scoped_collection_property(1000 collection_id: CollectionId,1001 scope: PropertyScope,1002 property: Property,1003 ) -> DispatchResult {1004 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1005 properties.try_scoped_set(scope, property.key, property.value)1006 })1007 .map_err(<Error<T>>::from)?;10081009 Ok(())1010 }10111012 /// Set scouped collection properties.1013 ///1014 /// * `collection_id` - ID of the collection for which the properties is being set.1015 /// * `scope` - Property scope.1016 /// * `properties` - The properties to set.1017 pub fn set_scoped_collection_properties(1018 collection_id: CollectionId,1019 scope: PropertyScope,1020 properties: impl Iterator<Item = Property>,1021 ) -> DispatchResult {1022 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1023 stored_properties.try_scoped_set_from_iter(scope, properties)1024 })1025 .map_err(<Error<T>>::from)?;10261027 Ok(())1028 }10291030 /// Set collection properties.1031 ///1032 /// * `collection` - Collection handler.1033 /// * `sender` - The owner or administrator of the collection.1034 /// * `properties` - The properties to set.1035 #[transactional]1036 pub fn set_collection_properties(1037 collection: &CollectionHandle<T>,1038 sender: &T::CrossAccountId,1039 properties: Vec<Property>,1040 ) -> DispatchResult {1041 for property in properties {1042 Self::set_collection_property(collection, sender, property)?;1043 }10441045 Ok(())1046 }10471048 /// Delete collection property.1049 ///1050 /// * `collection` - Collection handler.1051 /// * `sender` - The owner or administrator of the collection.1052 /// * `property` - The property to delete.1053 pub fn delete_collection_property(1054 collection: &CollectionHandle<T>,1055 sender: &T::CrossAccountId,1056 property_key: PropertyKey,1057 ) -> DispatchResult {1058 collection.check_is_owner_or_admin(sender)?;10591060 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1061 properties.remove(&property_key)1062 })1063 .map_err(<Error<T>>::from)?;10641065 Self::deposit_event(Event::CollectionPropertyDeleted(1066 collection.id,1067 property_key,1068 ));10691070 Ok(())1071 }10721073 /// Delete collection properties.1074 ///1075 /// * `collection` - Collection handler.1076 /// * `sender` - The owner or administrator of the collection.1077 /// * `properties` - The properties to delete.1078 #[transactional]1079 pub fn delete_collection_properties(1080 collection: &CollectionHandle<T>,1081 sender: &T::CrossAccountId,1082 property_keys: Vec<PropertyKey>,1083 ) -> DispatchResult {1084 for key in property_keys {1085 Self::delete_collection_property(collection, sender, key)?;1086 }10871088 Ok(())1089 }10901091 /// Set collection propetry permission without any checks.1092 ///1093 /// Used for migrations.1094 ///1095 /// * `collection` - Collection handler.1096 /// * `property_permissions` - Property permissions.1097 pub fn set_property_permission_unchecked(1098 collection: CollectionId,1099 property_permission: PropertyKeyPermission,1100 ) -> DispatchResult {1101 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1102 permissions.try_set(property_permission.key, property_permission.permission)1103 })1104 .map_err(<Error<T>>::from)?;1105 Ok(())1106 }11071108 /// Set collection property permission.1109 ///1110 /// * `collection` - Collection handler.1111 /// * `sender` - The owner or administrator of the collection.1112 /// * `property_permission` - Property permission.1113 pub fn set_property_permission(1114 collection: &CollectionHandle<T>,1115 sender: &T::CrossAccountId,1116 property_permission: PropertyKeyPermission,1117 ) -> DispatchResult {1118 collection.check_is_owner_or_admin(sender)?;11191120 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1121 let current_permission = all_permissions.get(&property_permission.key);1122 if matches![1123 current_permission,1124 Some(PropertyPermission { mutable: false, .. })1125 ] {1126 return Err(<Error<T>>::NoPermission.into());1127 }11281129 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1130 let property_permission = property_permission.clone();1131 permissions.try_set(property_permission.key, property_permission.permission)1132 })1133 .map_err(<Error<T>>::from)?;11341135 Self::deposit_event(Event::PropertyPermissionSet(1136 collection.id,1137 property_permission.key,1138 ));11391140 Ok(())1141 }11421143 /// Set token property permission.1144 ///1145 /// * `collection` - Collection handler.1146 /// * `sender` - The owner or administrator of the collection.1147 /// * `property_permissions` - Property permissions.1148 #[transactional]1149 pub fn set_token_property_permissions(1150 collection: &CollectionHandle<T>,1151 sender: &T::CrossAccountId,1152 property_permissions: Vec<PropertyKeyPermission>,1153 ) -> DispatchResult {1154 for prop_pemission in property_permissions {1155 Self::set_property_permission(collection, sender, prop_pemission)?;1156 }11571158 Ok(())1159 }11601161 /// Get collection property.1162 pub fn get_collection_property(1163 collection_id: CollectionId,1164 key: &PropertyKey,1165 ) -> Option<PropertyValue> {1166 Self::collection_properties(collection_id).get(key).cloned()1167 }11681169 /// Convert byte vector to property key vector.1170 pub fn bytes_keys_to_property_keys(1171 keys: Vec<Vec<u8>>,1172 ) -> Result<Vec<PropertyKey>, DispatchError> {1173 keys.into_iter()1174 .map(|key| -> Result<PropertyKey, DispatchError> {1175 key.try_into()1176 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1177 })1178 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1179 }11801181 /// Get properties according to given keys.1182 pub fn filter_collection_properties(1183 collection_id: CollectionId,1184 keys: Option<Vec<PropertyKey>>,1185 ) -> Result<Vec<Property>, DispatchError> {1186 let properties = Self::collection_properties(collection_id);11871188 let properties = keys1189 .map(|keys| {1190 keys.into_iter()1191 .filter_map(|key| {1192 properties.get(&key).map(|value| Property {1193 key,1194 value: value.clone(),1195 })1196 })1197 .collect()1198 })1199 .unwrap_or_else(|| {1200 properties1201 .into_iter()1202 .map(|(key, value)| Property { key, value })1203 .collect()1204 });12051206 Ok(properties)1207 }12081209 /// Get property permissions according to given keys.1210 pub fn filter_property_permissions(1211 collection_id: CollectionId,1212 keys: Option<Vec<PropertyKey>>,1213 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1214 let permissions = Self::property_permissions(collection_id);12151216 let key_permissions = keys1217 .map(|keys| {1218 keys.into_iter()1219 .filter_map(|key| {1220 permissions1221 .get(&key)1222 .map(|permission| PropertyKeyPermission {1223 key,1224 permission: permission.clone(),1225 })1226 })1227 .collect()1228 })1229 .unwrap_or_else(|| {1230 permissions1231 .into_iter()1232 .map(|(key, permission)| PropertyKeyPermission { key, permission })1233 .collect()1234 });12351236 Ok(key_permissions)1237 }12381239 /// Toggle `user` participation in the `collection`'s allow list.1240 pub fn toggle_allowlist(1241 collection: &CollectionHandle<T>,1242 sender: &T::CrossAccountId,1243 user: &T::CrossAccountId,1244 allowed: bool,1245 ) -> DispatchResult {1246 collection.check_is_owner_or_admin(sender)?;12471248 // =========12491250 if allowed {1251 <Allowlist<T>>::insert((collection.id, user), true);1252 } else {1253 <Allowlist<T>>::remove((collection.id, user));1254 }12551256 Ok(())1257 }12581259 /// Toggle `user` participation in the `collection`'s admin list.1260 pub fn toggle_admin(1261 collection: &CollectionHandle<T>,1262 sender: &T::CrossAccountId,1263 user: &T::CrossAccountId,1264 admin: bool,1265 ) -> DispatchResult {1266 collection.check_is_owner(sender)?;12671268 let was_admin = <IsAdmin<T>>::get((collection.id, user));1269 if was_admin == admin {1270 return Ok(());1271 }1272 let amount = <AdminAmount<T>>::get(collection.id);12731274 if admin {1275 let amount = amount1276 .checked_add(1)1277 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1278 ensure!(1279 amount <= Self::collection_admins_limit(),1280 <Error<T>>::CollectionAdminCountExceeded,1281 );12821283 // =========12841285 <AdminAmount<T>>::insert(collection.id, amount);1286 <IsAdmin<T>>::insert((collection.id, user), true);1287 } else {1288 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1289 <IsAdmin<T>>::remove((collection.id, user));1290 }12911292 Ok(())1293 }12941295 /// Merge set fields from `new_limit` to `old_limit`.1296 pub fn clamp_limits(1297 mode: CollectionMode,1298 old_limit: &CollectionLimits,1299 mut new_limit: CollectionLimits,1300 ) -> Result<CollectionLimits, DispatchError> {1301 let limits = old_limit;1302 limit_default!(old_limit, new_limit,1303 account_token_ownership_limit => ensure!(1304 new_limit <= MAX_TOKEN_OWNERSHIP,1305 <Error<T>>::CollectionLimitBoundsExceeded,1306 ),1307 sponsored_data_size => ensure!(1308 new_limit <= CUSTOM_DATA_LIMIT,1309 <Error<T>>::CollectionLimitBoundsExceeded,1310 ),13111312 sponsored_data_rate_limit => {},1313 token_limit => ensure!(1314 old_limit >= new_limit && new_limit > 0,1315 <Error<T>>::CollectionTokenLimitExceeded1316 ),13171318 sponsor_transfer_timeout(match mode {1319 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1320 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1321 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1322 }) => ensure!(1323 new_limit <= MAX_SPONSOR_TIMEOUT,1324 <Error<T>>::CollectionLimitBoundsExceeded,1325 ),1326 sponsor_approve_timeout => {},1327 owner_can_transfer => ensure!(1328 !limits.owner_can_transfer_instaled() ||1329 old_limit || !new_limit,1330 <Error<T>>::OwnerPermissionsCantBeReverted,1331 ),1332 owner_can_destroy => ensure!(1333 old_limit || !new_limit,1334 <Error<T>>::OwnerPermissionsCantBeReverted,1335 ),1336 transfers_enabled => {},1337 );1338 Ok(new_limit)1339 }13401341 /// Merge set fields from `new_permission` to `old_permission`.1342 pub fn clamp_permissions(1343 _mode: CollectionMode,1344 old_permission: &CollectionPermissions,1345 mut new_permission: CollectionPermissions,1346 ) -> Result<CollectionPermissions, DispatchError> {1347 limit_default_clone!(old_permission, new_permission,1348 access => {},1349 mint_mode => {},1350 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1351 );1352 Ok(new_permission)1353 }1354}13551356/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1357#[macro_export]1358macro_rules! unsupported {1359 () => {1360 Err(<Error<T>>::UnsupportedOperation.into())1361 };1362}13631364/// Return weights for various worst-case operations.1365pub trait CommonWeightInfo<CrossAccountId> {1366 /// Weight of item creation.1367 fn create_item() -> Weight;13681369 /// Weight of items creation.1370 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;13711372 /// Weight of items creation.1373 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;13741375 /// The weight of the burning item.1376 fn burn_item() -> Weight;13771378 /// Property setting weight.1379 ///1380 /// * `amount`- The number of properties to set.1381 fn set_collection_properties(amount: u32) -> Weight;13821383 /// Collection property deletion weight.1384 ///1385 /// * `amount`- The number of properties to set.1386 fn delete_collection_properties(amount: u32) -> Weight;13871388 /// Token property setting weight.1389 ///1390 /// * `amount`- The number of properties to set.1391 fn set_token_properties(amount: u32) -> Weight;13921393 /// Token property deletion weight.1394 ///1395 /// * `amount`- The number of properties to delete.1396 fn delete_token_properties(amount: u32) -> Weight;13971398 /// Token property permissions set weight.1399 ///1400 /// * `amount`- The number of property permissions to set.1401 fn set_token_property_permissions(amount: u32) -> Weight;14021403 /// Transfer price of the token or its parts.1404 fn transfer() -> Weight;14051406 /// The price of setting the permission of the operation from another user.1407 fn approve() -> Weight;14081409 /// Transfer price from another user.1410 fn transfer_from() -> Weight;14111412 /// The price of burning a token from another user.1413 fn burn_from() -> Weight;14141415 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1416 /// whole users's balance.1417 ///1418 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1419 fn burn_recursively_self_raw() -> Weight;14201421 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1422 ///1423 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1424 fn burn_recursively_breadth_raw(amount: u32) -> Weight;14251426 /// The price of recursive burning a token.1427 ///1428 /// `max_selfs` - The maximum burning weight of the token itself.1429 /// `max_breadth` - The maximum number of nested tokens to burn.1430 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1431 Self::burn_recursively_self_raw()1432 .saturating_mul(max_selfs.max(1) as u64)1433 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1434 }1435}14361437/// Weight info extension trait for refungible pallet.1438pub trait RefungibleExtensionsWeightInfo {1439 /// Weight of token repartition.1440 fn repartition() -> Weight;1441}14421443/// Common collection operations.1444///1445/// It wraps methods in Fungible, Nonfungible and Refungible pallets1446/// and adds weight info.1447pub trait CommonCollectionOperations<T: Config> {1448 /// Create token.1449 ///1450 /// * `sender` - The user who mint the token and pays for the transaction.1451 /// * `to` - The user who will own the token.1452 /// * `data` - Token data.1453 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1454 fn create_item(1455 &self,1456 sender: T::CrossAccountId,1457 to: T::CrossAccountId,1458 data: CreateItemData,1459 nesting_budget: &dyn Budget,1460 ) -> DispatchResultWithPostInfo;14611462 /// Create multiple tokens.1463 ///1464 /// * `sender` - The user who mint the token and pays for the transaction.1465 /// * `to` - The user who will own the token.1466 /// * `data` - Token data.1467 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1468 fn create_multiple_items(1469 &self,1470 sender: T::CrossAccountId,1471 to: T::CrossAccountId,1472 data: Vec<CreateItemData>,1473 nesting_budget: &dyn Budget,1474 ) -> DispatchResultWithPostInfo;14751476 /// Create multiple tokens.1477 ///1478 /// * `sender` - The user who mint the token and pays for the transaction.1479 /// * `to` - The user who will own the token.1480 /// * `data` - Token data.1481 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1482 fn create_multiple_items_ex(1483 &self,1484 sender: T::CrossAccountId,1485 data: CreateItemExData<T::CrossAccountId>,1486 nesting_budget: &dyn Budget,1487 ) -> DispatchResultWithPostInfo;14881489 /// Burn token.1490 ///1491 /// * `sender` - The user who owns the token.1492 /// * `token` - Token id that will burned.1493 /// * `amount` - The number of parts of the token that will be burned.1494 fn burn_item(1495 &self,1496 sender: T::CrossAccountId,1497 token: TokenId,1498 amount: u128,1499 ) -> DispatchResultWithPostInfo;15001501 /// Burn token and all nested tokens recursievly.1502 ///1503 /// * `sender` - The user who owns the token.1504 /// * `token` - Token id that will burned.1505 /// * `self_budget` - The budget that can be spent on burning tokens.1506 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1507 fn burn_item_recursively(1508 &self,1509 sender: T::CrossAccountId,1510 token: TokenId,1511 self_budget: &dyn Budget,1512 breadth_budget: &dyn Budget,1513 ) -> DispatchResultWithPostInfo;15141515 /// Set collection properties.1516 ///1517 /// * `sender` - Must be either the owner of the collection or its admin.1518 /// * `properties` - Properties to be set.1519 fn set_collection_properties(1520 &self,1521 sender: T::CrossAccountId,1522 properties: Vec<Property>,1523 ) -> DispatchResultWithPostInfo;15241525 /// Delete collection properties.1526 ///1527 /// * `sender` - Must be either the owner of the collection or its admin.1528 /// * `properties` - The properties to be removed.1529 fn delete_collection_properties(1530 &self,1531 sender: &T::CrossAccountId,1532 property_keys: Vec<PropertyKey>,1533 ) -> DispatchResultWithPostInfo;15341535 /// Set token properties.1536 ///1537 /// The appropriate [`PropertyPermission`] for the token property1538 /// must be set with [`Self::set_token_property_permissions`].1539 ///1540 /// * `sender` - Must be either the owner of the token or its admin.1541 /// * `token_id` - The token for which the properties are being set.1542 /// * `properties` - Properties to be set.1543 /// * `budget` - Budget for setting properties.1544 fn set_token_properties(1545 &self,1546 sender: T::CrossAccountId,1547 token_id: TokenId,1548 properties: Vec<Property>,1549 budget: &dyn Budget,1550 ) -> DispatchResultWithPostInfo;15511552 /// Remove token properties.1553 ///1554 /// The appropriate [`PropertyPermission`] for the token property1555 /// must be set with [`Self::set_token_property_permissions`].1556 ///1557 /// * `sender` - Must be either the owner of the token or its admin.1558 /// * `token_id` - The token for which the properties are being remove.1559 /// * `property_keys` - Keys to remove corresponding properties.1560 /// * `budget` - Budget for removing properties.1561 fn delete_token_properties(1562 &self,1563 sender: T::CrossAccountId,1564 token_id: TokenId,1565 property_keys: Vec<PropertyKey>,1566 budget: &dyn Budget,1567 ) -> DispatchResultWithPostInfo;15681569 /// Set token property permissions.1570 ///1571 /// * `sender` - Must be either the owner of the token or its admin.1572 /// * `token_id` - The token for which the properties are being set.1573 /// * `properties` - Properties to be set.1574 /// * `budget` - Budget for setting properties.1575 fn set_token_property_permissions(1576 &self,1577 sender: &T::CrossAccountId,1578 property_permissions: Vec<PropertyKeyPermission>,1579 ) -> DispatchResultWithPostInfo;15801581 /// Transfer amount of token pieces.1582 ///1583 /// * `sender` - Donor user.1584 /// * `to` - Recepient user.1585 /// * `token` - The token of which parts are being sent.1586 /// * `amount` - The number of parts of the token that will be transferred.1587 /// * `budget` - The maximum budget that can be spent on the transfer.1588 fn transfer(1589 &self,1590 sender: T::CrossAccountId,1591 to: T::CrossAccountId,1592 token: TokenId,1593 amount: u128,1594 budget: &dyn Budget,1595 ) -> DispatchResultWithPostInfo;15961597 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1598 ///1599 /// * `sender` - The user who grants access to the token.1600 /// * `spender` - The user to whom the rights are granted.1601 /// * `token` - The token to which access is granted.1602 /// * `amount` - The amount of pieces that another user can dispose of.1603 fn approve(1604 &self,1605 sender: T::CrossAccountId,1606 spender: T::CrossAccountId,1607 token: TokenId,1608 amount: u128,1609 ) -> DispatchResultWithPostInfo;16101611 /// Send parts of a token owned by another user.1612 ///1613 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1614 ///1615 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1616 /// * `from` - The user who owns the token.1617 /// * `to` - Recepient user.1618 /// * `token` - The token of which parts are being sent.1619 /// * `amount` - The number of parts of the token that will be transferred.1620 /// * `budget` - The maximum budget that can be spent on the transfer.1621 fn transfer_from(1622 &self,1623 sender: T::CrossAccountId,1624 from: T::CrossAccountId,1625 to: T::CrossAccountId,1626 token: TokenId,1627 amount: u128,1628 budget: &dyn Budget,1629 ) -> DispatchResultWithPostInfo;16301631 /// Burn parts of a token owned by another user.1632 ///1633 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1634 ///1635 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1636 /// * `from` - The user who owns the token.1637 /// * `token` - The token of which parts are being sent.1638 /// * `amount` - The number of parts of the token that will be transferred.1639 /// * `budget` - The maximum budget that can be spent on the burn.1640 fn burn_from(1641 &self,1642 sender: T::CrossAccountId,1643 from: T::CrossAccountId,1644 token: TokenId,1645 amount: u128,1646 budget: &dyn Budget,1647 ) -> DispatchResultWithPostInfo;16481649 /// Check permission to nest token.1650 ///1651 /// * `sender` - The user who initiated the check.1652 /// * `from` - The token that is checked for embedding.1653 /// * `under` - Token under which to check.1654 /// * `budget` - The maximum budget that can be spent on the check.1655 fn check_nesting(1656 &self,1657 sender: T::CrossAccountId,1658 from: (CollectionId, TokenId),1659 under: TokenId,1660 budget: &dyn Budget,1661 ) -> DispatchResult;16621663 /// Nest one token into another.1664 ///1665 /// * `under` - Token holder.1666 /// * `to_nest` - Nested token.1667 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16681669 /// Unnest token.1670 ///1671 /// * `under` - Token holder.1672 /// * `to_nest` - Token to unnest.1673 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16741675 /// Get all user tokens.1676 ///1677 /// * `account` - Account for which you need to get tokens.1678 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;16791680 /// Get all the tokens in the collection.1681 fn collection_tokens(&self) -> Vec<TokenId>;16821683 /// Check if the token exists.1684 ///1685 /// * `token` - Id token to check.1686 fn token_exists(&self, token: TokenId) -> bool;16871688 /// Get the id of the last minted token.1689 fn last_token_id(&self) -> TokenId;16901691 /// Get the owner of the token.1692 ///1693 /// * `token` - The token for which you need to find out the owner.1694 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;16951696 /// Returns 10 tokens owners in no particular order.1697 ///1698 /// * `token` - The token for which you need to find out the owners.1699 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17001701 /// Get the value of the token property by key.1702 ///1703 /// * `token` - Token with the property to get.1704 /// * `key` - Property name.1705 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17061707 /// Get a set of token properties by key vector.1708 ///1709 /// * `token` - Token with the property to get.1710 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1711 /// then all properties are returned.1712 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17131714 /// Amount of unique collection tokens1715 fn total_supply(&self) -> u32;17161717 /// Amount of different tokens account has.1718 ///1719 /// * `account` - The account for which need to get the balance.1720 fn account_balance(&self, account: T::CrossAccountId) -> u32;17211722 /// Amount of specific token account have.1723 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17241725 /// Amount of token pieces1726 fn total_pieces(&self, token: TokenId) -> Option<u128>;17271728 /// Get the number of parts of the token that a trusted user can manage.1729 ///1730 /// * `sender` - Trusted user.1731 /// * `spender` - Owner of the token.1732 /// * `token` - The token for which to get the value.1733 fn allowance(1734 &self,1735 sender: T::CrossAccountId,1736 spender: T::CrossAccountId,1737 token: TokenId,1738 ) -> u128;17391740 /// Get extension for RFT collection.1741 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1742}17431744/// Extension for RFT collection.1745pub trait RefungibleExtensions<T>1746where1747 T: Config,1748{1749 /// Change the number of parts of the token.1750 ///1751 /// When the value changes down, this function is equivalent to burning parts of the token.1752 ///1753 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1754 /// * `token` - The token for which you want to change the number of parts.1755 /// * `amount` - The new value of the parts of the token.1756 fn repartition(1757 &self,1758 sender: &T::CrossAccountId,1759 token: TokenId,1760 amount: u128,1761 ) -> DispatchResultWithPostInfo;1762}17631764/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1765///1766/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1767pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1768 let post_info = PostDispatchInfo {1769 actual_weight: Some(weight),1770 pays_fee: Pays::Yes,1771 };1772 match res {1773 Ok(()) => Ok(post_info),1774 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1775 }1776}17771778impl<T: Config> From<PropertiesError> for Error<T> {1779 fn from(error: PropertiesError) -> Self {1780 match error {1781 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1782 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1783 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1784 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1785 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1786 }1787 }1788}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 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionId,74 CreateItemData,75 MAX_TOKEN_PREFIX_LENGTH,76 COLLECTION_ADMINS_LIMIT,77 TokenId,78 TokenChild,79 CollectionStats,80 MAX_TOKEN_OWNERSHIP,81 CollectionMode,82 NFT_SPONSOR_TRANSFER_TIMEOUT,83 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 MAX_SPONSOR_TIMEOUT,86 CUSTOM_DATA_LIMIT,87 CollectionLimits,88 CreateCollectionData,89 SponsorshipState,90 CreateItemExData,91 SponsoringRateLimit,92 budget::Budget,93 PhantomType,94 Property,95 Properties,96 PropertiesPermissionMap,97 PropertyKey,98 PropertyValue,99 PropertyPermission,100 PropertiesError,101 PropertyKeyPermission,102 TokenData,103 TrySetProperty,104 PropertyScope,105 // RMRK106 RmrkCollectionInfo,107 RmrkInstanceInfo,108 RmrkResourceInfo,109 RmrkPropertyInfo,110 RmrkBaseInfo,111 RmrkPartType,112 RmrkBoundedTheme,113 RmrkNftChild,114 CollectionPermissions,115 SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139 /// Collection id140 pub id: CollectionId,141 collection: Collection<T::AccountId>,142 /// Substrate recorder for counting consumed gas143 pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 &self.recorder149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.recorder152 }153}154155impl<T: Config> CollectionHandle<T> {156 /// Same as [CollectionHandle::new] but with an explicit gas limit.157 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158 <CollectionById<T>>::get(id).map(|collection| Self {159 id,160 collection,161 recorder: SubstrateRecorder::new(gas_limit),162 })163 }164165 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder,171 })172 }173174 /// Retrives collection data from storage and creates collection handle with default parameters.175 /// If collection not found return `None`176 pub fn new(id: CollectionId) -> Option<Self> {177 Self::new_with_gas_limit(id, u64::MAX)178 }179180 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183 }184185 /// Consume gas for reading.186 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187 self.recorder188 .consume_gas(T::GasWeightMapping::weight_to_gas(189 <T as frame_system::Config>::DbWeight::get()190 .read191 .saturating_mul(reads),192 ))193 }194195 /// Consume gas for writing.196 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197 self.recorder198 .consume_gas(T::GasWeightMapping::weight_to_gas(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 ))203 }204205 /// Save collection to storage.206 pub fn save(self) -> DispatchResult {207 <CollectionById<T>>::insert(self.id, self.collection);208 Ok(())209 }210211 /// Set collection sponsor.212 ///213 /// Unique collections allows sponsoring for certain actions.214 /// This method allows you to set the sponsor of the collection.215 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218 Ok(())219 }220221 /// Confirm sponsorship222 ///223 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226 if self.collection.sponsorship.pending_sponsor() != Some(sender) {227 return Ok(false);228 }229230 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231 Ok(true)232 }233234 /// Checks that the collection was created with, and must be operated upon through **Unique API**.235 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236 pub fn check_is_internal(&self) -> DispatchResult {237 if self.external_collection {238 return Err(<Error<T>>::CollectionIsExternal)?;239 }240241 Ok(())242 }243244 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246 pub fn check_is_external(&self) -> DispatchResult {247 if !self.external_collection {248 return Err(<Error<T>>::CollectionIsInternal)?;249 }250251 Ok(())252 }253}254255impl<T: Config> Deref for CollectionHandle<T> {256 type Target = Collection<T::AccountId>;257258 fn deref(&self) -> &Self::Target {259 &self.collection260 }261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264 fn deref_mut(&mut self) -> &mut Self::Target {265 &mut self.collection266 }267}268269impl<T: Config> CollectionHandle<T> {270 /// Checks if the `user` is the owner of the collection.271 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273 Ok(())274 }275276 /// Returns **true** if the `user` is the owner or administrator of the collection.277 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279 }280281 /// Checks if the `user` is the owner or administrator of the collection.282 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284 Ok(())285 }286287 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290 }291292 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295 }296297 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299 ensure!(300 <Allowlist<T>>::get((self.id, user)),301 <Error<T>>::AddressNotInAllowlist302 );303 Ok(())304 }305}306307#[frame_support::pallet]308pub mod pallet {309 use super::*;310 use pallet_evm::account;311 use dispatch::CollectionDispatch;312 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313 use frame_system::pallet_prelude::*;314 use frame_support::traits::Currency;315 use up_data_structs::{TokenId, mapping::TokenAddressMapping};316 use scale_info::TypeInfo;317 use weights::WeightInfo;318319 #[pallet::config]320 pub trait Config:321 frame_system::Config322 + pallet_evm_coder_substrate::Config323 + pallet_evm::Config324 + TypeInfo325 + account::Config326 {327 /// Weight information for functions of this pallet.328 type WeightInfo: WeightInfo;329330 /// Events compatible with [`frame_system::Config::Event`].331 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333 /// Handler of accounts and payment.334 type Currency: Currency<Self::AccountId>;335336 /// Set price to create a collection.337 #[pallet::constant]338 type CollectionCreationPrice: Get<339 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340 >;341342 /// Dispatcher of operations on collections.343 type CollectionDispatch: CollectionDispatch<Self>;344345 /// Account which holds the chain's treasury.346 type TreasuryAccountId: Get<Self::AccountId>;347348 /// Address under which the CollectionHelper contract would be available.349 type ContractAddress: Get<H160>;350351 /// Mapper for token addresses to Ethereum addresses.352 type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354 /// Mapper for token addresses to [`CrossAccountId`].355 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356 }357358 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360 #[pallet::pallet]361 #[pallet::storage_version(STORAGE_VERSION)]362 #[pallet::generate_store(pub(super) trait Store)]363 pub struct Pallet<T>(_);364365 #[pallet::extra_constants]366 impl<T: Config> Pallet<T> {367 /// Maximum admins per collection.368 pub fn collection_admins_limit() -> u32 {369 COLLECTION_ADMINS_LIMIT370 }371 }372373 #[pallet::event]374 #[pallet::generate_deposit(pub fn deposit_event)]375 pub enum Event<T: Config> {376 /// New collection was created377 CollectionCreated(378 /// Globally unique identifier of newly created collection.379 CollectionId,380 /// [`CollectionMode`] converted into _u8_.381 u8,382 /// Collection owner.383 T::AccountId,384 ),385386 /// New collection was destroyed387 CollectionDestroyed(388 /// Globally unique identifier of collection.389 CollectionId,390 ),391392 /// New item was created.393 ItemCreated(394 /// Id of the collection where item was created.395 CollectionId,396 /// Id of an item. Unique within the collection.397 TokenId,398 /// Owner of newly created item399 T::CrossAccountId,400 /// Always 1 for NFT401 u128,402 ),403404 /// Collection item was burned.405 ItemDestroyed(406 /// Id of the collection where item was destroyed.407 CollectionId,408 /// Identifier of burned NFT.409 TokenId,410 /// Which user has destroyed its tokens.411 T::CrossAccountId,412 /// Amount of token pieces destroed. Always 1 for NFT.413 u128,414 ),415416 /// Item was transferred417 Transfer(418 /// Id of collection to which item is belong.419 CollectionId,420 /// Id of an item.421 TokenId,422 /// Original owner of item.423 T::CrossAccountId,424 /// New owner of item.425 T::CrossAccountId,426 /// Amount of token pieces transfered. Always 1 for NFT.427 u128,428 ),429430 /// Amount pieces of token owned by `sender` was approved for `spender`.431 Approved(432 /// Id of collection to which item is belong.433 CollectionId,434 /// Id of an item.435 TokenId,436 /// Original owner of item.437 T::CrossAccountId,438 /// Id for which the approval was granted.439 T::CrossAccountId,440 /// Amount of token pieces transfered. Always 1 for NFT.441 u128,442 ),443444 /// The colletion property has been added or edited.445 CollectionPropertySet(446 /// Id of collection to which property has been set.447 CollectionId,448 /// The property that was set.449 PropertyKey,450 ),451452 /// The property has been deleted.453 CollectionPropertyDeleted(454 /// Id of collection to which property has been deleted.455 CollectionId,456 /// The property that was deleted.457 PropertyKey,458 ),459460 /// The token property has been added or edited.461 TokenPropertySet(462 /// Identifier of the collection whose token has the property set.463 CollectionId,464 /// The token for which the property was set.465 TokenId,466 /// The property that was set.467 PropertyKey,468 ),469470 /// The token property has been deleted.471 TokenPropertyDeleted(472 /// Identifier of the collection whose token has the property deleted.473 CollectionId,474 /// The token for which the property was deleted.475 TokenId,476 /// The property that was deleted.477 PropertyKey,478 ),479480 /// The token property permission of a collection has been set.481 PropertyPermissionSet(482 /// ID of collection to which property permission has been set.483 CollectionId,484 /// The property permission that was set.485 PropertyKey,486 ),487 }488489 #[pallet::error]490 pub enum Error<T> {491 /// This collection does not exist.492 CollectionNotFound,493 /// Sender parameter and item owner must be equal.494 MustBeTokenOwner,495 /// No permission to perform action496 NoPermission,497 /// Destroying only empty collections is allowed498 CantDestroyNotEmptyCollection,499 /// Collection is not in mint mode.500 PublicMintingNotAllowed,501 /// Address is not in allow list.502 AddressNotInAllowlist,503504 /// Collection name can not be longer than 63 char.505 CollectionNameLimitExceeded,506 /// Collection description can not be longer than 255 char.507 CollectionDescriptionLimitExceeded,508 /// Token prefix can not be longer than 15 char.509 CollectionTokenPrefixLimitExceeded,510 /// Total collections bound exceeded.511 TotalCollectionsLimitExceeded,512 /// Exceeded max admin count513 CollectionAdminCountExceeded,514 /// Collection limit bounds per collection exceeded515 CollectionLimitBoundsExceeded,516 /// Tried to enable permissions which are only permitted to be disabled517 OwnerPermissionsCantBeReverted,518 /// Collection settings not allowing items transferring519 TransferNotAllowed,520 /// Account token limit exceeded per collection521 AccountTokenLimitExceeded,522 /// Collection token limit exceeded523 CollectionTokenLimitExceeded,524 /// Metadata flag frozen525 MetadataFlagFrozen,526527 /// Item does not exist528 TokenNotFound,529 /// Item is balance not enough530 TokenValueTooLow,531 /// Requested value is more than the approved532 ApprovedValueTooLow,533 /// Tried to approve more than owned534 CantApproveMoreThanOwned,535536 /// Can't transfer tokens to ethereum zero address537 AddressIsZero,538539 /// The oprtation is not supported540 UnsupportedOperation,541542 /// Insufficient funds to perform an action543 NotSufficientFounds,544545 /// User does not satisfy the nesting rule546 UserIsNotAllowedToNest,547 /// Only tokens from specific collections may nest tokens under this one548 SourceCollectionIsNotAllowedToNest,549550 /// Tried to store more data than allowed in collection field551 CollectionFieldSizeExceeded,552553 /// Tried to store more property data than allowed554 NoSpaceForProperty,555556 /// Tried to store more property keys than allowed557 PropertyLimitReached,558559 /// Property key is too long560 PropertyKeyIsTooLong,561562 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed563 InvalidCharacterInPropertyKey,564565 /// Empty property keys are forbidden566 EmptyPropertyKey,567568 /// Tried to access an external collection with an internal API569 CollectionIsExternal,570571 /// Tried to access an internal collection with an external API572 CollectionIsInternal,573 }574575 /// Storage of the count of created collections. Essentially contains the last collection ID.576 #[pallet::storage]577 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;578579 /// Storage of the count of deleted collections.580 #[pallet::storage]581 pub type DestroyedCollectionCount<T> =582 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;583584 /// Storage of collection info.585 #[pallet::storage]586 pub type CollectionById<T> = StorageMap<587 Hasher = Blake2_128Concat,588 Key = CollectionId,589 Value = Collection<<T as frame_system::Config>::AccountId>,590 QueryKind = OptionQuery,591 >;592593 /// Storage of collection properties.594 #[pallet::storage]595 #[pallet::getter(fn collection_properties)]596 pub type CollectionProperties<T> = StorageMap<597 Hasher = Blake2_128Concat,598 Key = CollectionId,599 Value = Properties,600 QueryKind = ValueQuery,601 OnEmpty = up_data_structs::CollectionProperties,602 >;603604 /// Storage of token property permissions of a collection.605 #[pallet::storage]606 #[pallet::getter(fn property_permissions)]607 pub type CollectionPropertyPermissions<T> = StorageMap<608 Hasher = Blake2_128Concat,609 Key = CollectionId,610 Value = PropertiesPermissionMap,611 QueryKind = ValueQuery,612 >;613614 /// Storage of the amount of collection admins.615 #[pallet::storage]616 pub type AdminAmount<T> = StorageMap<617 Hasher = Blake2_128Concat,618 Key = CollectionId,619 Value = u32,620 QueryKind = ValueQuery,621 >;622623 /// List of collection admins.624 #[pallet::storage]625 pub type IsAdmin<T: Config> = StorageNMap<626 Key = (627 Key<Blake2_128Concat, CollectionId>,628 Key<Blake2_128Concat, T::CrossAccountId>,629 ),630 Value = bool,631 QueryKind = ValueQuery,632 >;633634 /// Allowlisted collection users.635 #[pallet::storage]636 pub type Allowlist<T: Config> = StorageNMap<637 Key = (638 Key<Blake2_128Concat, CollectionId>,639 Key<Blake2_128Concat, T::CrossAccountId>,640 ),641 Value = bool,642 QueryKind = ValueQuery,643 >;644645 /// Not used by code, exists only to provide some types to metadata.646 #[pallet::storage]647 pub type DummyStorageValue<T: Config> = StorageValue<648 Value = (649 CollectionStats,650 CollectionId,651 TokenId,652 TokenChild,653 PhantomType<(654 TokenData<T::CrossAccountId>,655 RpcCollection<T::AccountId>,656 // RMRK657 RmrkCollectionInfo<T::AccountId>,658 RmrkInstanceInfo<T::AccountId>,659 RmrkResourceInfo,660 RmrkPropertyInfo,661 RmrkBaseInfo<T::AccountId>,662 RmrkPartType,663 RmrkBoundedTheme,664 RmrkNftChild,665 )>,666 ),667 QueryKind = OptionQuery,668 >;669670 #[pallet::hooks]671 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {672 fn on_runtime_upgrade() -> Weight {673 StorageVersion::new(1).put::<Pallet<T>>();674675 0676 }677 }678}679680impl<T: Config> Pallet<T> {681 /// Enshure that receiver address is correct.682 ///683 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.684 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {685 ensure!(686 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,687 <Error<T>>::AddressIsZero688 );689 Ok(())690 }691692 /// Get a vector of collection admins.693 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {694 <IsAdmin<T>>::iter_prefix((collection,))695 .map(|(a, _)| a)696 .collect()697 }698699 /// Get a vector of users allowed to mint tokens.700 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {701 <Allowlist<T>>::iter_prefix((collection,))702 .map(|(a, _)| a)703 .collect()704 }705706 /// Is `user` allowed to mint token in `collection`.707 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {708 <Allowlist<T>>::get((collection, user))709 }710711 /// Get statistics of collections.712 pub fn collection_stats() -> CollectionStats {713 let created = <CreatedCollectionCount<T>>::get();714 let destroyed = <DestroyedCollectionCount<T>>::get();715 CollectionStats {716 created: created.0,717 destroyed: destroyed.0,718 alive: created.0 - destroyed.0,719 }720 }721722 /// Get the effective limits for the collection.723 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {724 let collection = <CollectionById<T>>::get(collection);725 if collection.is_none() {726 return None;727 }728729 let collection = collection.unwrap();730 let limits = collection.limits;731 let effective_limits = CollectionLimits {732 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),733 sponsored_data_size: Some(limits.sponsored_data_size()),734 sponsored_data_rate_limit: Some(735 limits736 .sponsored_data_rate_limit737 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),738 ),739 token_limit: Some(limits.token_limit()),740 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(741 match collection.mode {742 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,743 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,744 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,745 },746 )),747 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),748 owner_can_transfer: Some(limits.owner_can_transfer()),749 owner_can_destroy: Some(limits.owner_can_destroy()),750 transfers_enabled: Some(limits.transfers_enabled()),751 };752753 Some(effective_limits)754 }755756 /// Returns information about the `collection` adapted for rpc.757 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {758 let Collection {759 name,760 description,761 owner,762 mode,763 token_prefix,764 sponsorship,765 limits,766 permissions,767 external_collection,768 } = <CollectionById<T>>::get(collection)?;769770 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)771 .into_iter()772 .map(|(key, permission)| PropertyKeyPermission { key, permission })773 .collect();774775 let properties = <CollectionProperties<T>>::get(collection)776 .into_iter()777 .map(|(key, value)| Property { key, value })778 .collect();779780 let permissions = CollectionPermissions {781 access: Some(permissions.access()),782 mint_mode: Some(permissions.mint_mode()),783 nesting: Some(permissions.nesting().clone()),784 };785786 Some(RpcCollection {787 name: name.into_inner(),788 description: description.into_inner(),789 owner,790 mode,791 token_prefix: token_prefix.into_inner(),792 sponsorship,793 limits,794 permissions,795 token_property_permissions,796 properties,797 read_only: external_collection,798 })799 }800}801802macro_rules! limit_default {803 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{804 $(805 if let Some($new) = $new.$field {806 let $old = $old.$field($($arg)?);807 let _ = $new;808 let _ = $old;809 $check810 } else {811 $new.$field = $old.$field812 }813 )*814 }};815}816macro_rules! limit_default_clone {817 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{818 $(819 if let Some($new) = $new.$field.clone() {820 let $old = $old.$field($($arg)?);821 let _ = $new;822 let _ = $old;823 $check824 } else {825 $new.$field = $old.$field.clone()826 }827 )*828 }};829}830831impl<T: Config> Pallet<T> {832 /// Create new collection.833 ///834 /// * `owner` - The owner of the collection.835 /// * `data` - Description of the created collection.836 /// * `is_external` - Marks that collection managet by not "Unique network".837 pub fn init_collection(838 owner: T::CrossAccountId,839 data: CreateCollectionData<T::AccountId>,840 is_external: bool,841 ) -> Result<CollectionId, DispatchError> {842 {843 ensure!(844 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,845 Error::<T>::CollectionTokenPrefixLimitExceeded846 );847 }848849 let created_count = <CreatedCollectionCount<T>>::get()850 .0851 .checked_add(1)852 .ok_or(ArithmeticError::Overflow)?;853 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;854 let id = CollectionId(created_count);855856 // bound Total number of collections857 ensure!(858 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,859 <Error<T>>::TotalCollectionsLimitExceeded860 );861862 // =========863864 let collection = Collection {865 owner: owner.as_sub().clone(),866 name: data.name,867 mode: data.mode.clone(),868 description: data.description,869 token_prefix: data.token_prefix,870 sponsorship: data871 .pending_sponsor872 .map(SponsorshipState::Unconfirmed)873 .unwrap_or_default(),874 limits: data875 .limits876 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))877 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,878 permissions: data879 .permissions880 .map(|permissions| {881 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)882 })883 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,884 external_collection: is_external,885 };886887 let mut collection_properties = up_data_structs::CollectionProperties::get();888 collection_properties889 .try_set_from_iter(data.properties.into_iter())890 .map_err(<Error<T>>::from)?;891892 CollectionProperties::<T>::insert(id, collection_properties);893894 let mut token_props_permissions = PropertiesPermissionMap::new();895 token_props_permissions896 .try_set_from_iter(data.token_property_permissions.into_iter())897 .map_err(<Error<T>>::from)?;898899 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);900901 // Take a (non-refundable) deposit of collection creation902 {903 let mut imbalance =904 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();905 imbalance.subsume(906 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(907 &T::TreasuryAccountId::get(),908 T::CollectionCreationPrice::get(),909 ),910 );911 <T as Config>::Currency::settle(912 owner.as_sub(),913 imbalance,914 WithdrawReasons::TRANSFER,915 ExistenceRequirement::KeepAlive,916 )917 .map_err(|_| Error::<T>::NotSufficientFounds)?;918 }919920 <CreatedCollectionCount<T>>::put(created_count);921 <Pallet<T>>::deposit_event(Event::CollectionCreated(922 id,923 data.mode.id(),924 owner.as_sub().clone(),925 ));926 <PalletEvm<T>>::deposit_log(927 erc::CollectionHelpersEvents::CollectionCreated {928 owner: *owner.as_eth(),929 collection_id: eth::collection_id_to_address(id),930 }931 .to_log(T::ContractAddress::get()),932 );933 <CollectionById<T>>::insert(id, collection);934 Ok(id)935 }936937 /// Destroy collection.938 ///939 /// * `collection` - Collection handler.940 /// * `sender` - The owner or administrator of the collection.941 pub fn destroy_collection(942 collection: CollectionHandle<T>,943 sender: &T::CrossAccountId,944 ) -> DispatchResult {945 ensure!(946 collection.limits.owner_can_destroy(),947 <Error<T>>::NoPermission,948 );949 collection.check_is_owner(sender)?;950951 let destroyed_collections = <DestroyedCollectionCount<T>>::get()952 .0953 .checked_add(1)954 .ok_or(ArithmeticError::Overflow)?;955956 // =========957958 <DestroyedCollectionCount<T>>::put(destroyed_collections);959 <CollectionById<T>>::remove(collection.id);960 <AdminAmount<T>>::remove(collection.id);961 <IsAdmin<T>>::remove_prefix((collection.id,), None);962 <Allowlist<T>>::remove_prefix((collection.id,), None);963 <CollectionProperties<T>>::remove(collection.id);964965 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));966 Ok(())967 }968969 /// Set collection property.970 ///971 /// * `collection` - Collection handler.972 /// * `sender` - The owner or administrator of the collection.973 /// * `property` - The property to set.974 pub fn set_collection_property(975 collection: &CollectionHandle<T>,976 sender: &T::CrossAccountId,977 property: Property,978 ) -> DispatchResult {979 collection.check_is_owner_or_admin(sender)?;980981 CollectionProperties::<T>::try_mutate(collection.id, |properties| {982 let property = property.clone();983 properties.try_set(property.key, property.value)984 })985 .map_err(<Error<T>>::from)?;986987 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));988989 Ok(())990 }991992 /// Set scouped collection property.993 ///994 /// * `collection_id` - ID of the collection for which the property is being set.995 /// * `scope` - Property scope.996 /// * `property` - The property to set.997 pub fn set_scoped_collection_property(998 collection_id: CollectionId,999 scope: PropertyScope,1000 property: Property,1001 ) -> DispatchResult {1002 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1003 properties.try_scoped_set(scope, property.key, property.value)1004 })1005 .map_err(<Error<T>>::from)?;10061007 Ok(())1008 }10091010 /// Set scouped collection properties.1011 ///1012 /// * `collection_id` - ID of the collection for which the properties is being set.1013 /// * `scope` - Property scope.1014 /// * `properties` - The properties to set.1015 pub fn set_scoped_collection_properties(1016 collection_id: CollectionId,1017 scope: PropertyScope,1018 properties: impl Iterator<Item = Property>,1019 ) -> DispatchResult {1020 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1021 stored_properties.try_scoped_set_from_iter(scope, properties)1022 })1023 .map_err(<Error<T>>::from)?;10241025 Ok(())1026 }10271028 /// Set collection properties.1029 ///1030 /// * `collection` - Collection handler.1031 /// * `sender` - The owner or administrator of the collection.1032 /// * `properties` - The properties to set.1033 #[transactional]1034 pub fn set_collection_properties(1035 collection: &CollectionHandle<T>,1036 sender: &T::CrossAccountId,1037 properties: Vec<Property>,1038 ) -> DispatchResult {1039 for property in properties {1040 Self::set_collection_property(collection, sender, property)?;1041 }10421043 Ok(())1044 }10451046 /// Delete collection property.1047 ///1048 /// * `collection` - Collection handler.1049 /// * `sender` - The owner or administrator of the collection.1050 /// * `property` - The property to delete.1051 pub fn delete_collection_property(1052 collection: &CollectionHandle<T>,1053 sender: &T::CrossAccountId,1054 property_key: PropertyKey,1055 ) -> DispatchResult {1056 collection.check_is_owner_or_admin(sender)?;10571058 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1059 properties.remove(&property_key)1060 })1061 .map_err(<Error<T>>::from)?;10621063 Self::deposit_event(Event::CollectionPropertyDeleted(1064 collection.id,1065 property_key,1066 ));10671068 Ok(())1069 }10701071 /// Delete collection properties.1072 ///1073 /// * `collection` - Collection handler.1074 /// * `sender` - The owner or administrator of the collection.1075 /// * `properties` - The properties to delete.1076 #[transactional]1077 pub fn delete_collection_properties(1078 collection: &CollectionHandle<T>,1079 sender: &T::CrossAccountId,1080 property_keys: Vec<PropertyKey>,1081 ) -> DispatchResult {1082 for key in property_keys {1083 Self::delete_collection_property(collection, sender, key)?;1084 }10851086 Ok(())1087 }10881089 /// Set collection propetry permission without any checks.1090 ///1091 /// Used for migrations.1092 ///1093 /// * `collection` - Collection handler.1094 /// * `property_permissions` - Property permissions.1095 pub fn set_property_permission_unchecked(1096 collection: CollectionId,1097 property_permission: PropertyKeyPermission,1098 ) -> DispatchResult {1099 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1100 permissions.try_set(property_permission.key, property_permission.permission)1101 })1102 .map_err(<Error<T>>::from)?;1103 Ok(())1104 }11051106 /// Set collection property permission.1107 ///1108 /// * `collection` - Collection handler.1109 /// * `sender` - The owner or administrator of the collection.1110 /// * `property_permission` - Property permission.1111 pub fn set_property_permission(1112 collection: &CollectionHandle<T>,1113 sender: &T::CrossAccountId,1114 property_permission: PropertyKeyPermission,1115 ) -> DispatchResult {1116 collection.check_is_owner_or_admin(sender)?;11171118 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1119 let current_permission = all_permissions.get(&property_permission.key);1120 if matches![1121 current_permission,1122 Some(PropertyPermission { mutable: false, .. })1123 ] {1124 return Err(<Error<T>>::NoPermission.into());1125 }11261127 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1128 let property_permission = property_permission.clone();1129 permissions.try_set(property_permission.key, property_permission.permission)1130 })1131 .map_err(<Error<T>>::from)?;11321133 Self::deposit_event(Event::PropertyPermissionSet(1134 collection.id,1135 property_permission.key,1136 ));11371138 Ok(())1139 }11401141 /// Set token property permission.1142 ///1143 /// * `collection` - Collection handler.1144 /// * `sender` - The owner or administrator of the collection.1145 /// * `property_permissions` - Property permissions.1146 #[transactional]1147 pub fn set_token_property_permissions(1148 collection: &CollectionHandle<T>,1149 sender: &T::CrossAccountId,1150 property_permissions: Vec<PropertyKeyPermission>,1151 ) -> DispatchResult {1152 for prop_pemission in property_permissions {1153 Self::set_property_permission(collection, sender, prop_pemission)?;1154 }11551156 Ok(())1157 }11581159 /// Get collection property.1160 pub fn get_collection_property(1161 collection_id: CollectionId,1162 key: &PropertyKey,1163 ) -> Option<PropertyValue> {1164 Self::collection_properties(collection_id).get(key).cloned()1165 }11661167 /// Convert byte vector to property key vector.1168 pub fn bytes_keys_to_property_keys(1169 keys: Vec<Vec<u8>>,1170 ) -> Result<Vec<PropertyKey>, DispatchError> {1171 keys.into_iter()1172 .map(|key| -> Result<PropertyKey, DispatchError> {1173 key.try_into()1174 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1175 })1176 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1177 }11781179 /// Get properties according to given keys.1180 pub fn filter_collection_properties(1181 collection_id: CollectionId,1182 keys: Option<Vec<PropertyKey>>,1183 ) -> Result<Vec<Property>, DispatchError> {1184 let properties = Self::collection_properties(collection_id);11851186 let properties = keys1187 .map(|keys| {1188 keys.into_iter()1189 .filter_map(|key| {1190 properties.get(&key).map(|value| Property {1191 key,1192 value: value.clone(),1193 })1194 })1195 .collect()1196 })1197 .unwrap_or_else(|| {1198 properties1199 .into_iter()1200 .map(|(key, value)| Property { key, value })1201 .collect()1202 });12031204 Ok(properties)1205 }12061207 /// Get property permissions according to given keys.1208 pub fn filter_property_permissions(1209 collection_id: CollectionId,1210 keys: Option<Vec<PropertyKey>>,1211 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1212 let permissions = Self::property_permissions(collection_id);12131214 let key_permissions = keys1215 .map(|keys| {1216 keys.into_iter()1217 .filter_map(|key| {1218 permissions1219 .get(&key)1220 .map(|permission| PropertyKeyPermission {1221 key,1222 permission: permission.clone(),1223 })1224 })1225 .collect()1226 })1227 .unwrap_or_else(|| {1228 permissions1229 .into_iter()1230 .map(|(key, permission)| PropertyKeyPermission { key, permission })1231 .collect()1232 });12331234 Ok(key_permissions)1235 }12361237 /// Toggle `user` participation in the `collection`'s allow list.1238 pub fn toggle_allowlist(1239 collection: &CollectionHandle<T>,1240 sender: &T::CrossAccountId,1241 user: &T::CrossAccountId,1242 allowed: bool,1243 ) -> DispatchResult {1244 collection.check_is_owner_or_admin(sender)?;12451246 // =========12471248 if allowed {1249 <Allowlist<T>>::insert((collection.id, user), true);1250 } else {1251 <Allowlist<T>>::remove((collection.id, user));1252 }12531254 Ok(())1255 }12561257 /// Toggle `user` participation in the `collection`'s admin list.1258 pub fn toggle_admin(1259 collection: &CollectionHandle<T>,1260 sender: &T::CrossAccountId,1261 user: &T::CrossAccountId,1262 admin: bool,1263 ) -> DispatchResult {1264 collection.check_is_owner(sender)?;12651266 let was_admin = <IsAdmin<T>>::get((collection.id, user));1267 if was_admin == admin {1268 return Ok(());1269 }1270 let amount = <AdminAmount<T>>::get(collection.id);12711272 if admin {1273 let amount = amount1274 .checked_add(1)1275 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1276 ensure!(1277 amount <= Self::collection_admins_limit(),1278 <Error<T>>::CollectionAdminCountExceeded,1279 );12801281 // =========12821283 <AdminAmount<T>>::insert(collection.id, amount);1284 <IsAdmin<T>>::insert((collection.id, user), true);1285 } else {1286 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1287 <IsAdmin<T>>::remove((collection.id, user));1288 }12891290 Ok(())1291 }12921293 /// Merge set fields from `new_limit` to `old_limit`.1294 pub fn clamp_limits(1295 mode: CollectionMode,1296 old_limit: &CollectionLimits,1297 mut new_limit: CollectionLimits,1298 ) -> Result<CollectionLimits, DispatchError> {1299 let limits = old_limit;1300 limit_default!(old_limit, new_limit,1301 account_token_ownership_limit => ensure!(1302 new_limit <= MAX_TOKEN_OWNERSHIP,1303 <Error<T>>::CollectionLimitBoundsExceeded,1304 ),1305 sponsored_data_size => ensure!(1306 new_limit <= CUSTOM_DATA_LIMIT,1307 <Error<T>>::CollectionLimitBoundsExceeded,1308 ),13091310 sponsored_data_rate_limit => {},1311 token_limit => ensure!(1312 old_limit >= new_limit && new_limit > 0,1313 <Error<T>>::CollectionTokenLimitExceeded1314 ),13151316 sponsor_transfer_timeout(match mode {1317 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1318 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1319 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1320 }) => ensure!(1321 new_limit <= MAX_SPONSOR_TIMEOUT,1322 <Error<T>>::CollectionLimitBoundsExceeded,1323 ),1324 sponsor_approve_timeout => {},1325 owner_can_transfer => ensure!(1326 !limits.owner_can_transfer_instaled() ||1327 old_limit || !new_limit,1328 <Error<T>>::OwnerPermissionsCantBeReverted,1329 ),1330 owner_can_destroy => ensure!(1331 old_limit || !new_limit,1332 <Error<T>>::OwnerPermissionsCantBeReverted,1333 ),1334 transfers_enabled => {},1335 );1336 Ok(new_limit)1337 }13381339 /// Merge set fields from `new_permission` to `old_permission`.1340 pub fn clamp_permissions(1341 _mode: CollectionMode,1342 old_permission: &CollectionPermissions,1343 mut new_permission: CollectionPermissions,1344 ) -> Result<CollectionPermissions, DispatchError> {1345 limit_default_clone!(old_permission, new_permission,1346 access => {},1347 mint_mode => {},1348 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1349 );1350 Ok(new_permission)1351 }1352}13531354/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1355#[macro_export]1356macro_rules! unsupported {1357 ($runtime:path) => {1358 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1359 };1360}13611362/// Return weights for various worst-case operations.1363pub trait CommonWeightInfo<CrossAccountId> {1364 /// Weight of item creation.1365 fn create_item() -> Weight;13661367 /// Weight of items creation.1368 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;13691370 /// Weight of items creation.1371 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;13721373 /// The weight of the burning item.1374 fn burn_item() -> Weight;13751376 /// Property setting weight.1377 ///1378 /// * `amount`- The number of properties to set.1379 fn set_collection_properties(amount: u32) -> Weight;13801381 /// Collection property deletion weight.1382 ///1383 /// * `amount`- The number of properties to set.1384 fn delete_collection_properties(amount: u32) -> Weight;13851386 /// Token property setting weight.1387 ///1388 /// * `amount`- The number of properties to set.1389 fn set_token_properties(amount: u32) -> Weight;13901391 /// Token property deletion weight.1392 ///1393 /// * `amount`- The number of properties to delete.1394 fn delete_token_properties(amount: u32) -> Weight;13951396 /// Token property permissions set weight.1397 ///1398 /// * `amount`- The number of property permissions to set.1399 fn set_token_property_permissions(amount: u32) -> Weight;14001401 /// Transfer price of the token or its parts.1402 fn transfer() -> Weight;14031404 /// The price of setting the permission of the operation from another user.1405 fn approve() -> Weight;14061407 /// Transfer price from another user.1408 fn transfer_from() -> Weight;14091410 /// The price of burning a token from another user.1411 fn burn_from() -> Weight;14121413 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1414 /// whole users's balance.1415 ///1416 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1417 fn burn_recursively_self_raw() -> Weight;14181419 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1420 ///1421 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1422 fn burn_recursively_breadth_raw(amount: u32) -> Weight;14231424 /// The price of recursive burning a token.1425 ///1426 /// `max_selfs` - The maximum burning weight of the token itself.1427 /// `max_breadth` - The maximum number of nested tokens to burn.1428 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1429 Self::burn_recursively_self_raw()1430 .saturating_mul(max_selfs.max(1) as u64)1431 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1432 }1433}14341435/// Weight info extension trait for refungible pallet.1436pub trait RefungibleExtensionsWeightInfo {1437 /// Weight of token repartition.1438 fn repartition() -> Weight;1439}14401441/// Common collection operations.1442///1443/// It wraps methods in Fungible, Nonfungible and Refungible pallets1444/// and adds weight info.1445pub trait CommonCollectionOperations<T: Config> {1446 /// Create token.1447 ///1448 /// * `sender` - The user who mint the token and pays for the transaction.1449 /// * `to` - The user who will own the token.1450 /// * `data` - Token data.1451 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1452 fn create_item(1453 &self,1454 sender: T::CrossAccountId,1455 to: T::CrossAccountId,1456 data: CreateItemData,1457 nesting_budget: &dyn Budget,1458 ) -> DispatchResultWithPostInfo;14591460 /// Create multiple tokens.1461 ///1462 /// * `sender` - The user who mint the token and pays for the transaction.1463 /// * `to` - The user who will own the token.1464 /// * `data` - Token data.1465 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1466 fn create_multiple_items(1467 &self,1468 sender: T::CrossAccountId,1469 to: T::CrossAccountId,1470 data: Vec<CreateItemData>,1471 nesting_budget: &dyn Budget,1472 ) -> DispatchResultWithPostInfo;14731474 /// Create multiple tokens.1475 ///1476 /// * `sender` - The user who mint the token and pays for the transaction.1477 /// * `to` - The user who will own the token.1478 /// * `data` - Token data.1479 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1480 fn create_multiple_items_ex(1481 &self,1482 sender: T::CrossAccountId,1483 data: CreateItemExData<T::CrossAccountId>,1484 nesting_budget: &dyn Budget,1485 ) -> DispatchResultWithPostInfo;14861487 /// Burn token.1488 ///1489 /// * `sender` - The user who owns the token.1490 /// * `token` - Token id that will burned.1491 /// * `amount` - The number of parts of the token that will be burned.1492 fn burn_item(1493 &self,1494 sender: T::CrossAccountId,1495 token: TokenId,1496 amount: u128,1497 ) -> DispatchResultWithPostInfo;14981499 /// Burn token and all nested tokens recursievly.1500 ///1501 /// * `sender` - The user who owns the token.1502 /// * `token` - Token id that will burned.1503 /// * `self_budget` - The budget that can be spent on burning tokens.1504 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1505 fn burn_item_recursively(1506 &self,1507 sender: T::CrossAccountId,1508 token: TokenId,1509 self_budget: &dyn Budget,1510 breadth_budget: &dyn Budget,1511 ) -> DispatchResultWithPostInfo;15121513 /// Set collection properties.1514 ///1515 /// * `sender` - Must be either the owner of the collection or its admin.1516 /// * `properties` - Properties to be set.1517 fn set_collection_properties(1518 &self,1519 sender: T::CrossAccountId,1520 properties: Vec<Property>,1521 ) -> DispatchResultWithPostInfo;15221523 /// Delete collection properties.1524 ///1525 /// * `sender` - Must be either the owner of the collection or its admin.1526 /// * `properties` - The properties to be removed.1527 fn delete_collection_properties(1528 &self,1529 sender: &T::CrossAccountId,1530 property_keys: Vec<PropertyKey>,1531 ) -> DispatchResultWithPostInfo;15321533 /// Set token properties.1534 ///1535 /// The appropriate [`PropertyPermission`] for the token property1536 /// must be set with [`Self::set_token_property_permissions`].1537 ///1538 /// * `sender` - Must be either the owner of the token or its admin.1539 /// * `token_id` - The token for which the properties are being set.1540 /// * `properties` - Properties to be set.1541 /// * `budget` - Budget for setting properties.1542 fn set_token_properties(1543 &self,1544 sender: T::CrossAccountId,1545 token_id: TokenId,1546 properties: Vec<Property>,1547 budget: &dyn Budget,1548 ) -> DispatchResultWithPostInfo;15491550 /// Remove token properties.1551 ///1552 /// The appropriate [`PropertyPermission`] for the token property1553 /// must be set with [`Self::set_token_property_permissions`].1554 ///1555 /// * `sender` - Must be either the owner of the token or its admin.1556 /// * `token_id` - The token for which the properties are being remove.1557 /// * `property_keys` - Keys to remove corresponding properties.1558 /// * `budget` - Budget for removing properties.1559 fn delete_token_properties(1560 &self,1561 sender: T::CrossAccountId,1562 token_id: TokenId,1563 property_keys: Vec<PropertyKey>,1564 budget: &dyn Budget,1565 ) -> DispatchResultWithPostInfo;15661567 /// Set token property permissions.1568 ///1569 /// * `sender` - Must be either the owner of the token or its admin.1570 /// * `token_id` - The token for which the properties are being set.1571 /// * `properties` - Properties to be set.1572 /// * `budget` - Budget for setting properties.1573 fn set_token_property_permissions(1574 &self,1575 sender: &T::CrossAccountId,1576 property_permissions: Vec<PropertyKeyPermission>,1577 ) -> DispatchResultWithPostInfo;15781579 /// Transfer amount of token pieces.1580 ///1581 /// * `sender` - Donor user.1582 /// * `to` - Recepient user.1583 /// * `token` - The token of which parts are being sent.1584 /// * `amount` - The number of parts of the token that will be transferred.1585 /// * `budget` - The maximum budget that can be spent on the transfer.1586 fn transfer(1587 &self,1588 sender: T::CrossAccountId,1589 to: T::CrossAccountId,1590 token: TokenId,1591 amount: u128,1592 budget: &dyn Budget,1593 ) -> DispatchResultWithPostInfo;15941595 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1596 ///1597 /// * `sender` - The user who grants access to the token.1598 /// * `spender` - The user to whom the rights are granted.1599 /// * `token` - The token to which access is granted.1600 /// * `amount` - The amount of pieces that another user can dispose of.1601 fn approve(1602 &self,1603 sender: T::CrossAccountId,1604 spender: T::CrossAccountId,1605 token: TokenId,1606 amount: u128,1607 ) -> DispatchResultWithPostInfo;16081609 /// Send parts of a token owned by another user.1610 ///1611 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1612 ///1613 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1614 /// * `from` - The user who owns the token.1615 /// * `to` - Recepient user.1616 /// * `token` - The token of which parts are being sent.1617 /// * `amount` - The number of parts of the token that will be transferred.1618 /// * `budget` - The maximum budget that can be spent on the transfer.1619 fn transfer_from(1620 &self,1621 sender: T::CrossAccountId,1622 from: T::CrossAccountId,1623 to: T::CrossAccountId,1624 token: TokenId,1625 amount: u128,1626 budget: &dyn Budget,1627 ) -> DispatchResultWithPostInfo;16281629 /// Burn parts of a token owned by another user.1630 ///1631 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1632 ///1633 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1634 /// * `from` - The user who owns the token.1635 /// * `token` - The token of which parts are being sent.1636 /// * `amount` - The number of parts of the token that will be transferred.1637 /// * `budget` - The maximum budget that can be spent on the burn.1638 fn burn_from(1639 &self,1640 sender: T::CrossAccountId,1641 from: T::CrossAccountId,1642 token: TokenId,1643 amount: u128,1644 budget: &dyn Budget,1645 ) -> DispatchResultWithPostInfo;16461647 /// Check permission to nest token.1648 ///1649 /// * `sender` - The user who initiated the check.1650 /// * `from` - The token that is checked for embedding.1651 /// * `under` - Token under which to check.1652 /// * `budget` - The maximum budget that can be spent on the check.1653 fn check_nesting(1654 &self,1655 sender: T::CrossAccountId,1656 from: (CollectionId, TokenId),1657 under: TokenId,1658 budget: &dyn Budget,1659 ) -> DispatchResult;16601661 /// Nest one token into another.1662 ///1663 /// * `under` - Token holder.1664 /// * `to_nest` - Nested token.1665 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16661667 /// Unnest token.1668 ///1669 /// * `under` - Token holder.1670 /// * `to_nest` - Token to unnest.1671 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16721673 /// Get all user tokens.1674 ///1675 /// * `account` - Account for which you need to get tokens.1676 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;16771678 /// Get all the tokens in the collection.1679 fn collection_tokens(&self) -> Vec<TokenId>;16801681 /// Check if the token exists.1682 ///1683 /// * `token` - Id token to check.1684 fn token_exists(&self, token: TokenId) -> bool;16851686 /// Get the id of the last minted token.1687 fn last_token_id(&self) -> TokenId;16881689 /// Get the owner of the token.1690 ///1691 /// * `token` - The token for which you need to find out the owner.1692 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;16931694 /// Returns 10 tokens owners in no particular order.1695 ///1696 /// * `token` - The token for which you need to find out the owners.1697 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;16981699 /// Get the value of the token property by key.1700 ///1701 /// * `token` - Token with the property to get.1702 /// * `key` - Property name.1703 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17041705 /// Get a set of token properties by key vector.1706 ///1707 /// * `token` - Token with the property to get.1708 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1709 /// then all properties are returned.1710 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17111712 /// Amount of unique collection tokens1713 fn total_supply(&self) -> u32;17141715 /// Amount of different tokens account has.1716 ///1717 /// * `account` - The account for which need to get the balance.1718 fn account_balance(&self, account: T::CrossAccountId) -> u32;17191720 /// Amount of specific token account have.1721 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17221723 /// Amount of token pieces1724 fn total_pieces(&self, token: TokenId) -> Option<u128>;17251726 /// Get the number of parts of the token that a trusted user can manage.1727 ///1728 /// * `sender` - Trusted user.1729 /// * `spender` - Owner of the token.1730 /// * `token` - The token for which to get the value.1731 fn allowance(1732 &self,1733 sender: T::CrossAccountId,1734 spender: T::CrossAccountId,1735 token: TokenId,1736 ) -> u128;17371738 /// Get extension for RFT collection.1739 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1740}17411742/// Extension for RFT collection.1743pub trait RefungibleExtensions<T>1744where1745 T: Config,1746{1747 /// Change the number of parts of the token.1748 ///1749 /// When the value changes down, this function is equivalent to burning parts of the token.1750 ///1751 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1752 /// * `token` - The token for which you want to change the number of parts.1753 /// * `amount` - The new value of the parts of the token.1754 fn repartition(1755 &self,1756 sender: &T::CrossAccountId,1757 token: TokenId,1758 amount: u128,1759 ) -> DispatchResultWithPostInfo;1760}17611762/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1763///1764/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1765pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1766 let post_info = PostDispatchInfo {1767 actual_weight: Some(weight),1768 pays_fee: Pays::Yes,1769 };1770 match res {1771 Ok(()) => Ok(post_info),1772 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1773 }1774}17751776impl<T: Config> From<PropertiesError> for Error<T> {1777 fn from(error: PropertiesError) -> Self {1778 match error {1779 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1780 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1781 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1782 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1783 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1784 }1785 }1786}runtime/common/dispatch.rsdiffbeforeafterboth--- a/runtime/common/dispatch.rs
+++ b/runtime/common/dispatch.rs
@@ -34,6 +34,9 @@
CollectionId,
};
+#[cfg(not(feature = "refungible"))]
+use pallet_common::unsupported;
+
pub enum CollectionDispatchT<T>
where
T: pallet_fungible::Config + pallet_nonfungible::Config + pallet_refungible::Config,
@@ -64,13 +67,12 @@
);
<PalletFungible<T>>::init_collection(sender, data)?
}
+
#[cfg(feature = "refungible")]
CollectionMode::ReFungible => <PalletRefungible<T>>::init_collection(sender, data)?,
#[cfg(not(feature = "refungible"))]
- CollectionMode::ReFungible => {
- return Err(DispatchError::Other("Refunginle pallet is not supported"))
- }
+ CollectionMode::ReFungible => return unsupported!(T)
};
Ok(id)
}
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -43,7 +43,12 @@
};
use common_types::{AccountId, BlockNumber};
-pub type CommonError = pallet_common::Error<Runtime>;
+#[macro_export]
+macro_rules! unsupported {
+ () => {
+ pallet_common::unsupported!($crate::Runtime)
+ }
+}
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -205,7 +205,7 @@
return pallet_proxy_rmrk_core::rpc::last_collection_idx::<Runtime>();
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -214,7 +214,7 @@
return pallet_proxy_rmrk_core::rpc::collection_by_id::<Runtime>(collection_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -223,7 +223,7 @@
return pallet_proxy_rmrk_core::rpc::nft_by_id::<Runtime>(collection_id, nft_by_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -232,7 +232,7 @@
return pallet_proxy_rmrk_core::rpc::account_tokens::<Runtime>(account_id, collection_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -241,7 +241,7 @@
return pallet_proxy_rmrk_core::rpc::nft_children::<Runtime>(collection_id, nft_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -253,7 +253,7 @@
return pallet_proxy_rmrk_core::rpc::collection_properties::<Runtime>(collection_id, filter_keys);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -266,7 +266,7 @@
return pallet_proxy_rmrk_core::rpc::nft_properties::<Runtime>(collection_id, nft_id, filter_keys);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -275,7 +275,7 @@
return pallet_proxy_rmrk_core::rpc::nft_resources::<Runtime>(collection_id, nft_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -288,7 +288,7 @@
return pallet_proxy_rmrk_core::rpc::nft_resource_priority::<Runtime>(collection_id, nft_id, resource_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -297,7 +297,7 @@
return pallet_proxy_rmrk_equip::rpc::base::<Runtime>(base_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -306,7 +306,7 @@
return pallet_proxy_rmrk_equip::rpc::base_parts::<Runtime>(base_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -315,7 +315,7 @@
return pallet_proxy_rmrk_equip::rpc::theme_names::<Runtime>(base_id);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
#[allow(unused_variables)]
@@ -328,7 +328,7 @@
return pallet_proxy_rmrk_equip::rpc::theme::<Runtime>(base_id, theme_name, filter_keys);
#[cfg(not(feature = "rmrk"))]
- return Err(CommonError::UnsupportedRuntimeApi.into());
+ return unsupported!();
}
}