difftreelog
fix cargo fmt
in: master
7 files changed
crates/evm-coder/src/execution.rsdiffbeforeafterboth--- a/crates/evm-coder/src/execution.rs
+++ b/crates/evm-coder/src/execution.rs
@@ -60,12 +60,16 @@
}
impl From<u64> for DispatchInfo {
fn from(weight: u64) -> Self {
- Self { weight: Weight::from_ref_time(weight) }
+ Self {
+ weight: Weight::from_ref_time(weight),
+ }
}
}
impl From<()> for DispatchInfo {
fn from(_: ()) -> Self {
- Self { weight: Weight::zero() }
+ Self {
+ weight: Weight::zero(),
+ }
}
}
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -327,7 +327,7 @@
Arc::new(RelayChainRpcInterface::new(rpc_client)) as Arc<_>,
None,
))
- },
+ }
None => build_inprocess_relay_chain(
polkadot_config,
parachain_config,
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 CollectionFlags,74 CollectionId,75 CreateItemData,76 MAX_TOKEN_PREFIX_LENGTH,77 COLLECTION_ADMINS_LIMIT,78 TokenId,79 TokenChild,80 CollectionStats,81 MAX_TOKEN_OWNERSHIP,82 CollectionMode,83 NFT_SPONSOR_TRANSFER_TIMEOUT,84 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 MAX_SPONSOR_TIMEOUT,87 CUSTOM_DATA_LIMIT,88 CollectionLimits,89 CreateCollectionData,90 SponsorshipState,91 CreateItemExData,92 SponsoringRateLimit,93 budget::Budget,94 PhantomType,95 Property,96 Properties,97 PropertiesPermissionMap,98 PropertyKey,99 PropertyValue,100 PropertyPermission,101 PropertiesError,102 PropertyKeyPermission,103 TokenData,104 TrySetProperty,105 PropertyScope,106 // RMRK107 RmrkCollectionInfo,108 RmrkInstanceInfo,109 RmrkResourceInfo,110 RmrkPropertyInfo,111 RmrkBaseInfo,112 RmrkPartType,113 RmrkBoundedTheme,114 RmrkNftChild,115 CollectionPermissions,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 Weight::from_ref_time(190 <T as frame_system::Config>::DbWeight::get()191 .read192 .saturating_mul(reads)193 ),194 ))195 }196197 /// Consume gas for writing.198 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199 self.recorder200 .consume_gas(T::GasWeightMapping::weight_to_gas(201 Weight::from_ref_time(202 <T as frame_system::Config>::DbWeight::get()203 .write204 .saturating_mul(writes)205 ),206 ))207 }208209 /// Consume gas for reading and writing.210 pub fn consume_store_reads_and_writes(211 &self,212 reads: u64,213 writes: u64,214 ) -> evm_coder::execution::Result<()> {215 let weight = <T as frame_system::Config>::DbWeight::get();216 let reads = weight.read.saturating_mul(reads);217 let writes = weight.read.saturating_mul(writes);218 self.recorder219 .consume_gas(T::GasWeightMapping::weight_to_gas(220 Weight::from_ref_time(reads.saturating_add(writes)),221 ))222 }223224 /// Save collection to storage.225 pub fn save(&self) -> DispatchResult {226 <CollectionById<T>>::insert(self.id, &self.collection);227 Ok(())228 }229230 /// Set collection sponsor.231 ///232 /// Unique collections allows sponsoring for certain actions.233 /// This method allows you to set the sponsor of the collection.234 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].235 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {236 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);237 Ok(())238 }239240 /// Confirm sponsorship241 ///242 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.243 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].244 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {245 if self.collection.sponsorship.pending_sponsor() != Some(sender) {246 return Ok(false);247 }248249 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());250 Ok(true)251 }252253 /// Remove collection sponsor.254 pub fn remove_sponsor(&mut self) -> DispatchResult {255 self.collection.sponsorship = SponsorshipState::Disabled;256 Ok(())257 }258259 /// Checks that the collection was created with, and must be operated upon through **Unique API**.260 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.261 pub fn check_is_internal(&self) -> DispatchResult {262 if self.flags.external {263 return Err(<Error<T>>::CollectionIsExternal)?;264 }265266 Ok(())267 }268269 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.270 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.271 pub fn check_is_external(&self) -> DispatchResult {272 if !self.flags.external {273 return Err(<Error<T>>::CollectionIsInternal)?;274 }275276 Ok(())277 }278}279280impl<T: Config> Deref for CollectionHandle<T> {281 type Target = Collection<T::AccountId>;282283 fn deref(&self) -> &Self::Target {284 &self.collection285 }286}287288impl<T: Config> DerefMut for CollectionHandle<T> {289 fn deref_mut(&mut self) -> &mut Self::Target {290 &mut self.collection291 }292}293294impl<T: Config> CollectionHandle<T> {295 /// Checks if the `user` is the owner of the collection.296 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {297 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);298 Ok(())299 }300301 /// Returns **true** if the `user` is the owner or administrator of the collection.302 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {303 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))304 }305306 /// Checks if the `user` is the owner or administrator of the collection.307 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {308 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);309 Ok(())310 }311312 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.313 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {314 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)315 }316317 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.318 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {319 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)320 }321322 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.323 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {324 ensure!(325 <Allowlist<T>>::get((self.id, user)),326 <Error<T>>::AddressNotInAllowlist327 );328 Ok(())329 }330331 /// Changes collection owner to another account332 /// #### Store read/writes333 /// 1 writes334 fn set_owner_internal(335 &mut self,336 caller: T::CrossAccountId,337 new_owner: T::CrossAccountId,338 ) -> DispatchResult {339 self.check_is_owner(&caller)?;340 self.collection.owner = new_owner.as_sub().clone();341 self.save()342 }343}344345#[frame_support::pallet]346pub mod pallet {347 use super::*;348 use pallet_evm::account;349 use dispatch::CollectionDispatch;350 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};351 use frame_system::pallet_prelude::*;352 use frame_support::traits::Currency;353 use up_data_structs::{TokenId, mapping::TokenAddressMapping};354 use scale_info::TypeInfo;355 use weights::WeightInfo;356357 #[pallet::config]358 pub trait Config:359 frame_system::Config360 + pallet_evm_coder_substrate::Config361 + pallet_evm::Config362 + TypeInfo363 + account::Config364 {365 /// Weight information for functions of this pallet.366 type WeightInfo: WeightInfo;367368 /// Events compatible with [`frame_system::Config::Event`].369 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;370371 /// Handler of accounts and payment.372 type Currency: Currency<Self::AccountId>;373374 /// Set price to create a collection.375 #[pallet::constant]376 type CollectionCreationPrice: Get<377 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,378 >;379380 /// Dispatcher of operations on collections.381 type CollectionDispatch: CollectionDispatch<Self>;382383 /// Account which holds the chain's treasury.384 type TreasuryAccountId: Get<Self::AccountId>;385386 /// Address under which the CollectionHelper contract would be available.387 type ContractAddress: Get<H160>;388389 /// Mapper for token addresses to Ethereum addresses.390 type EvmTokenAddressMapping: TokenAddressMapping<H160>;391392 /// Mapper for token addresses to [`CrossAccountId`].393 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;394 }395396 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);397398 #[pallet::pallet]399 #[pallet::storage_version(STORAGE_VERSION)]400 #[pallet::generate_store(pub(super) trait Store)]401 pub struct Pallet<T>(_);402403 #[pallet::extra_constants]404 impl<T: Config> Pallet<T> {405 /// Maximum admins per collection.406 pub fn collection_admins_limit() -> u32 {407 COLLECTION_ADMINS_LIMIT408 }409 }410411 #[pallet::event]412 #[pallet::generate_deposit(pub fn deposit_event)]413 pub enum Event<T: Config> {414 /// New collection was created415 CollectionCreated(416 /// Globally unique identifier of newly created collection.417 CollectionId,418 /// [`CollectionMode`] converted into _u8_.419 u8,420 /// Collection owner.421 T::AccountId,422 ),423424 /// New collection was destroyed425 CollectionDestroyed(426 /// Globally unique identifier of collection.427 CollectionId,428 ),429430 /// New item was created.431 ItemCreated(432 /// Id of the collection where item was created.433 CollectionId,434 /// Id of an item. Unique within the collection.435 TokenId,436 /// Owner of newly created item437 T::CrossAccountId,438 /// Always 1 for NFT439 u128,440 ),441442 /// Collection item was burned.443 ItemDestroyed(444 /// Id of the collection where item was destroyed.445 CollectionId,446 /// Identifier of burned NFT.447 TokenId,448 /// Which user has destroyed its tokens.449 T::CrossAccountId,450 /// Amount of token pieces destroed. Always 1 for NFT.451 u128,452 ),453454 /// Item was transferred455 Transfer(456 /// Id of collection to which item is belong.457 CollectionId,458 /// Id of an item.459 TokenId,460 /// Original owner of item.461 T::CrossAccountId,462 /// New owner of item.463 T::CrossAccountId,464 /// Amount of token pieces transfered. Always 1 for NFT.465 u128,466 ),467468 /// Amount pieces of token owned by `sender` was approved for `spender`.469 Approved(470 /// Id of collection to which item is belong.471 CollectionId,472 /// Id of an item.473 TokenId,474 /// Original owner of item.475 T::CrossAccountId,476 /// Id for which the approval was granted.477 T::CrossAccountId,478 /// Amount of token pieces transfered. Always 1 for NFT.479 u128,480 ),481482 /// The colletion property has been added or edited.483 CollectionPropertySet(484 /// Id of collection to which property has been set.485 CollectionId,486 /// The property that was set.487 PropertyKey,488 ),489490 /// The property has been deleted.491 CollectionPropertyDeleted(492 /// Id of collection to which property has been deleted.493 CollectionId,494 /// The property that was deleted.495 PropertyKey,496 ),497498 /// The token property has been added or edited.499 TokenPropertySet(500 /// Identifier of the collection whose token has the property set.501 CollectionId,502 /// The token for which the property was set.503 TokenId,504 /// The property that was set.505 PropertyKey,506 ),507508 /// The token property has been deleted.509 TokenPropertyDeleted(510 /// Identifier of the collection whose token has the property deleted.511 CollectionId,512 /// The token for which the property was deleted.513 TokenId,514 /// The property that was deleted.515 PropertyKey,516 ),517518 /// The token property permission of a collection has been set.519 PropertyPermissionSet(520 /// ID of collection to which property permission has been set.521 CollectionId,522 /// The property permission that was set.523 PropertyKey,524 ),525 }526527 #[pallet::error]528 pub enum Error<T> {529 /// This collection does not exist.530 CollectionNotFound,531 /// Sender parameter and item owner must be equal.532 MustBeTokenOwner,533 /// No permission to perform action534 NoPermission,535 /// Destroying only empty collections is allowed536 CantDestroyNotEmptyCollection,537 /// Collection is not in mint mode.538 PublicMintingNotAllowed,539 /// Address is not in allow list.540 AddressNotInAllowlist,541542 /// Collection name can not be longer than 63 char.543 CollectionNameLimitExceeded,544 /// Collection description can not be longer than 255 char.545 CollectionDescriptionLimitExceeded,546 /// Token prefix can not be longer than 15 char.547 CollectionTokenPrefixLimitExceeded,548 /// Total collections bound exceeded.549 TotalCollectionsLimitExceeded,550 /// Exceeded max admin count551 CollectionAdminCountExceeded,552 /// Collection limit bounds per collection exceeded553 CollectionLimitBoundsExceeded,554 /// Tried to enable permissions which are only permitted to be disabled555 OwnerPermissionsCantBeReverted,556 /// Collection settings not allowing items transferring557 TransferNotAllowed,558 /// Account token limit exceeded per collection559 AccountTokenLimitExceeded,560 /// Collection token limit exceeded561 CollectionTokenLimitExceeded,562 /// Metadata flag frozen563 MetadataFlagFrozen,564565 /// Item does not exist566 TokenNotFound,567 /// Item is balance not enough568 TokenValueTooLow,569 /// Requested value is more than the approved570 ApprovedValueTooLow,571 /// Tried to approve more than owned572 CantApproveMoreThanOwned,573574 /// Can't transfer tokens to ethereum zero address575 AddressIsZero,576577 /// The operation is not supported578 UnsupportedOperation,579580 /// Insufficient funds to perform an action581 NotSufficientFounds,582583 /// User does not satisfy the nesting rule584 UserIsNotAllowedToNest,585 /// Only tokens from specific collections may nest tokens under this one586 SourceCollectionIsNotAllowedToNest,587588 /// Tried to store more data than allowed in collection field589 CollectionFieldSizeExceeded,590591 /// Tried to store more property data than allowed592 NoSpaceForProperty,593594 /// Tried to store more property keys than allowed595 PropertyLimitReached,596597 /// Property key is too long598 PropertyKeyIsTooLong,599600 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed601 InvalidCharacterInPropertyKey,602603 /// Empty property keys are forbidden604 EmptyPropertyKey,605606 /// Tried to access an external collection with an internal API607 CollectionIsExternal,608609 /// Tried to access an internal collection with an external API610 CollectionIsInternal,611 }612613 /// Storage of the count of created collections. Essentially contains the last collection ID.614 #[pallet::storage]615 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;616617 /// Storage of the count of deleted collections.618 #[pallet::storage]619 pub type DestroyedCollectionCount<T> =620 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;621622 /// Storage of collection info.623 #[pallet::storage]624 pub type CollectionById<T> = StorageMap<625 Hasher = Blake2_128Concat,626 Key = CollectionId,627 Value = Collection<<T as frame_system::Config>::AccountId>,628 QueryKind = OptionQuery,629 >;630631 /// Storage of collection properties.632 #[pallet::storage]633 #[pallet::getter(fn collection_properties)]634 pub type CollectionProperties<T> = StorageMap<635 Hasher = Blake2_128Concat,636 Key = CollectionId,637 Value = Properties,638 QueryKind = ValueQuery,639 OnEmpty = up_data_structs::CollectionProperties,640 >;641642 /// Storage of token property permissions of a collection.643 #[pallet::storage]644 #[pallet::getter(fn property_permissions)]645 pub type CollectionPropertyPermissions<T> = StorageMap<646 Hasher = Blake2_128Concat,647 Key = CollectionId,648 Value = PropertiesPermissionMap,649 QueryKind = ValueQuery,650 >;651652 /// Storage of the amount of collection admins.653 #[pallet::storage]654 pub type AdminAmount<T> = StorageMap<655 Hasher = Blake2_128Concat,656 Key = CollectionId,657 Value = u32,658 QueryKind = ValueQuery,659 >;660661 /// List of collection admins.662 #[pallet::storage]663 pub type IsAdmin<T: Config> = StorageNMap<664 Key = (665 Key<Blake2_128Concat, CollectionId>,666 Key<Blake2_128Concat, T::CrossAccountId>,667 ),668 Value = bool,669 QueryKind = ValueQuery,670 >;671672 /// Allowlisted collection users.673 #[pallet::storage]674 pub type Allowlist<T: Config> = StorageNMap<675 Key = (676 Key<Blake2_128Concat, CollectionId>,677 Key<Blake2_128Concat, T::CrossAccountId>,678 ),679 Value = bool,680 QueryKind = ValueQuery,681 >;682683 /// Not used by code, exists only to provide some types to metadata.684 #[pallet::storage]685 pub type DummyStorageValue<T: Config> = StorageValue<686 Value = (687 CollectionStats,688 CollectionId,689 TokenId,690 TokenChild,691 PhantomType<(692 TokenData<T::CrossAccountId>,693 RpcCollection<T::AccountId>,694 // RMRK695 RmrkCollectionInfo<T::AccountId>,696 RmrkInstanceInfo<T::AccountId>,697 RmrkResourceInfo,698 RmrkPropertyInfo,699 RmrkBaseInfo<T::AccountId>,700 RmrkPartType,701 RmrkBoundedTheme,702 RmrkNftChild,703 )>,704 ),705 QueryKind = OptionQuery,706 >;707708 #[pallet::hooks]709 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {710 fn on_runtime_upgrade() -> Weight {711 StorageVersion::new(1).put::<Pallet<T>>();712713 Weight::zero()714 }715 }716}717718impl<T: Config> Pallet<T> {719 /// Enshure that receiver address is correct.720 ///721 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.722 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {723 ensure!(724 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,725 <Error<T>>::AddressIsZero726 );727 Ok(())728 }729730 /// Get a vector of collection admins.731 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {732 <IsAdmin<T>>::iter_prefix((collection,))733 .map(|(a, _)| a)734 .collect()735 }736737 /// Get a vector of users allowed to mint tokens.738 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {739 <Allowlist<T>>::iter_prefix((collection,))740 .map(|(a, _)| a)741 .collect()742 }743744 /// Is `user` allowed to mint token in `collection`.745 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {746 <Allowlist<T>>::get((collection, user))747 }748749 /// Get statistics of collections.750 pub fn collection_stats() -> CollectionStats {751 let created = <CreatedCollectionCount<T>>::get();752 let destroyed = <DestroyedCollectionCount<T>>::get();753 CollectionStats {754 created: created.0,755 destroyed: destroyed.0,756 alive: created.0 - destroyed.0,757 }758 }759760 /// Get the effective limits for the collection.761 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {762 let collection = <CollectionById<T>>::get(collection)?;763 let limits = collection.limits;764 let effective_limits = CollectionLimits {765 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),766 sponsored_data_size: Some(limits.sponsored_data_size()),767 sponsored_data_rate_limit: Some(768 limits769 .sponsored_data_rate_limit770 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),771 ),772 token_limit: Some(limits.token_limit()),773 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(774 match collection.mode {775 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,776 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,777 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,778 },779 )),780 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),781 owner_can_transfer: Some(limits.owner_can_transfer()),782 owner_can_destroy: Some(limits.owner_can_destroy()),783 transfers_enabled: Some(limits.transfers_enabled()),784 };785786 Some(effective_limits)787 }788789 /// Returns information about the `collection` adapted for rpc.790 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {791 let Collection {792 name,793 description,794 owner,795 mode,796 token_prefix,797 sponsorship,798 limits,799 permissions,800 flags,801 } = <CollectionById<T>>::get(collection)?;802803 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)804 .into_iter()805 .map(|(key, permission)| PropertyKeyPermission { key, permission })806 .collect();807808 let properties = <CollectionProperties<T>>::get(collection)809 .into_iter()810 .map(|(key, value)| Property { key, value })811 .collect();812813 let permissions = CollectionPermissions {814 access: Some(permissions.access()),815 mint_mode: Some(permissions.mint_mode()),816 nesting: Some(permissions.nesting().clone()),817 };818819 Some(RpcCollection {820 name: name.into_inner(),821 description: description.into_inner(),822 owner,823 mode,824 token_prefix: token_prefix.into_inner(),825 sponsorship,826 limits,827 permissions,828 token_property_permissions,829 properties,830 read_only: flags.external,831 foreign: flags.foreign,832 })833 }834}835836macro_rules! limit_default {837 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{838 $(839 if let Some($new) = $new.$field {840 let $old = $old.$field($($arg)?);841 let _ = $new;842 let _ = $old;843 $check844 } else {845 $new.$field = $old.$field846 }847 )*848 }};849}850macro_rules! limit_default_clone {851 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{852 $(853 if let Some($new) = $new.$field.clone() {854 let $old = $old.$field($($arg)?);855 let _ = $new;856 let _ = $old;857 $check858 } else {859 $new.$field = $old.$field.clone()860 }861 )*862 }};863}864865impl<T: Config> Pallet<T> {866 /// Create new collection.867 ///868 /// * `owner` - The owner of the collection.869 /// * `data` - Description of the created collection.870 /// * `flags` - Extra flags to store.871 pub fn init_collection(872 owner: T::CrossAccountId,873 payer: T::CrossAccountId,874 data: CreateCollectionData<T::AccountId>,875 flags: CollectionFlags,876 ) -> Result<CollectionId, DispatchError> {877 {878 ensure!(879 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,880 Error::<T>::CollectionTokenPrefixLimitExceeded881 );882 }883884 let created_count = <CreatedCollectionCount<T>>::get()885 .0886 .checked_add(1)887 .ok_or(ArithmeticError::Overflow)?;888 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;889 let id = CollectionId(created_count);890891 // bound Total number of collections892 ensure!(893 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,894 <Error<T>>::TotalCollectionsLimitExceeded895 );896897 // =========898899 let collection = Collection {900 owner: owner.as_sub().clone(),901 name: data.name,902 mode: data.mode.clone(),903 description: data.description,904 token_prefix: data.token_prefix,905 sponsorship: data906 .pending_sponsor907 .map(SponsorshipState::Unconfirmed)908 .unwrap_or_default(),909 limits: data910 .limits911 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))912 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,913 permissions: data914 .permissions915 .map(|permissions| {916 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)917 })918 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,919 flags,920 };921922 let mut collection_properties = up_data_structs::CollectionProperties::get();923 collection_properties924 .try_set_from_iter(data.properties.into_iter())925 .map_err(<Error<T>>::from)?;926927 CollectionProperties::<T>::insert(id, collection_properties);928929 let mut token_props_permissions = PropertiesPermissionMap::new();930 token_props_permissions931 .try_set_from_iter(data.token_property_permissions.into_iter())932 .map_err(<Error<T>>::from)?;933934 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);935936 // Take a (non-refundable) deposit of collection creation937 {938 let mut imbalance =939 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();940 imbalance.subsume(941 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(942 &T::TreasuryAccountId::get(),943 T::CollectionCreationPrice::get(),944 ),945 );946 <T as Config>::Currency::settle(947 payer.as_sub(),948 imbalance,949 WithdrawReasons::TRANSFER,950 ExistenceRequirement::KeepAlive,951 )952 .map_err(|_| Error::<T>::NotSufficientFounds)?;953 }954955 <CreatedCollectionCount<T>>::put(created_count);956 <Pallet<T>>::deposit_event(Event::CollectionCreated(957 id,958 data.mode.id(),959 owner.as_sub().clone(),960 ));961 <PalletEvm<T>>::deposit_log(962 erc::CollectionHelpersEvents::CollectionCreated {963 owner: *owner.as_eth(),964 collection_id: eth::collection_id_to_address(id),965 }966 .to_log(T::ContractAddress::get()),967 );968 <CollectionById<T>>::insert(id, collection);969 Ok(id)970 }971972 /// Destroy collection.973 ///974 /// * `collection` - Collection handler.975 /// * `sender` - The owner or administrator of the collection.976 pub fn destroy_collection(977 collection: CollectionHandle<T>,978 sender: &T::CrossAccountId,979 ) -> DispatchResult {980 ensure!(981 collection.limits.owner_can_destroy(),982 <Error<T>>::NoPermission,983 );984 collection.check_is_owner(sender)?;985986 let destroyed_collections = <DestroyedCollectionCount<T>>::get()987 .0988 .checked_add(1)989 .ok_or(ArithmeticError::Overflow)?;990991 // =========992993 <DestroyedCollectionCount<T>>::put(destroyed_collections);994 <CollectionById<T>>::remove(collection.id);995 <AdminAmount<T>>::remove(collection.id);996 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);997 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);998 <CollectionProperties<T>>::remove(collection.id);9991000 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));1001 Ok(())1002 }10031004 /// Set collection property.1005 ///1006 /// * `collection` - Collection handler.1007 /// * `sender` - The owner or administrator of the collection.1008 /// * `property` - The property to set.1009 pub fn set_collection_property(1010 collection: &CollectionHandle<T>,1011 sender: &T::CrossAccountId,1012 property: Property,1013 ) -> DispatchResult {1014 collection.check_is_owner_or_admin(sender)?;10151016 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1017 let property = property.clone();1018 properties.try_set(property.key, property.value)1019 })1020 .map_err(<Error<T>>::from)?;10211022 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10231024 Ok(())1025 }10261027 /// Set scouped collection property.1028 ///1029 /// * `collection_id` - ID of the collection for which the property is being set.1030 /// * `scope` - Property scope.1031 /// * `property` - The property to set.1032 pub fn set_scoped_collection_property(1033 collection_id: CollectionId,1034 scope: PropertyScope,1035 property: Property,1036 ) -> DispatchResult {1037 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1038 properties.try_scoped_set(scope, property.key, property.value)1039 })1040 .map_err(<Error<T>>::from)?;10411042 Ok(())1043 }10441045 /// Set scouped collection properties.1046 ///1047 /// * `collection_id` - ID of the collection for which the properties is being set.1048 /// * `scope` - Property scope.1049 /// * `properties` - The properties to set.1050 pub fn set_scoped_collection_properties(1051 collection_id: CollectionId,1052 scope: PropertyScope,1053 properties: impl Iterator<Item = Property>,1054 ) -> DispatchResult {1055 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1056 stored_properties.try_scoped_set_from_iter(scope, properties)1057 })1058 .map_err(<Error<T>>::from)?;10591060 Ok(())1061 }10621063 /// Set collection properties.1064 ///1065 /// * `collection` - Collection handler.1066 /// * `sender` - The owner or administrator of the collection.1067 /// * `properties` - The properties to set.1068 #[transactional]1069 pub fn set_collection_properties(1070 collection: &CollectionHandle<T>,1071 sender: &T::CrossAccountId,1072 properties: Vec<Property>,1073 ) -> DispatchResult {1074 for property in properties {1075 Self::set_collection_property(collection, sender, property)?;1076 }10771078 Ok(())1079 }10801081 /// Delete collection property.1082 ///1083 /// * `collection` - Collection handler.1084 /// * `sender` - The owner or administrator of the collection.1085 /// * `property` - The property to delete.1086 pub fn delete_collection_property(1087 collection: &CollectionHandle<T>,1088 sender: &T::CrossAccountId,1089 property_key: PropertyKey,1090 ) -> DispatchResult {1091 collection.check_is_owner_or_admin(sender)?;10921093 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1094 properties.remove(&property_key)1095 })1096 .map_err(<Error<T>>::from)?;10971098 Self::deposit_event(Event::CollectionPropertyDeleted(1099 collection.id,1100 property_key,1101 ));11021103 Ok(())1104 }11051106 /// Delete collection properties.1107 ///1108 /// * `collection` - Collection handler.1109 /// * `sender` - The owner or administrator of the collection.1110 /// * `properties` - The properties to delete.1111 #[transactional]1112 pub fn delete_collection_properties(1113 collection: &CollectionHandle<T>,1114 sender: &T::CrossAccountId,1115 property_keys: Vec<PropertyKey>,1116 ) -> DispatchResult {1117 for key in property_keys {1118 Self::delete_collection_property(collection, sender, key)?;1119 }11201121 Ok(())1122 }11231124 /// Set collection propetry permission without any checks.1125 ///1126 /// Used for migrations.1127 ///1128 /// * `collection` - Collection handler.1129 /// * `property_permissions` - Property permissions.1130 pub fn set_property_permission_unchecked(1131 collection: CollectionId,1132 property_permission: PropertyKeyPermission,1133 ) -> DispatchResult {1134 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1135 permissions.try_set(property_permission.key, property_permission.permission)1136 })1137 .map_err(<Error<T>>::from)?;1138 Ok(())1139 }11401141 /// Set collection property permission.1142 ///1143 /// * `collection` - Collection handler.1144 /// * `sender` - The owner or administrator of the collection.1145 /// * `property_permission` - Property permission.1146 pub fn set_property_permission(1147 collection: &CollectionHandle<T>,1148 sender: &T::CrossAccountId,1149 property_permission: PropertyKeyPermission,1150 ) -> DispatchResult {1151 Self::set_scoped_property_permission(1152 collection,1153 sender,1154 PropertyScope::None,1155 property_permission,1156 )1157 }11581159 /// Set collection property permission with scope.1160 ///1161 /// * `collection` - Collection handler.1162 /// * `sender` - The owner or administrator of the collection.1163 /// * `scope` - Property scope.1164 /// * `property_permission` - Property permission.1165 pub fn set_scoped_property_permission(1166 collection: &CollectionHandle<T>,1167 sender: &T::CrossAccountId,1168 scope: PropertyScope,1169 property_permission: PropertyKeyPermission,1170 ) -> DispatchResult {1171 collection.check_is_owner_or_admin(sender)?;11721173 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1174 let current_permission = all_permissions.get(&property_permission.key);1175 if matches![1176 current_permission,1177 Some(PropertyPermission { mutable: false, .. })1178 ] {1179 return Err(<Error<T>>::NoPermission.into());1180 }11811182 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1183 let property_permission = property_permission.clone();1184 permissions.try_scoped_set(1185 scope,1186 property_permission.key,1187 property_permission.permission,1188 )1189 })1190 .map_err(<Error<T>>::from)?;11911192 Self::deposit_event(Event::PropertyPermissionSet(1193 collection.id,1194 property_permission.key,1195 ));11961197 Ok(())1198 }11991200 /// Set token property permission.1201 ///1202 /// * `collection` - Collection handler.1203 /// * `sender` - The owner or administrator of the collection.1204 /// * `property_permissions` - Property permissions.1205 #[transactional]1206 pub fn set_token_property_permissions(1207 collection: &CollectionHandle<T>,1208 sender: &T::CrossAccountId,1209 property_permissions: Vec<PropertyKeyPermission>,1210 ) -> DispatchResult {1211 Self::set_scoped_token_property_permissions(1212 collection,1213 sender,1214 PropertyScope::None,1215 property_permissions,1216 )1217 }12181219 /// Set token property permission with scope.1220 ///1221 /// * `collection` - Collection handler.1222 /// * `sender` - The owner or administrator of the collection.1223 /// * `scope` - Property scope.1224 /// * `property_permissions` - Property permissions.1225 #[transactional]1226 pub fn set_scoped_token_property_permissions(1227 collection: &CollectionHandle<T>,1228 sender: &T::CrossAccountId,1229 scope: PropertyScope,1230 property_permissions: Vec<PropertyKeyPermission>,1231 ) -> DispatchResult {1232 for prop_pemission in property_permissions {1233 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1234 }12351236 Ok(())1237 }12381239 /// Get collection property.1240 pub fn get_collection_property(1241 collection_id: CollectionId,1242 key: &PropertyKey,1243 ) -> Option<PropertyValue> {1244 Self::collection_properties(collection_id).get(key).cloned()1245 }12461247 /// Convert byte vector to property key vector.1248 pub fn bytes_keys_to_property_keys(1249 keys: Vec<Vec<u8>>,1250 ) -> Result<Vec<PropertyKey>, DispatchError> {1251 keys.into_iter()1252 .map(|key| -> Result<PropertyKey, DispatchError> {1253 key.try_into()1254 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1255 })1256 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1257 }12581259 /// Get properties according to given keys.1260 pub fn filter_collection_properties(1261 collection_id: CollectionId,1262 keys: Option<Vec<PropertyKey>>,1263 ) -> Result<Vec<Property>, DispatchError> {1264 let properties = Self::collection_properties(collection_id);12651266 let properties = keys1267 .map(|keys| {1268 keys.into_iter()1269 .filter_map(|key| {1270 properties.get(&key).map(|value| Property {1271 key,1272 value: value.clone(),1273 })1274 })1275 .collect()1276 })1277 .unwrap_or_else(|| {1278 properties1279 .into_iter()1280 .map(|(key, value)| Property { key, value })1281 .collect()1282 });12831284 Ok(properties)1285 }12861287 /// Get property permissions according to given keys.1288 pub fn filter_property_permissions(1289 collection_id: CollectionId,1290 keys: Option<Vec<PropertyKey>>,1291 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1292 let permissions = Self::property_permissions(collection_id);12931294 let key_permissions = keys1295 .map(|keys| {1296 keys.into_iter()1297 .filter_map(|key| {1298 permissions1299 .get(&key)1300 .map(|permission| PropertyKeyPermission {1301 key,1302 permission: permission.clone(),1303 })1304 })1305 .collect()1306 })1307 .unwrap_or_else(|| {1308 permissions1309 .into_iter()1310 .map(|(key, permission)| PropertyKeyPermission { key, permission })1311 .collect()1312 });13131314 Ok(key_permissions)1315 }13161317 /// Toggle `user` participation in the `collection`'s allow list.1318 /// #### Store read/writes1319 /// 1 writes1320 pub fn toggle_allowlist(1321 collection: &CollectionHandle<T>,1322 sender: &T::CrossAccountId,1323 user: &T::CrossAccountId,1324 allowed: bool,1325 ) -> DispatchResult {1326 collection.check_is_owner_or_admin(sender)?;13271328 // =========13291330 if allowed {1331 <Allowlist<T>>::insert((collection.id, user), true);1332 } else {1333 <Allowlist<T>>::remove((collection.id, user));1334 }13351336 Ok(())1337 }13381339 /// Toggle `user` participation in the `collection`'s admin list.1340 /// #### Store read/writes1341 /// 2 writes1342 pub fn toggle_admin(1343 collection: &CollectionHandle<T>,1344 sender: &T::CrossAccountId,1345 user: &T::CrossAccountId,1346 admin: bool,1347 ) -> DispatchResult {1348 collection.check_is_owner(sender)?;13491350 let was_admin = <IsAdmin<T>>::get((collection.id, user));1351 if was_admin == admin {1352 return Ok(());1353 }1354 let amount = <AdminAmount<T>>::get(collection.id);13551356 if admin {1357 let amount = amount1358 .checked_add(1)1359 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1360 ensure!(1361 amount <= Self::collection_admins_limit(),1362 <Error<T>>::CollectionAdminCountExceeded,1363 );13641365 // =========13661367 <AdminAmount<T>>::insert(collection.id, amount);1368 <IsAdmin<T>>::insert((collection.id, user), true);1369 } else {1370 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1371 <IsAdmin<T>>::remove((collection.id, user));1372 }13731374 Ok(())1375 }13761377 /// Merge set fields from `new_limit` to `old_limit`.1378 pub fn clamp_limits(1379 mode: CollectionMode,1380 old_limit: &CollectionLimits,1381 mut new_limit: CollectionLimits,1382 ) -> Result<CollectionLimits, DispatchError> {1383 let limits = old_limit;1384 limit_default!(old_limit, new_limit,1385 account_token_ownership_limit => ensure!(1386 new_limit <= MAX_TOKEN_OWNERSHIP,1387 <Error<T>>::CollectionLimitBoundsExceeded,1388 ),1389 sponsored_data_size => ensure!(1390 new_limit <= CUSTOM_DATA_LIMIT,1391 <Error<T>>::CollectionLimitBoundsExceeded,1392 ),13931394 sponsored_data_rate_limit => {},1395 token_limit => ensure!(1396 old_limit >= new_limit && new_limit > 0,1397 <Error<T>>::CollectionTokenLimitExceeded1398 ),13991400 sponsor_transfer_timeout(match mode {1401 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1402 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1403 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1404 }) => ensure!(1405 new_limit <= MAX_SPONSOR_TIMEOUT,1406 <Error<T>>::CollectionLimitBoundsExceeded,1407 ),1408 sponsor_approve_timeout => {},1409 owner_can_transfer => ensure!(1410 !limits.owner_can_transfer_instaled() ||1411 old_limit || !new_limit,1412 <Error<T>>::OwnerPermissionsCantBeReverted,1413 ),1414 owner_can_destroy => ensure!(1415 old_limit || !new_limit,1416 <Error<T>>::OwnerPermissionsCantBeReverted,1417 ),1418 transfers_enabled => {},1419 );1420 Ok(new_limit)1421 }14221423 /// Merge set fields from `new_permission` to `old_permission`.1424 pub fn clamp_permissions(1425 _mode: CollectionMode,1426 old_permission: &CollectionPermissions,1427 mut new_permission: CollectionPermissions,1428 ) -> Result<CollectionPermissions, DispatchError> {1429 limit_default_clone!(old_permission, new_permission,1430 access => {},1431 mint_mode => {},1432 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1433 );1434 Ok(new_permission)1435 }1436}14371438/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1439#[macro_export]1440macro_rules! unsupported {1441 ($runtime:path) => {1442 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1443 };1444}14451446/// Return weights for various worst-case operations.1447pub trait CommonWeightInfo<CrossAccountId> {1448 /// Weight of item creation.1449 fn create_item() -> Weight;14501451 /// Weight of items creation.1452 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14531454 /// Weight of items creation.1455 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14561457 /// The weight of the burning item.1458 fn burn_item() -> Weight;14591460 /// Property setting weight.1461 ///1462 /// * `amount`- The number of properties to set.1463 fn set_collection_properties(amount: u32) -> Weight;14641465 /// Collection property deletion weight.1466 ///1467 /// * `amount`- The number of properties to set.1468 fn delete_collection_properties(amount: u32) -> Weight;14691470 /// Token property setting weight.1471 ///1472 /// * `amount`- The number of properties to set.1473 fn set_token_properties(amount: u32) -> Weight;14741475 /// Token property deletion weight.1476 ///1477 /// * `amount`- The number of properties to delete.1478 fn delete_token_properties(amount: u32) -> Weight;14791480 /// Token property permissions set weight.1481 ///1482 /// * `amount`- The number of property permissions to set.1483 fn set_token_property_permissions(amount: u32) -> Weight;14841485 /// Transfer price of the token or its parts.1486 fn transfer() -> Weight;14871488 /// The price of setting the permission of the operation from another user.1489 fn approve() -> Weight;14901491 /// Transfer price from another user.1492 fn transfer_from() -> Weight;14931494 /// The price of burning a token from another user.1495 fn burn_from() -> Weight;14961497 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1498 /// whole users's balance.1499 ///1500 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1501 fn burn_recursively_self_raw() -> Weight;15021503 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1504 ///1505 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1506 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15071508 /// The price of recursive burning a token.1509 ///1510 /// `max_selfs` - The maximum burning weight of the token itself.1511 /// `max_breadth` - The maximum number of nested tokens to burn.1512 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1513 Self::burn_recursively_self_raw()1514 .saturating_mul(max_selfs.max(1) as u64)1515 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1516 }15171518 /// The price of retrieving token owner1519 fn token_owner() -> Weight;1520}15211522/// Weight info extension trait for refungible pallet.1523pub trait RefungibleExtensionsWeightInfo {1524 /// Weight of token repartition.1525 fn repartition() -> Weight;1526}15271528/// Common collection operations.1529///1530/// It wraps methods in Fungible, Nonfungible and Refungible pallets1531/// and adds weight info.1532pub trait CommonCollectionOperations<T: Config> {1533 /// Create token.1534 ///1535 /// * `sender` - The user who mint the token and pays for the transaction.1536 /// * `to` - The user who will own the token.1537 /// * `data` - Token data.1538 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1539 fn create_item(1540 &self,1541 sender: T::CrossAccountId,1542 to: T::CrossAccountId,1543 data: CreateItemData,1544 nesting_budget: &dyn Budget,1545 ) -> DispatchResultWithPostInfo;15461547 /// Create multiple tokens.1548 ///1549 /// * `sender` - The user who mint the token and pays for the transaction.1550 /// * `to` - The user who will own the token.1551 /// * `data` - Token data.1552 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1553 fn create_multiple_items(1554 &self,1555 sender: T::CrossAccountId,1556 to: T::CrossAccountId,1557 data: Vec<CreateItemData>,1558 nesting_budget: &dyn Budget,1559 ) -> DispatchResultWithPostInfo;15601561 /// Create multiple tokens.1562 ///1563 /// * `sender` - The user who mint the token and pays for the transaction.1564 /// * `to` - The user who will own the token.1565 /// * `data` - Token data.1566 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1567 fn create_multiple_items_ex(1568 &self,1569 sender: T::CrossAccountId,1570 data: CreateItemExData<T::CrossAccountId>,1571 nesting_budget: &dyn Budget,1572 ) -> DispatchResultWithPostInfo;15731574 /// Burn token.1575 ///1576 /// * `sender` - The user who owns the token.1577 /// * `token` - Token id that will burned.1578 /// * `amount` - The number of parts of the token that will be burned.1579 fn burn_item(1580 &self,1581 sender: T::CrossAccountId,1582 token: TokenId,1583 amount: u128,1584 ) -> DispatchResultWithPostInfo;15851586 /// Burn token and all nested tokens recursievly.1587 ///1588 /// * `sender` - The user who owns the token.1589 /// * `token` - Token id that will burned.1590 /// * `self_budget` - The budget that can be spent on burning tokens.1591 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1592 fn burn_item_recursively(1593 &self,1594 sender: T::CrossAccountId,1595 token: TokenId,1596 self_budget: &dyn Budget,1597 breadth_budget: &dyn Budget,1598 ) -> DispatchResultWithPostInfo;15991600 /// Set collection properties.1601 ///1602 /// * `sender` - Must be either the owner of the collection or its admin.1603 /// * `properties` - Properties to be set.1604 fn set_collection_properties(1605 &self,1606 sender: T::CrossAccountId,1607 properties: Vec<Property>,1608 ) -> DispatchResultWithPostInfo;16091610 /// Delete collection properties.1611 ///1612 /// * `sender` - Must be either the owner of the collection or its admin.1613 /// * `properties` - The properties to be removed.1614 fn delete_collection_properties(1615 &self,1616 sender: &T::CrossAccountId,1617 property_keys: Vec<PropertyKey>,1618 ) -> DispatchResultWithPostInfo;16191620 /// Set token properties.1621 ///1622 /// The appropriate [`PropertyPermission`] for the token property1623 /// must be set with [`Self::set_token_property_permissions`].1624 ///1625 /// * `sender` - Must be either the owner of the token or its admin.1626 /// * `token_id` - The token for which the properties are being set.1627 /// * `properties` - Properties to be set.1628 /// * `budget` - Budget for setting properties.1629 fn set_token_properties(1630 &self,1631 sender: T::CrossAccountId,1632 token_id: TokenId,1633 properties: Vec<Property>,1634 budget: &dyn Budget,1635 ) -> DispatchResultWithPostInfo;16361637 /// Remove token properties.1638 ///1639 /// The appropriate [`PropertyPermission`] for the token property1640 /// must be set with [`Self::set_token_property_permissions`].1641 ///1642 /// * `sender` - Must be either the owner of the token or its admin.1643 /// * `token_id` - The token for which the properties are being remove.1644 /// * `property_keys` - Keys to remove corresponding properties.1645 /// * `budget` - Budget for removing properties.1646 fn delete_token_properties(1647 &self,1648 sender: T::CrossAccountId,1649 token_id: TokenId,1650 property_keys: Vec<PropertyKey>,1651 budget: &dyn Budget,1652 ) -> DispatchResultWithPostInfo;16531654 /// Set token property permissions.1655 ///1656 /// * `sender` - Must be either the owner of the token or its admin.1657 /// * `token_id` - The token for which the properties are being set.1658 /// * `property_permissions` - Property permissions to be set.1659 /// * `budget` - Budget for setting properties.1660 fn set_token_property_permissions(1661 &self,1662 sender: &T::CrossAccountId,1663 property_permissions: Vec<PropertyKeyPermission>,1664 ) -> DispatchResultWithPostInfo;16651666 /// Transfer amount of token pieces.1667 ///1668 /// * `sender` - Donor user.1669 /// * `to` - Recepient user.1670 /// * `token` - The token of which parts are being sent.1671 /// * `amount` - The number of parts of the token that will be transferred.1672 /// * `budget` - The maximum budget that can be spent on the transfer.1673 fn transfer(1674 &self,1675 sender: T::CrossAccountId,1676 to: T::CrossAccountId,1677 token: TokenId,1678 amount: u128,1679 budget: &dyn Budget,1680 ) -> DispatchResultWithPostInfo;16811682 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1683 ///1684 /// * `sender` - The user who grants access to the token.1685 /// * `spender` - The user to whom the rights are granted.1686 /// * `token` - The token to which access is granted.1687 /// * `amount` - The amount of pieces that another user can dispose of.1688 fn approve(1689 &self,1690 sender: T::CrossAccountId,1691 spender: T::CrossAccountId,1692 token: TokenId,1693 amount: u128,1694 ) -> DispatchResultWithPostInfo;16951696 /// Send parts of a token owned by another user.1697 ///1698 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1699 ///1700 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1701 /// * `from` - The user who owns the token.1702 /// * `to` - Recepient user.1703 /// * `token` - The token of which parts are being sent.1704 /// * `amount` - The number of parts of the token that will be transferred.1705 /// * `budget` - The maximum budget that can be spent on the transfer.1706 fn transfer_from(1707 &self,1708 sender: T::CrossAccountId,1709 from: T::CrossAccountId,1710 to: T::CrossAccountId,1711 token: TokenId,1712 amount: u128,1713 budget: &dyn Budget,1714 ) -> DispatchResultWithPostInfo;17151716 /// Burn parts of a token owned by another user.1717 ///1718 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1719 ///1720 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1721 /// * `from` - The user who owns the token.1722 /// * `token` - The token of which parts are being sent.1723 /// * `amount` - The number of parts of the token that will be transferred.1724 /// * `budget` - The maximum budget that can be spent on the burn.1725 fn burn_from(1726 &self,1727 sender: T::CrossAccountId,1728 from: T::CrossAccountId,1729 token: TokenId,1730 amount: u128,1731 budget: &dyn Budget,1732 ) -> DispatchResultWithPostInfo;17331734 /// Check permission to nest token.1735 ///1736 /// * `sender` - The user who initiated the check.1737 /// * `from` - The token that is checked for embedding.1738 /// * `under` - Token under which to check.1739 /// * `budget` - The maximum budget that can be spent on the check.1740 fn check_nesting(1741 &self,1742 sender: T::CrossAccountId,1743 from: (CollectionId, TokenId),1744 under: TokenId,1745 budget: &dyn Budget,1746 ) -> DispatchResult;17471748 /// Nest one token into another.1749 ///1750 /// * `under` - Token holder.1751 /// * `to_nest` - Nested token.1752 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17531754 /// Unnest token.1755 ///1756 /// * `under` - Token holder.1757 /// * `to_nest` - Token to unnest.1758 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17591760 /// Get all user tokens.1761 ///1762 /// * `account` - Account for which you need to get tokens.1763 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17641765 /// Get all the tokens in the collection.1766 fn collection_tokens(&self) -> Vec<TokenId>;17671768 /// Check if the token exists.1769 ///1770 /// * `token` - Id token to check.1771 fn token_exists(&self, token: TokenId) -> bool;17721773 /// Get the id of the last minted token.1774 fn last_token_id(&self) -> TokenId;17751776 /// Get the owner of the token.1777 ///1778 /// * `token` - The token for which you need to find out the owner.1779 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17801781 /// Returns 10 tokens owners in no particular order.1782 ///1783 /// * `token` - The token for which you need to find out the owners.1784 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17851786 /// Get the value of the token property by key.1787 ///1788 /// * `token` - Token with the property to get.1789 /// * `key` - Property name.1790 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17911792 /// Get a set of token properties by key vector.1793 ///1794 /// * `token` - Token with the property to get.1795 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1796 /// then all properties are returned.1797 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17981799 /// Amount of unique collection tokens1800 fn total_supply(&self) -> u32;18011802 /// Amount of different tokens account has.1803 ///1804 /// * `account` - The account for which need to get the balance.1805 fn account_balance(&self, account: T::CrossAccountId) -> u32;18061807 /// Amount of specific token account have.1808 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18091810 /// Amount of token pieces1811 fn total_pieces(&self, token: TokenId) -> Option<u128>;18121813 /// Get the number of parts of the token that a trusted user can manage.1814 ///1815 /// * `sender` - Trusted user.1816 /// * `spender` - Owner of the token.1817 /// * `token` - The token for which to get the value.1818 fn allowance(1819 &self,1820 sender: T::CrossAccountId,1821 spender: T::CrossAccountId,1822 token: TokenId,1823 ) -> u128;18241825 /// Get extension for RFT collection.1826 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1827}18281829/// Extension for RFT collection.1830pub trait RefungibleExtensions<T>1831where1832 T: Config,1833{1834 /// Change the number of parts of the token.1835 ///1836 /// When the value changes down, this function is equivalent to burning parts of the token.1837 ///1838 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1839 /// * `token` - The token for which you want to change the number of parts.1840 /// * `amount` - The new value of the parts of the token.1841 fn repartition(1842 &self,1843 sender: &T::CrossAccountId,1844 token: TokenId,1845 amount: u128,1846 ) -> DispatchResultWithPostInfo;1847}18481849/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1850///1851/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1852pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1853 let post_info = PostDispatchInfo {1854 actual_weight: Some(weight),1855 pays_fee: Pays::Yes,1856 };1857 match res {1858 Ok(()) => Ok(post_info),1859 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1860 }1861}18621863impl<T: Config> From<PropertiesError> for Error<T> {1864 fn from(error: PropertiesError) -> Self {1865 match error {1866 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1867 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1868 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1869 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1870 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1871 }1872 }1873}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 CollectionFlags,74 CollectionId,75 CreateItemData,76 MAX_TOKEN_PREFIX_LENGTH,77 COLLECTION_ADMINS_LIMIT,78 TokenId,79 TokenChild,80 CollectionStats,81 MAX_TOKEN_OWNERSHIP,82 CollectionMode,83 NFT_SPONSOR_TRANSFER_TIMEOUT,84 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 MAX_SPONSOR_TIMEOUT,87 CUSTOM_DATA_LIMIT,88 CollectionLimits,89 CreateCollectionData,90 SponsorshipState,91 CreateItemExData,92 SponsoringRateLimit,93 budget::Budget,94 PhantomType,95 Property,96 Properties,97 PropertiesPermissionMap,98 PropertyKey,99 PropertyValue,100 PropertyPermission,101 PropertiesError,102 PropertyKeyPermission,103 TokenData,104 TrySetProperty,105 PropertyScope,106 // RMRK107 RmrkCollectionInfo,108 RmrkInstanceInfo,109 RmrkResourceInfo,110 RmrkPropertyInfo,111 RmrkBaseInfo,112 RmrkPartType,113 RmrkBoundedTheme,114 RmrkNftChild,115 CollectionPermissions,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(Weight::from_ref_time(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(Weight::from_ref_time(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 )))203 }204205 /// Consume gas for reading and writing.206 pub fn consume_store_reads_and_writes(207 &self,208 reads: u64,209 writes: u64,210 ) -> evm_coder::execution::Result<()> {211 let weight = <T as frame_system::Config>::DbWeight::get();212 let reads = weight.read.saturating_mul(reads);213 let writes = weight.read.saturating_mul(writes);214 self.recorder215 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(216 reads.saturating_add(writes),217 )))218 }219220 /// Save collection to storage.221 pub fn save(&self) -> DispatchResult {222 <CollectionById<T>>::insert(self.id, &self.collection);223 Ok(())224 }225226 /// Set collection sponsor.227 ///228 /// Unique collections allows sponsoring for certain actions.229 /// This method allows you to set the sponsor of the collection.230 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].231 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {232 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);233 Ok(())234 }235236 /// Confirm sponsorship237 ///238 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.239 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].240 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {241 if self.collection.sponsorship.pending_sponsor() != Some(sender) {242 return Ok(false);243 }244245 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());246 Ok(true)247 }248249 /// Remove collection sponsor.250 pub fn remove_sponsor(&mut self) -> DispatchResult {251 self.collection.sponsorship = SponsorshipState::Disabled;252 Ok(())253 }254255 /// Checks that the collection was created with, and must be operated upon through **Unique API**.256 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.257 pub fn check_is_internal(&self) -> DispatchResult {258 if self.flags.external {259 return Err(<Error<T>>::CollectionIsExternal)?;260 }261262 Ok(())263 }264265 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.266 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.267 pub fn check_is_external(&self) -> DispatchResult {268 if !self.flags.external {269 return Err(<Error<T>>::CollectionIsInternal)?;270 }271272 Ok(())273 }274}275276impl<T: Config> Deref for CollectionHandle<T> {277 type Target = Collection<T::AccountId>;278279 fn deref(&self) -> &Self::Target {280 &self.collection281 }282}283284impl<T: Config> DerefMut for CollectionHandle<T> {285 fn deref_mut(&mut self) -> &mut Self::Target {286 &mut self.collection287 }288}289290impl<T: Config> CollectionHandle<T> {291 /// Checks if the `user` is the owner of the collection.292 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {293 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);294 Ok(())295 }296297 /// Returns **true** if the `user` is the owner or administrator of the collection.298 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {299 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))300 }301302 /// Checks if the `user` is the owner or administrator of the collection.303 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {304 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);305 Ok(())306 }307308 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.309 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {310 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)311 }312313 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.314 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {315 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)316 }317318 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.319 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {320 ensure!(321 <Allowlist<T>>::get((self.id, user)),322 <Error<T>>::AddressNotInAllowlist323 );324 Ok(())325 }326327 /// Changes collection owner to another account328 /// #### Store read/writes329 /// 1 writes330 fn set_owner_internal(331 &mut self,332 caller: T::CrossAccountId,333 new_owner: T::CrossAccountId,334 ) -> DispatchResult {335 self.check_is_owner(&caller)?;336 self.collection.owner = new_owner.as_sub().clone();337 self.save()338 }339}340341#[frame_support::pallet]342pub mod pallet {343 use super::*;344 use pallet_evm::account;345 use dispatch::CollectionDispatch;346 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};347 use frame_system::pallet_prelude::*;348 use frame_support::traits::Currency;349 use up_data_structs::{TokenId, mapping::TokenAddressMapping};350 use scale_info::TypeInfo;351 use weights::WeightInfo;352353 #[pallet::config]354 pub trait Config:355 frame_system::Config356 + pallet_evm_coder_substrate::Config357 + pallet_evm::Config358 + TypeInfo359 + account::Config360 {361 /// Weight information for functions of this pallet.362 type WeightInfo: WeightInfo;363364 /// Events compatible with [`frame_system::Config::Event`].365 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;366367 /// Handler of accounts and payment.368 type Currency: Currency<Self::AccountId>;369370 /// Set price to create a collection.371 #[pallet::constant]372 type CollectionCreationPrice: Get<373 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,374 >;375376 /// Dispatcher of operations on collections.377 type CollectionDispatch: CollectionDispatch<Self>;378379 /// Account which holds the chain's treasury.380 type TreasuryAccountId: Get<Self::AccountId>;381382 /// Address under which the CollectionHelper contract would be available.383 type ContractAddress: Get<H160>;384385 /// Mapper for token addresses to Ethereum addresses.386 type EvmTokenAddressMapping: TokenAddressMapping<H160>;387388 /// Mapper for token addresses to [`CrossAccountId`].389 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;390 }391392 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);393394 #[pallet::pallet]395 #[pallet::storage_version(STORAGE_VERSION)]396 #[pallet::generate_store(pub(super) trait Store)]397 pub struct Pallet<T>(_);398399 #[pallet::extra_constants]400 impl<T: Config> Pallet<T> {401 /// Maximum admins per collection.402 pub fn collection_admins_limit() -> u32 {403 COLLECTION_ADMINS_LIMIT404 }405 }406407 #[pallet::event]408 #[pallet::generate_deposit(pub fn deposit_event)]409 pub enum Event<T: Config> {410 /// New collection was created411 CollectionCreated(412 /// Globally unique identifier of newly created collection.413 CollectionId,414 /// [`CollectionMode`] converted into _u8_.415 u8,416 /// Collection owner.417 T::AccountId,418 ),419420 /// New collection was destroyed421 CollectionDestroyed(422 /// Globally unique identifier of collection.423 CollectionId,424 ),425426 /// New item was created.427 ItemCreated(428 /// Id of the collection where item was created.429 CollectionId,430 /// Id of an item. Unique within the collection.431 TokenId,432 /// Owner of newly created item433 T::CrossAccountId,434 /// Always 1 for NFT435 u128,436 ),437438 /// Collection item was burned.439 ItemDestroyed(440 /// Id of the collection where item was destroyed.441 CollectionId,442 /// Identifier of burned NFT.443 TokenId,444 /// Which user has destroyed its tokens.445 T::CrossAccountId,446 /// Amount of token pieces destroed. Always 1 for NFT.447 u128,448 ),449450 /// Item was transferred451 Transfer(452 /// Id of collection to which item is belong.453 CollectionId,454 /// Id of an item.455 TokenId,456 /// Original owner of item.457 T::CrossAccountId,458 /// New owner of item.459 T::CrossAccountId,460 /// Amount of token pieces transfered. Always 1 for NFT.461 u128,462 ),463464 /// Amount pieces of token owned by `sender` was approved for `spender`.465 Approved(466 /// Id of collection to which item is belong.467 CollectionId,468 /// Id of an item.469 TokenId,470 /// Original owner of item.471 T::CrossAccountId,472 /// Id for which the approval was granted.473 T::CrossAccountId,474 /// Amount of token pieces transfered. Always 1 for NFT.475 u128,476 ),477478 /// The colletion property has been added or edited.479 CollectionPropertySet(480 /// Id of collection to which property has been set.481 CollectionId,482 /// The property that was set.483 PropertyKey,484 ),485486 /// The property has been deleted.487 CollectionPropertyDeleted(488 /// Id of collection to which property has been deleted.489 CollectionId,490 /// The property that was deleted.491 PropertyKey,492 ),493494 /// The token property has been added or edited.495 TokenPropertySet(496 /// Identifier of the collection whose token has the property set.497 CollectionId,498 /// The token for which the property was set.499 TokenId,500 /// The property that was set.501 PropertyKey,502 ),503504 /// The token property has been deleted.505 TokenPropertyDeleted(506 /// Identifier of the collection whose token has the property deleted.507 CollectionId,508 /// The token for which the property was deleted.509 TokenId,510 /// The property that was deleted.511 PropertyKey,512 ),513514 /// The token property permission of a collection has been set.515 PropertyPermissionSet(516 /// ID of collection to which property permission has been set.517 CollectionId,518 /// The property permission that was set.519 PropertyKey,520 ),521 }522523 #[pallet::error]524 pub enum Error<T> {525 /// This collection does not exist.526 CollectionNotFound,527 /// Sender parameter and item owner must be equal.528 MustBeTokenOwner,529 /// No permission to perform action530 NoPermission,531 /// Destroying only empty collections is allowed532 CantDestroyNotEmptyCollection,533 /// Collection is not in mint mode.534 PublicMintingNotAllowed,535 /// Address is not in allow list.536 AddressNotInAllowlist,537538 /// Collection name can not be longer than 63 char.539 CollectionNameLimitExceeded,540 /// Collection description can not be longer than 255 char.541 CollectionDescriptionLimitExceeded,542 /// Token prefix can not be longer than 15 char.543 CollectionTokenPrefixLimitExceeded,544 /// Total collections bound exceeded.545 TotalCollectionsLimitExceeded,546 /// Exceeded max admin count547 CollectionAdminCountExceeded,548 /// Collection limit bounds per collection exceeded549 CollectionLimitBoundsExceeded,550 /// Tried to enable permissions which are only permitted to be disabled551 OwnerPermissionsCantBeReverted,552 /// Collection settings not allowing items transferring553 TransferNotAllowed,554 /// Account token limit exceeded per collection555 AccountTokenLimitExceeded,556 /// Collection token limit exceeded557 CollectionTokenLimitExceeded,558 /// Metadata flag frozen559 MetadataFlagFrozen,560561 /// Item does not exist562 TokenNotFound,563 /// Item is balance not enough564 TokenValueTooLow,565 /// Requested value is more than the approved566 ApprovedValueTooLow,567 /// Tried to approve more than owned568 CantApproveMoreThanOwned,569570 /// Can't transfer tokens to ethereum zero address571 AddressIsZero,572573 /// The operation is not supported574 UnsupportedOperation,575576 /// Insufficient funds to perform an action577 NotSufficientFounds,578579 /// User does not satisfy the nesting rule580 UserIsNotAllowedToNest,581 /// Only tokens from specific collections may nest tokens under this one582 SourceCollectionIsNotAllowedToNest,583584 /// Tried to store more data than allowed in collection field585 CollectionFieldSizeExceeded,586587 /// Tried to store more property data than allowed588 NoSpaceForProperty,589590 /// Tried to store more property keys than allowed591 PropertyLimitReached,592593 /// Property key is too long594 PropertyKeyIsTooLong,595596 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed597 InvalidCharacterInPropertyKey,598599 /// Empty property keys are forbidden600 EmptyPropertyKey,601602 /// Tried to access an external collection with an internal API603 CollectionIsExternal,604605 /// Tried to access an internal collection with an external API606 CollectionIsInternal,607 }608609 /// Storage of the count of created collections. Essentially contains the last collection ID.610 #[pallet::storage]611 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;612613 /// Storage of the count of deleted collections.614 #[pallet::storage]615 pub type DestroyedCollectionCount<T> =616 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;617618 /// Storage of collection info.619 #[pallet::storage]620 pub type CollectionById<T> = StorageMap<621 Hasher = Blake2_128Concat,622 Key = CollectionId,623 Value = Collection<<T as frame_system::Config>::AccountId>,624 QueryKind = OptionQuery,625 >;626627 /// Storage of collection properties.628 #[pallet::storage]629 #[pallet::getter(fn collection_properties)]630 pub type CollectionProperties<T> = StorageMap<631 Hasher = Blake2_128Concat,632 Key = CollectionId,633 Value = Properties,634 QueryKind = ValueQuery,635 OnEmpty = up_data_structs::CollectionProperties,636 >;637638 /// Storage of token property permissions of a collection.639 #[pallet::storage]640 #[pallet::getter(fn property_permissions)]641 pub type CollectionPropertyPermissions<T> = StorageMap<642 Hasher = Blake2_128Concat,643 Key = CollectionId,644 Value = PropertiesPermissionMap,645 QueryKind = ValueQuery,646 >;647648 /// Storage of the amount of collection admins.649 #[pallet::storage]650 pub type AdminAmount<T> = StorageMap<651 Hasher = Blake2_128Concat,652 Key = CollectionId,653 Value = u32,654 QueryKind = ValueQuery,655 >;656657 /// List of collection admins.658 #[pallet::storage]659 pub type IsAdmin<T: Config> = StorageNMap<660 Key = (661 Key<Blake2_128Concat, CollectionId>,662 Key<Blake2_128Concat, T::CrossAccountId>,663 ),664 Value = bool,665 QueryKind = ValueQuery,666 >;667668 /// Allowlisted collection users.669 #[pallet::storage]670 pub type Allowlist<T: Config> = StorageNMap<671 Key = (672 Key<Blake2_128Concat, CollectionId>,673 Key<Blake2_128Concat, T::CrossAccountId>,674 ),675 Value = bool,676 QueryKind = ValueQuery,677 >;678679 /// Not used by code, exists only to provide some types to metadata.680 #[pallet::storage]681 pub type DummyStorageValue<T: Config> = StorageValue<682 Value = (683 CollectionStats,684 CollectionId,685 TokenId,686 TokenChild,687 PhantomType<(688 TokenData<T::CrossAccountId>,689 RpcCollection<T::AccountId>,690 // RMRK691 RmrkCollectionInfo<T::AccountId>,692 RmrkInstanceInfo<T::AccountId>,693 RmrkResourceInfo,694 RmrkPropertyInfo,695 RmrkBaseInfo<T::AccountId>,696 RmrkPartType,697 RmrkBoundedTheme,698 RmrkNftChild,699 )>,700 ),701 QueryKind = OptionQuery,702 >;703704 #[pallet::hooks]705 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {706 fn on_runtime_upgrade() -> Weight {707 StorageVersion::new(1).put::<Pallet<T>>();708709 Weight::zero()710 }711 }712}713714impl<T: Config> Pallet<T> {715 /// Enshure that receiver address is correct.716 ///717 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.718 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {719 ensure!(720 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,721 <Error<T>>::AddressIsZero722 );723 Ok(())724 }725726 /// Get a vector of collection admins.727 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {728 <IsAdmin<T>>::iter_prefix((collection,))729 .map(|(a, _)| a)730 .collect()731 }732733 /// Get a vector of users allowed to mint tokens.734 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {735 <Allowlist<T>>::iter_prefix((collection,))736 .map(|(a, _)| a)737 .collect()738 }739740 /// Is `user` allowed to mint token in `collection`.741 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {742 <Allowlist<T>>::get((collection, user))743 }744745 /// Get statistics of collections.746 pub fn collection_stats() -> CollectionStats {747 let created = <CreatedCollectionCount<T>>::get();748 let destroyed = <DestroyedCollectionCount<T>>::get();749 CollectionStats {750 created: created.0,751 destroyed: destroyed.0,752 alive: created.0 - destroyed.0,753 }754 }755756 /// Get the effective limits for the collection.757 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {758 let collection = <CollectionById<T>>::get(collection)?;759 let limits = collection.limits;760 let effective_limits = CollectionLimits {761 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),762 sponsored_data_size: Some(limits.sponsored_data_size()),763 sponsored_data_rate_limit: Some(764 limits765 .sponsored_data_rate_limit766 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),767 ),768 token_limit: Some(limits.token_limit()),769 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(770 match collection.mode {771 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,772 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,773 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,774 },775 )),776 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),777 owner_can_transfer: Some(limits.owner_can_transfer()),778 owner_can_destroy: Some(limits.owner_can_destroy()),779 transfers_enabled: Some(limits.transfers_enabled()),780 };781782 Some(effective_limits)783 }784785 /// Returns information about the `collection` adapted for rpc.786 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {787 let Collection {788 name,789 description,790 owner,791 mode,792 token_prefix,793 sponsorship,794 limits,795 permissions,796 flags,797 } = <CollectionById<T>>::get(collection)?;798799 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)800 .into_iter()801 .map(|(key, permission)| PropertyKeyPermission { key, permission })802 .collect();803804 let properties = <CollectionProperties<T>>::get(collection)805 .into_iter()806 .map(|(key, value)| Property { key, value })807 .collect();808809 let permissions = CollectionPermissions {810 access: Some(permissions.access()),811 mint_mode: Some(permissions.mint_mode()),812 nesting: Some(permissions.nesting().clone()),813 };814815 Some(RpcCollection {816 name: name.into_inner(),817 description: description.into_inner(),818 owner,819 mode,820 token_prefix: token_prefix.into_inner(),821 sponsorship,822 limits,823 permissions,824 token_property_permissions,825 properties,826 read_only: flags.external,827 foreign: flags.foreign,828 })829 }830}831832macro_rules! limit_default {833 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{834 $(835 if let Some($new) = $new.$field {836 let $old = $old.$field($($arg)?);837 let _ = $new;838 let _ = $old;839 $check840 } else {841 $new.$field = $old.$field842 }843 )*844 }};845}846macro_rules! limit_default_clone {847 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{848 $(849 if let Some($new) = $new.$field.clone() {850 let $old = $old.$field($($arg)?);851 let _ = $new;852 let _ = $old;853 $check854 } else {855 $new.$field = $old.$field.clone()856 }857 )*858 }};859}860861impl<T: Config> Pallet<T> {862 /// Create new collection.863 ///864 /// * `owner` - The owner of the collection.865 /// * `data` - Description of the created collection.866 /// * `flags` - Extra flags to store.867 pub fn init_collection(868 owner: T::CrossAccountId,869 payer: T::CrossAccountId,870 data: CreateCollectionData<T::AccountId>,871 flags: CollectionFlags,872 ) -> Result<CollectionId, DispatchError> {873 {874 ensure!(875 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,876 Error::<T>::CollectionTokenPrefixLimitExceeded877 );878 }879880 let created_count = <CreatedCollectionCount<T>>::get()881 .0882 .checked_add(1)883 .ok_or(ArithmeticError::Overflow)?;884 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;885 let id = CollectionId(created_count);886887 // bound Total number of collections888 ensure!(889 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,890 <Error<T>>::TotalCollectionsLimitExceeded891 );892893 // =========894895 let collection = Collection {896 owner: owner.as_sub().clone(),897 name: data.name,898 mode: data.mode.clone(),899 description: data.description,900 token_prefix: data.token_prefix,901 sponsorship: data902 .pending_sponsor903 .map(SponsorshipState::Unconfirmed)904 .unwrap_or_default(),905 limits: data906 .limits907 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))908 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,909 permissions: data910 .permissions911 .map(|permissions| {912 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)913 })914 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,915 flags,916 };917918 let mut collection_properties = up_data_structs::CollectionProperties::get();919 collection_properties920 .try_set_from_iter(data.properties.into_iter())921 .map_err(<Error<T>>::from)?;922923 CollectionProperties::<T>::insert(id, collection_properties);924925 let mut token_props_permissions = PropertiesPermissionMap::new();926 token_props_permissions927 .try_set_from_iter(data.token_property_permissions.into_iter())928 .map_err(<Error<T>>::from)?;929930 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);931932 // Take a (non-refundable) deposit of collection creation933 {934 let mut imbalance =935 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();936 imbalance.subsume(937 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(938 &T::TreasuryAccountId::get(),939 T::CollectionCreationPrice::get(),940 ),941 );942 <T as Config>::Currency::settle(943 payer.as_sub(),944 imbalance,945 WithdrawReasons::TRANSFER,946 ExistenceRequirement::KeepAlive,947 )948 .map_err(|_| Error::<T>::NotSufficientFounds)?;949 }950951 <CreatedCollectionCount<T>>::put(created_count);952 <Pallet<T>>::deposit_event(Event::CollectionCreated(953 id,954 data.mode.id(),955 owner.as_sub().clone(),956 ));957 <PalletEvm<T>>::deposit_log(958 erc::CollectionHelpersEvents::CollectionCreated {959 owner: *owner.as_eth(),960 collection_id: eth::collection_id_to_address(id),961 }962 .to_log(T::ContractAddress::get()),963 );964 <CollectionById<T>>::insert(id, collection);965 Ok(id)966 }967968 /// Destroy collection.969 ///970 /// * `collection` - Collection handler.971 /// * `sender` - The owner or administrator of the collection.972 pub fn destroy_collection(973 collection: CollectionHandle<T>,974 sender: &T::CrossAccountId,975 ) -> DispatchResult {976 ensure!(977 collection.limits.owner_can_destroy(),978 <Error<T>>::NoPermission,979 );980 collection.check_is_owner(sender)?;981982 let destroyed_collections = <DestroyedCollectionCount<T>>::get()983 .0984 .checked_add(1)985 .ok_or(ArithmeticError::Overflow)?;986987 // =========988989 <DestroyedCollectionCount<T>>::put(destroyed_collections);990 <CollectionById<T>>::remove(collection.id);991 <AdminAmount<T>>::remove(collection.id);992 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);993 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);994 <CollectionProperties<T>>::remove(collection.id);995996 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));997 Ok(())998 }9991000 /// Set collection property.1001 ///1002 /// * `collection` - Collection handler.1003 /// * `sender` - The owner or administrator of the collection.1004 /// * `property` - The property to set.1005 pub fn set_collection_property(1006 collection: &CollectionHandle<T>,1007 sender: &T::CrossAccountId,1008 property: Property,1009 ) -> DispatchResult {1010 collection.check_is_owner_or_admin(sender)?;10111012 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1013 let property = property.clone();1014 properties.try_set(property.key, property.value)1015 })1016 .map_err(<Error<T>>::from)?;10171018 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10191020 Ok(())1021 }10221023 /// Set scouped collection property.1024 ///1025 /// * `collection_id` - ID of the collection for which the property is being set.1026 /// * `scope` - Property scope.1027 /// * `property` - The property to set.1028 pub fn set_scoped_collection_property(1029 collection_id: CollectionId,1030 scope: PropertyScope,1031 property: Property,1032 ) -> DispatchResult {1033 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1034 properties.try_scoped_set(scope, property.key, property.value)1035 })1036 .map_err(<Error<T>>::from)?;10371038 Ok(())1039 }10401041 /// Set scouped collection properties.1042 ///1043 /// * `collection_id` - ID of the collection for which the properties is being set.1044 /// * `scope` - Property scope.1045 /// * `properties` - The properties to set.1046 pub fn set_scoped_collection_properties(1047 collection_id: CollectionId,1048 scope: PropertyScope,1049 properties: impl Iterator<Item = Property>,1050 ) -> DispatchResult {1051 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1052 stored_properties.try_scoped_set_from_iter(scope, properties)1053 })1054 .map_err(<Error<T>>::from)?;10551056 Ok(())1057 }10581059 /// Set collection properties.1060 ///1061 /// * `collection` - Collection handler.1062 /// * `sender` - The owner or administrator of the collection.1063 /// * `properties` - The properties to set.1064 #[transactional]1065 pub fn set_collection_properties(1066 collection: &CollectionHandle<T>,1067 sender: &T::CrossAccountId,1068 properties: Vec<Property>,1069 ) -> DispatchResult {1070 for property in properties {1071 Self::set_collection_property(collection, sender, property)?;1072 }10731074 Ok(())1075 }10761077 /// Delete collection property.1078 ///1079 /// * `collection` - Collection handler.1080 /// * `sender` - The owner or administrator of the collection.1081 /// * `property` - The property to delete.1082 pub fn delete_collection_property(1083 collection: &CollectionHandle<T>,1084 sender: &T::CrossAccountId,1085 property_key: PropertyKey,1086 ) -> DispatchResult {1087 collection.check_is_owner_or_admin(sender)?;10881089 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1090 properties.remove(&property_key)1091 })1092 .map_err(<Error<T>>::from)?;10931094 Self::deposit_event(Event::CollectionPropertyDeleted(1095 collection.id,1096 property_key,1097 ));10981099 Ok(())1100 }11011102 /// Delete collection properties.1103 ///1104 /// * `collection` - Collection handler.1105 /// * `sender` - The owner or administrator of the collection.1106 /// * `properties` - The properties to delete.1107 #[transactional]1108 pub fn delete_collection_properties(1109 collection: &CollectionHandle<T>,1110 sender: &T::CrossAccountId,1111 property_keys: Vec<PropertyKey>,1112 ) -> DispatchResult {1113 for key in property_keys {1114 Self::delete_collection_property(collection, sender, key)?;1115 }11161117 Ok(())1118 }11191120 /// Set collection propetry permission without any checks.1121 ///1122 /// Used for migrations.1123 ///1124 /// * `collection` - Collection handler.1125 /// * `property_permissions` - Property permissions.1126 pub fn set_property_permission_unchecked(1127 collection: CollectionId,1128 property_permission: PropertyKeyPermission,1129 ) -> DispatchResult {1130 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1131 permissions.try_set(property_permission.key, property_permission.permission)1132 })1133 .map_err(<Error<T>>::from)?;1134 Ok(())1135 }11361137 /// Set collection property permission.1138 ///1139 /// * `collection` - Collection handler.1140 /// * `sender` - The owner or administrator of the collection.1141 /// * `property_permission` - Property permission.1142 pub fn set_property_permission(1143 collection: &CollectionHandle<T>,1144 sender: &T::CrossAccountId,1145 property_permission: PropertyKeyPermission,1146 ) -> DispatchResult {1147 Self::set_scoped_property_permission(1148 collection,1149 sender,1150 PropertyScope::None,1151 property_permission,1152 )1153 }11541155 /// Set collection property permission with scope.1156 ///1157 /// * `collection` - Collection handler.1158 /// * `sender` - The owner or administrator of the collection.1159 /// * `scope` - Property scope.1160 /// * `property_permission` - Property permission.1161 pub fn set_scoped_property_permission(1162 collection: &CollectionHandle<T>,1163 sender: &T::CrossAccountId,1164 scope: PropertyScope,1165 property_permission: PropertyKeyPermission,1166 ) -> DispatchResult {1167 collection.check_is_owner_or_admin(sender)?;11681169 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1170 let current_permission = all_permissions.get(&property_permission.key);1171 if matches![1172 current_permission,1173 Some(PropertyPermission { mutable: false, .. })1174 ] {1175 return Err(<Error<T>>::NoPermission.into());1176 }11771178 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1179 let property_permission = property_permission.clone();1180 permissions.try_scoped_set(1181 scope,1182 property_permission.key,1183 property_permission.permission,1184 )1185 })1186 .map_err(<Error<T>>::from)?;11871188 Self::deposit_event(Event::PropertyPermissionSet(1189 collection.id,1190 property_permission.key,1191 ));11921193 Ok(())1194 }11951196 /// Set token property permission.1197 ///1198 /// * `collection` - Collection handler.1199 /// * `sender` - The owner or administrator of the collection.1200 /// * `property_permissions` - Property permissions.1201 #[transactional]1202 pub fn set_token_property_permissions(1203 collection: &CollectionHandle<T>,1204 sender: &T::CrossAccountId,1205 property_permissions: Vec<PropertyKeyPermission>,1206 ) -> DispatchResult {1207 Self::set_scoped_token_property_permissions(1208 collection,1209 sender,1210 PropertyScope::None,1211 property_permissions,1212 )1213 }12141215 /// Set token property permission with scope.1216 ///1217 /// * `collection` - Collection handler.1218 /// * `sender` - The owner or administrator of the collection.1219 /// * `scope` - Property scope.1220 /// * `property_permissions` - Property permissions.1221 #[transactional]1222 pub fn set_scoped_token_property_permissions(1223 collection: &CollectionHandle<T>,1224 sender: &T::CrossAccountId,1225 scope: PropertyScope,1226 property_permissions: Vec<PropertyKeyPermission>,1227 ) -> DispatchResult {1228 for prop_pemission in property_permissions {1229 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1230 }12311232 Ok(())1233 }12341235 /// Get collection property.1236 pub fn get_collection_property(1237 collection_id: CollectionId,1238 key: &PropertyKey,1239 ) -> Option<PropertyValue> {1240 Self::collection_properties(collection_id).get(key).cloned()1241 }12421243 /// Convert byte vector to property key vector.1244 pub fn bytes_keys_to_property_keys(1245 keys: Vec<Vec<u8>>,1246 ) -> Result<Vec<PropertyKey>, DispatchError> {1247 keys.into_iter()1248 .map(|key| -> Result<PropertyKey, DispatchError> {1249 key.try_into()1250 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1251 })1252 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1253 }12541255 /// Get properties according to given keys.1256 pub fn filter_collection_properties(1257 collection_id: CollectionId,1258 keys: Option<Vec<PropertyKey>>,1259 ) -> Result<Vec<Property>, DispatchError> {1260 let properties = Self::collection_properties(collection_id);12611262 let properties = keys1263 .map(|keys| {1264 keys.into_iter()1265 .filter_map(|key| {1266 properties.get(&key).map(|value| Property {1267 key,1268 value: value.clone(),1269 })1270 })1271 .collect()1272 })1273 .unwrap_or_else(|| {1274 properties1275 .into_iter()1276 .map(|(key, value)| Property { key, value })1277 .collect()1278 });12791280 Ok(properties)1281 }12821283 /// Get property permissions according to given keys.1284 pub fn filter_property_permissions(1285 collection_id: CollectionId,1286 keys: Option<Vec<PropertyKey>>,1287 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1288 let permissions = Self::property_permissions(collection_id);12891290 let key_permissions = keys1291 .map(|keys| {1292 keys.into_iter()1293 .filter_map(|key| {1294 permissions1295 .get(&key)1296 .map(|permission| PropertyKeyPermission {1297 key,1298 permission: permission.clone(),1299 })1300 })1301 .collect()1302 })1303 .unwrap_or_else(|| {1304 permissions1305 .into_iter()1306 .map(|(key, permission)| PropertyKeyPermission { key, permission })1307 .collect()1308 });13091310 Ok(key_permissions)1311 }13121313 /// Toggle `user` participation in the `collection`'s allow list.1314 /// #### Store read/writes1315 /// 1 writes1316 pub fn toggle_allowlist(1317 collection: &CollectionHandle<T>,1318 sender: &T::CrossAccountId,1319 user: &T::CrossAccountId,1320 allowed: bool,1321 ) -> DispatchResult {1322 collection.check_is_owner_or_admin(sender)?;13231324 // =========13251326 if allowed {1327 <Allowlist<T>>::insert((collection.id, user), true);1328 } else {1329 <Allowlist<T>>::remove((collection.id, user));1330 }13311332 Ok(())1333 }13341335 /// Toggle `user` participation in the `collection`'s admin list.1336 /// #### Store read/writes1337 /// 2 writes1338 pub fn toggle_admin(1339 collection: &CollectionHandle<T>,1340 sender: &T::CrossAccountId,1341 user: &T::CrossAccountId,1342 admin: bool,1343 ) -> DispatchResult {1344 collection.check_is_owner(sender)?;13451346 let was_admin = <IsAdmin<T>>::get((collection.id, user));1347 if was_admin == admin {1348 return Ok(());1349 }1350 let amount = <AdminAmount<T>>::get(collection.id);13511352 if admin {1353 let amount = amount1354 .checked_add(1)1355 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1356 ensure!(1357 amount <= Self::collection_admins_limit(),1358 <Error<T>>::CollectionAdminCountExceeded,1359 );13601361 // =========13621363 <AdminAmount<T>>::insert(collection.id, amount);1364 <IsAdmin<T>>::insert((collection.id, user), true);1365 } else {1366 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1367 <IsAdmin<T>>::remove((collection.id, user));1368 }13691370 Ok(())1371 }13721373 /// Merge set fields from `new_limit` to `old_limit`.1374 pub fn clamp_limits(1375 mode: CollectionMode,1376 old_limit: &CollectionLimits,1377 mut new_limit: CollectionLimits,1378 ) -> Result<CollectionLimits, DispatchError> {1379 let limits = old_limit;1380 limit_default!(old_limit, new_limit,1381 account_token_ownership_limit => ensure!(1382 new_limit <= MAX_TOKEN_OWNERSHIP,1383 <Error<T>>::CollectionLimitBoundsExceeded,1384 ),1385 sponsored_data_size => ensure!(1386 new_limit <= CUSTOM_DATA_LIMIT,1387 <Error<T>>::CollectionLimitBoundsExceeded,1388 ),13891390 sponsored_data_rate_limit => {},1391 token_limit => ensure!(1392 old_limit >= new_limit && new_limit > 0,1393 <Error<T>>::CollectionTokenLimitExceeded1394 ),13951396 sponsor_transfer_timeout(match mode {1397 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1398 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1399 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1400 }) => ensure!(1401 new_limit <= MAX_SPONSOR_TIMEOUT,1402 <Error<T>>::CollectionLimitBoundsExceeded,1403 ),1404 sponsor_approve_timeout => {},1405 owner_can_transfer => ensure!(1406 !limits.owner_can_transfer_instaled() ||1407 old_limit || !new_limit,1408 <Error<T>>::OwnerPermissionsCantBeReverted,1409 ),1410 owner_can_destroy => ensure!(1411 old_limit || !new_limit,1412 <Error<T>>::OwnerPermissionsCantBeReverted,1413 ),1414 transfers_enabled => {},1415 );1416 Ok(new_limit)1417 }14181419 /// Merge set fields from `new_permission` to `old_permission`.1420 pub fn clamp_permissions(1421 _mode: CollectionMode,1422 old_permission: &CollectionPermissions,1423 mut new_permission: CollectionPermissions,1424 ) -> Result<CollectionPermissions, DispatchError> {1425 limit_default_clone!(old_permission, new_permission,1426 access => {},1427 mint_mode => {},1428 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1429 );1430 Ok(new_permission)1431 }1432}14331434/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1435#[macro_export]1436macro_rules! unsupported {1437 ($runtime:path) => {1438 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1439 };1440}14411442/// Return weights for various worst-case operations.1443pub trait CommonWeightInfo<CrossAccountId> {1444 /// Weight of item creation.1445 fn create_item() -> Weight;14461447 /// Weight of items creation.1448 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14491450 /// Weight of items creation.1451 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14521453 /// The weight of the burning item.1454 fn burn_item() -> Weight;14551456 /// Property setting weight.1457 ///1458 /// * `amount`- The number of properties to set.1459 fn set_collection_properties(amount: u32) -> Weight;14601461 /// Collection property deletion weight.1462 ///1463 /// * `amount`- The number of properties to set.1464 fn delete_collection_properties(amount: u32) -> Weight;14651466 /// Token property setting weight.1467 ///1468 /// * `amount`- The number of properties to set.1469 fn set_token_properties(amount: u32) -> Weight;14701471 /// Token property deletion weight.1472 ///1473 /// * `amount`- The number of properties to delete.1474 fn delete_token_properties(amount: u32) -> Weight;14751476 /// Token property permissions set weight.1477 ///1478 /// * `amount`- The number of property permissions to set.1479 fn set_token_property_permissions(amount: u32) -> Weight;14801481 /// Transfer price of the token or its parts.1482 fn transfer() -> Weight;14831484 /// The price of setting the permission of the operation from another user.1485 fn approve() -> Weight;14861487 /// Transfer price from another user.1488 fn transfer_from() -> Weight;14891490 /// The price of burning a token from another user.1491 fn burn_from() -> Weight;14921493 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1494 /// whole users's balance.1495 ///1496 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1497 fn burn_recursively_self_raw() -> Weight;14981499 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1500 ///1501 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1502 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15031504 /// The price of recursive burning a token.1505 ///1506 /// `max_selfs` - The maximum burning weight of the token itself.1507 /// `max_breadth` - The maximum number of nested tokens to burn.1508 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1509 Self::burn_recursively_self_raw()1510 .saturating_mul(max_selfs.max(1) as u64)1511 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1512 }15131514 /// The price of retrieving token owner1515 fn token_owner() -> Weight;1516}15171518/// Weight info extension trait for refungible pallet.1519pub trait RefungibleExtensionsWeightInfo {1520 /// Weight of token repartition.1521 fn repartition() -> Weight;1522}15231524/// Common collection operations.1525///1526/// It wraps methods in Fungible, Nonfungible and Refungible pallets1527/// and adds weight info.1528pub trait CommonCollectionOperations<T: Config> {1529 /// Create token.1530 ///1531 /// * `sender` - The user who mint the token and pays for the transaction.1532 /// * `to` - The user who will own the token.1533 /// * `data` - Token data.1534 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1535 fn create_item(1536 &self,1537 sender: T::CrossAccountId,1538 to: T::CrossAccountId,1539 data: CreateItemData,1540 nesting_budget: &dyn Budget,1541 ) -> DispatchResultWithPostInfo;15421543 /// Create multiple tokens.1544 ///1545 /// * `sender` - The user who mint the token and pays for the transaction.1546 /// * `to` - The user who will own the token.1547 /// * `data` - Token data.1548 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1549 fn create_multiple_items(1550 &self,1551 sender: T::CrossAccountId,1552 to: T::CrossAccountId,1553 data: Vec<CreateItemData>,1554 nesting_budget: &dyn Budget,1555 ) -> DispatchResultWithPostInfo;15561557 /// Create multiple tokens.1558 ///1559 /// * `sender` - The user who mint the token and pays for the transaction.1560 /// * `to` - The user who will own the token.1561 /// * `data` - Token data.1562 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1563 fn create_multiple_items_ex(1564 &self,1565 sender: T::CrossAccountId,1566 data: CreateItemExData<T::CrossAccountId>,1567 nesting_budget: &dyn Budget,1568 ) -> DispatchResultWithPostInfo;15691570 /// Burn token.1571 ///1572 /// * `sender` - The user who owns the token.1573 /// * `token` - Token id that will burned.1574 /// * `amount` - The number of parts of the token that will be burned.1575 fn burn_item(1576 &self,1577 sender: T::CrossAccountId,1578 token: TokenId,1579 amount: u128,1580 ) -> DispatchResultWithPostInfo;15811582 /// Burn token and all nested tokens recursievly.1583 ///1584 /// * `sender` - The user who owns the token.1585 /// * `token` - Token id that will burned.1586 /// * `self_budget` - The budget that can be spent on burning tokens.1587 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1588 fn burn_item_recursively(1589 &self,1590 sender: T::CrossAccountId,1591 token: TokenId,1592 self_budget: &dyn Budget,1593 breadth_budget: &dyn Budget,1594 ) -> DispatchResultWithPostInfo;15951596 /// Set collection properties.1597 ///1598 /// * `sender` - Must be either the owner of the collection or its admin.1599 /// * `properties` - Properties to be set.1600 fn set_collection_properties(1601 &self,1602 sender: T::CrossAccountId,1603 properties: Vec<Property>,1604 ) -> DispatchResultWithPostInfo;16051606 /// Delete collection properties.1607 ///1608 /// * `sender` - Must be either the owner of the collection or its admin.1609 /// * `properties` - The properties to be removed.1610 fn delete_collection_properties(1611 &self,1612 sender: &T::CrossAccountId,1613 property_keys: Vec<PropertyKey>,1614 ) -> DispatchResultWithPostInfo;16151616 /// Set token properties.1617 ///1618 /// The appropriate [`PropertyPermission`] for the token property1619 /// must be set with [`Self::set_token_property_permissions`].1620 ///1621 /// * `sender` - Must be either the owner of the token or its admin.1622 /// * `token_id` - The token for which the properties are being set.1623 /// * `properties` - Properties to be set.1624 /// * `budget` - Budget for setting properties.1625 fn set_token_properties(1626 &self,1627 sender: T::CrossAccountId,1628 token_id: TokenId,1629 properties: Vec<Property>,1630 budget: &dyn Budget,1631 ) -> DispatchResultWithPostInfo;16321633 /// Remove token properties.1634 ///1635 /// The appropriate [`PropertyPermission`] for the token property1636 /// must be set with [`Self::set_token_property_permissions`].1637 ///1638 /// * `sender` - Must be either the owner of the token or its admin.1639 /// * `token_id` - The token for which the properties are being remove.1640 /// * `property_keys` - Keys to remove corresponding properties.1641 /// * `budget` - Budget for removing properties.1642 fn delete_token_properties(1643 &self,1644 sender: T::CrossAccountId,1645 token_id: TokenId,1646 property_keys: Vec<PropertyKey>,1647 budget: &dyn Budget,1648 ) -> DispatchResultWithPostInfo;16491650 /// Set token property permissions.1651 ///1652 /// * `sender` - Must be either the owner of the token or its admin.1653 /// * `token_id` - The token for which the properties are being set.1654 /// * `property_permissions` - Property permissions to be set.1655 /// * `budget` - Budget for setting properties.1656 fn set_token_property_permissions(1657 &self,1658 sender: &T::CrossAccountId,1659 property_permissions: Vec<PropertyKeyPermission>,1660 ) -> DispatchResultWithPostInfo;16611662 /// Transfer amount of token pieces.1663 ///1664 /// * `sender` - Donor user.1665 /// * `to` - Recepient user.1666 /// * `token` - The token of which parts are being sent.1667 /// * `amount` - The number of parts of the token that will be transferred.1668 /// * `budget` - The maximum budget that can be spent on the transfer.1669 fn transfer(1670 &self,1671 sender: T::CrossAccountId,1672 to: T::CrossAccountId,1673 token: TokenId,1674 amount: u128,1675 budget: &dyn Budget,1676 ) -> DispatchResultWithPostInfo;16771678 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1679 ///1680 /// * `sender` - The user who grants access to the token.1681 /// * `spender` - The user to whom the rights are granted.1682 /// * `token` - The token to which access is granted.1683 /// * `amount` - The amount of pieces that another user can dispose of.1684 fn approve(1685 &self,1686 sender: T::CrossAccountId,1687 spender: T::CrossAccountId,1688 token: TokenId,1689 amount: u128,1690 ) -> DispatchResultWithPostInfo;16911692 /// Send parts of a token owned by another user.1693 ///1694 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1695 ///1696 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1697 /// * `from` - The user who owns the token.1698 /// * `to` - Recepient user.1699 /// * `token` - The token of which parts are being sent.1700 /// * `amount` - The number of parts of the token that will be transferred.1701 /// * `budget` - The maximum budget that can be spent on the transfer.1702 fn transfer_from(1703 &self,1704 sender: T::CrossAccountId,1705 from: T::CrossAccountId,1706 to: T::CrossAccountId,1707 token: TokenId,1708 amount: u128,1709 budget: &dyn Budget,1710 ) -> DispatchResultWithPostInfo;17111712 /// Burn parts of a token owned by another user.1713 ///1714 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1715 ///1716 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1717 /// * `from` - The user who owns the token.1718 /// * `token` - The token of which parts are being sent.1719 /// * `amount` - The number of parts of the token that will be transferred.1720 /// * `budget` - The maximum budget that can be spent on the burn.1721 fn burn_from(1722 &self,1723 sender: T::CrossAccountId,1724 from: T::CrossAccountId,1725 token: TokenId,1726 amount: u128,1727 budget: &dyn Budget,1728 ) -> DispatchResultWithPostInfo;17291730 /// Check permission to nest token.1731 ///1732 /// * `sender` - The user who initiated the check.1733 /// * `from` - The token that is checked for embedding.1734 /// * `under` - Token under which to check.1735 /// * `budget` - The maximum budget that can be spent on the check.1736 fn check_nesting(1737 &self,1738 sender: T::CrossAccountId,1739 from: (CollectionId, TokenId),1740 under: TokenId,1741 budget: &dyn Budget,1742 ) -> DispatchResult;17431744 /// Nest one token into another.1745 ///1746 /// * `under` - Token holder.1747 /// * `to_nest` - Nested token.1748 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17491750 /// Unnest token.1751 ///1752 /// * `under` - Token holder.1753 /// * `to_nest` - Token to unnest.1754 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17551756 /// Get all user tokens.1757 ///1758 /// * `account` - Account for which you need to get tokens.1759 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17601761 /// Get all the tokens in the collection.1762 fn collection_tokens(&self) -> Vec<TokenId>;17631764 /// Check if the token exists.1765 ///1766 /// * `token` - Id token to check.1767 fn token_exists(&self, token: TokenId) -> bool;17681769 /// Get the id of the last minted token.1770 fn last_token_id(&self) -> TokenId;17711772 /// Get the owner of the token.1773 ///1774 /// * `token` - The token for which you need to find out the owner.1775 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17761777 /// Returns 10 tokens owners in no particular order.1778 ///1779 /// * `token` - The token for which you need to find out the owners.1780 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17811782 /// Get the value of the token property by key.1783 ///1784 /// * `token` - Token with the property to get.1785 /// * `key` - Property name.1786 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17871788 /// Get a set of token properties by key vector.1789 ///1790 /// * `token` - Token with the property to get.1791 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1792 /// then all properties are returned.1793 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17941795 /// Amount of unique collection tokens1796 fn total_supply(&self) -> u32;17971798 /// Amount of different tokens account has.1799 ///1800 /// * `account` - The account for which need to get the balance.1801 fn account_balance(&self, account: T::CrossAccountId) -> u32;18021803 /// Amount of specific token account have.1804 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18051806 /// Amount of token pieces1807 fn total_pieces(&self, token: TokenId) -> Option<u128>;18081809 /// Get the number of parts of the token that a trusted user can manage.1810 ///1811 /// * `sender` - Trusted user.1812 /// * `spender` - Owner of the token.1813 /// * `token` - The token for which to get the value.1814 fn allowance(1815 &self,1816 sender: T::CrossAccountId,1817 spender: T::CrossAccountId,1818 token: TokenId,1819 ) -> u128;18201821 /// Get extension for RFT collection.1822 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1823}18241825/// Extension for RFT collection.1826pub trait RefungibleExtensions<T>1827where1828 T: Config,1829{1830 /// Change the number of parts of the token.1831 ///1832 /// When the value changes down, this function is equivalent to burning parts of the token.1833 ///1834 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1835 /// * `token` - The token for which you want to change the number of parts.1836 /// * `amount` - The new value of the parts of the token.1837 fn repartition(1838 &self,1839 sender: &T::CrossAccountId,1840 token: TokenId,1841 amount: u128,1842 ) -> DispatchResultWithPostInfo;1843}18441845/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1846///1847/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1848pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1849 let post_info = PostDispatchInfo {1850 actual_weight: Some(weight),1851 pays_fee: Pays::Yes,1852 };1853 match res {1854 Ok(()) => Ok(post_info),1855 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1856 }1857}18581859impl<T: Config> From<PropertiesError> for Error<T> {1860 fn from(error: PropertiesError) -> Self {1861 match error {1862 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1863 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1864 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1865 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1866 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1867 }1868 }1869}pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -99,9 +99,7 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
- CommonCollectionOperations,
- Error as CommonError,
- eth::collection_id_to_address,
+ CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
@@ -110,10 +108,10 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
- AccessMode, budget::Budget, CollectionId, CollectionFlags,
- CollectionPropertiesVec, CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping,
- MAX_ITEMS_PER_BATCH, MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission,
- PropertyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,
+ AccessMode, budget::Budget, CollectionId, CollectionFlags, CollectionPropertiesVec,
+ CreateCollectionData, CustomDataLimit, mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH,
+ MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyPermission,
+ PropertyScope, PropertyValue, TokenId, TrySetProperty,
};
use frame_support::BoundedBTreeMap;
use derivative::Derivative;
runtime/common/config/xcm/nativeassets.rsdiffbeforeafterboth--- a/runtime/common/config/xcm/nativeassets.rs
+++ b/runtime/common/config/xcm/nativeassets.rs
@@ -23,8 +23,7 @@
use xcm::latest::{
AssetId::{Concrete},
Fungibility::Fungible as XcmFungible,
- MultiAsset, Error as XcmError,
- Weight,
+ MultiAsset, Error as XcmError, Weight,
};
use xcm_builder::{CurrencyAdapter, NativeAsset};
use xcm_executor::{
runtime/common/mod.rsdiffbeforeafterboth--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -39,10 +39,7 @@
#[cfg(feature = "std")]
use sp_version::NativeVersion;
-use crate::{
- Runtime, Call, Balances, Treasury, Aura, Signature, AllPalletsWithSystem,
- InherentDataExt,
-};
+use crate::{Runtime, Call, Balances, Treasury, Aura, Signature, AllPalletsWithSystem, InherentDataExt};
use up_common::types::{AccountId, BlockNumber};
#[macro_export]
@@ -105,7 +102,7 @@
Block,
frame_system::ChainContext<Runtime>,
Runtime,
- AllPalletsWithSystem
+ AllPalletsWithSystem,
>;
type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;
runtime/opal/src/xcm_barrier.rsdiffbeforeafterboth--- a/runtime/opal/src/xcm_barrier.rs
+++ b/runtime/opal/src/xcm_barrier.rs
@@ -15,7 +15,10 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use frame_support::traits::Everything;
-use xcm::{latest::{Xcm, Weight}, v1::MultiLocation};
+use xcm::{
+ latest::{Xcm, Weight},
+ v1::MultiLocation,
+};
use xcm_builder::{AllowTopLevelPaidExecutionFrom, TakeWeightCredit};
use xcm_executor::traits::ShouldExecute;