difftreelog
fix after rebase
in: master
5 files changed
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68 dispatch::Pays,69 transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73 AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74 RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75 COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76 CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78 CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyValue,80 PropertyPermission, PropertiesError, TokenOwnerError, PropertyKeyPermission, TokenData,81 TrySetProperty, PropertyScope, CollectionPermissions,82};83use up_pov_estimate_rpc::PovInfo;8485pub use pallet::*;86use sp_core::H160;87use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8889use crate::erc::CollectionHelpersEvents;90#[cfg(feature = "runtime-benchmarks")]91pub mod benchmarking;92pub mod dispatch;93pub mod erc;94pub mod eth;95pub mod weights;9697/// Weight info.98pub type SelfWeightOf<T> = <T as Config>::WeightInfo;99100/// Collection handle contains information about collection data and id.101/// Also provides functionality to count consumed gas.102///103/// CollectionHandle is used as a generic wrapper for collections of all types.104/// It allows to perform common operations and queries on any collection type,105/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].106#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]107pub struct CollectionHandle<T: Config> {108 /// Collection id109 pub id: CollectionId,110 collection: Collection<T::AccountId>,111 /// Substrate recorder for counting consumed gas112 pub recorder: SubstrateRecorder<T>,113}114115impl<T: Config> WithRecorder<T> for CollectionHandle<T> {116 fn recorder(&self) -> &SubstrateRecorder<T> {117 &self.recorder118 }119 fn into_recorder(self) -> SubstrateRecorder<T> {120 self.recorder121 }122}123124impl<T: Config> CollectionHandle<T> {125 /// Same as [CollectionHandle::new] but with an explicit gas limit.126 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {127 <CollectionById<T>>::get(id).map(|collection| Self {128 id,129 collection,130 recorder: SubstrateRecorder::new(gas_limit),131 })132 }133134 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].135 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {136 <CollectionById<T>>::get(id).map(|collection| Self {137 id,138 collection,139 recorder,140 })141 }142143 /// Retrives collection data from storage and creates collection handle with default parameters.144 /// If collection not found return `None`145 pub fn new(id: CollectionId) -> Option<Self> {146 Self::new_with_gas_limit(id, u64::MAX)147 }148149 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.150 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {151 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)152 }153154 /// Consume gas for reading.155 pub fn consume_store_reads(156 &self,157 reads: u64,158 ) -> pallet_evm_coder_substrate::execution::Result<()> {159 self.recorder160 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(161 <T as frame_system::Config>::DbWeight::get()162 .read163 .saturating_mul(reads),164 )))165 }166167 /// Consume gas for writing.168 pub fn consume_store_writes(169 &self,170 writes: u64,171 ) -> pallet_evm_coder_substrate::execution::Result<()> {172 self.recorder173 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(174 <T as frame_system::Config>::DbWeight::get()175 .write176 .saturating_mul(writes),177 )))178 }179180 /// Consume gas for reading and writing.181 pub fn consume_store_reads_and_writes(182 &self,183 reads: u64,184 writes: u64,185 ) -> pallet_evm_coder_substrate::execution::Result<()> {186 let weight = <T as frame_system::Config>::DbWeight::get();187 let reads = weight.read.saturating_mul(reads);188 let writes = weight.read.saturating_mul(writes);189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 reads.saturating_add(writes),192 )))193 }194195 /// Save collection to storage.196 pub fn save(&self) -> DispatchResult {197 <CollectionById<T>>::insert(self.id, &self.collection);198 Ok(())199 }200201 /// Set collection sponsor.202 ///203 /// Unique collections allows sponsoring for certain actions.204 /// This method allows you to set the sponsor of the collection.205 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].206 pub fn set_sponsor(207 &mut self,208 sender: &T::CrossAccountId,209 sponsor: T::AccountId,210 ) -> DispatchResult {211 self.check_is_internal()?;212 self.check_is_owner_or_admin(sender)?;213214 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());215216 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));217 <PalletEvm<T>>::deposit_log(218 erc::CollectionHelpersEvents::CollectionChanged {219 collection_id: eth::collection_id_to_address(self.id),220 }221 .to_log(T::ContractAddress::get()),222 );223224 self.save()225 }226227 /// Force set `sponsor`.228 ///229 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation230 /// from the `sponsor` is not required.231 ///232 /// # Arguments233 ///234 /// * `sender`: Caller's account.235 /// * `sponsor`: ID of the account of the sponsor-to-be.236 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {237 self.check_is_internal()?;238239 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());240241 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));242 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));243 <PalletEvm<T>>::deposit_log(244 erc::CollectionHelpersEvents::CollectionChanged {245 collection_id: eth::collection_id_to_address(self.id),246 }247 .to_log(T::ContractAddress::get()),248 );249250 self.save()251 }252253 /// Confirm sponsorship254 ///255 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.256 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].257 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {258 self.check_is_internal()?;259 ensure!(260 self.collection.sponsorship.pending_sponsor() == Some(sender),261 Error::<T>::ConfirmSponsorshipFail262 );263264 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());265266 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));267 <PalletEvm<T>>::deposit_log(268 erc::CollectionHelpersEvents::CollectionChanged {269 collection_id: eth::collection_id_to_address(self.id),270 }271 .to_log(T::ContractAddress::get()),272 );273274 self.save()275 }276277 /// Remove collection sponsor.278 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {279 self.check_is_internal()?;280 self.check_is_owner_or_admin(sender)?;281282 self.collection.sponsorship = SponsorshipState::Disabled;283284 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));285 <PalletEvm<T>>::deposit_log(286 erc::CollectionHelpersEvents::CollectionChanged {287 collection_id: eth::collection_id_to_address(self.id),288 }289 .to_log(T::ContractAddress::get()),290 );291 self.save()292 }293294 /// Force remove `sponsor`.295 ///296 /// Differs from `remove_sponsor` in that297 /// it doesn't require consent from the `owner` of the collection.298 pub fn force_remove_sponsor(&mut self) -> DispatchResult {299 self.check_is_internal()?;300301 self.collection.sponsorship = SponsorshipState::Disabled;302303 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));304 <PalletEvm<T>>::deposit_log(305 erc::CollectionHelpersEvents::CollectionChanged {306 collection_id: eth::collection_id_to_address(self.id),307 }308 .to_log(T::ContractAddress::get()),309 );310 self.save()311 }312313 /// Checks that the collection was created with, and must be operated upon through **Unique API**.314 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.315 pub fn check_is_internal(&self) -> DispatchResult {316 if self.flags.external {317 return Err(<Error<T>>::CollectionIsExternal)?;318 }319320 Ok(())321 }322323 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.324 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.325 pub fn check_is_external(&self) -> DispatchResult {326 if !self.flags.external {327 return Err(<Error<T>>::CollectionIsInternal)?;328 }329330 Ok(())331 }332}333334impl<T: Config> Deref for CollectionHandle<T> {335 type Target = Collection<T::AccountId>;336337 fn deref(&self) -> &Self::Target {338 &self.collection339 }340}341342impl<T: Config> DerefMut for CollectionHandle<T> {343 fn deref_mut(&mut self) -> &mut Self::Target {344 &mut self.collection345 }346}347348impl<T: Config> CollectionHandle<T> {349 /// Checks if the `user` is the owner of the collection.350 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {351 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);352 Ok(())353 }354355 /// Returns **true** if the `user` is the owner or administrator of the collection.356 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {357 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))358 }359360 /// Checks if the `user` is the owner or administrator of the collection.361 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {362 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);363 Ok(())364 }365366 /// Returns **true** if367 /// * the `user`is a collection owner or admin368 /// * the collection limits allow the owner/admins to transfer/burn any collection token369 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {370 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)371 }372373 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.374 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {375 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)376 }377378 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.379 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {380 ensure!(381 <Allowlist<T>>::get((self.id, user)),382 <Error<T>>::AddressNotInAllowlist383 );384 Ok(())385 }386387 /// Changes collection owner to another account388 /// #### Store read/writes389 /// 1 writes390 pub fn change_owner(391 &mut self,392 caller: T::CrossAccountId,393 new_owner: T::CrossAccountId,394 ) -> DispatchResult {395 self.check_is_internal()?;396 self.check_is_owner(&caller)?;397 self.collection.owner = new_owner.as_sub().clone();398399 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(400 self.id,401 new_owner.as_sub().clone(),402 ));403 <PalletEvm<T>>::deposit_log(404 erc::CollectionHelpersEvents::CollectionChanged {405 collection_id: eth::collection_id_to_address(self.id),406 }407 .to_log(T::ContractAddress::get()),408 );409410 self.save()411 }412}413414#[frame_support::pallet]415pub mod pallet {416 use super::*;417 use dispatch::CollectionDispatch;418 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};419 use frame_system::pallet_prelude::*;420 use frame_support::traits::Currency;421 use up_data_structs::{TokenId, mapping::TokenAddressMapping};422 use scale_info::TypeInfo;423 use weights::WeightInfo;424425 #[pallet::config]426 pub trait Config:427 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo428 {429 /// Weight information for functions of this pallet.430 type WeightInfo: WeightInfo;431432 /// Events compatible with [`frame_system::Config::Event`].433 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;434435 /// Handler of accounts and payment.436 type Currency: Currency<Self::AccountId>;437438 /// Set price to create a collection.439 #[pallet::constant]440 type CollectionCreationPrice: Get<441 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,442 >;443444 /// Dispatcher of operations on collections.445 type CollectionDispatch: CollectionDispatch<Self>;446447 /// Account which holds the chain's treasury.448 type TreasuryAccountId: Get<Self::AccountId>;449450 /// Address under which the CollectionHelper contract would be available.451 #[pallet::constant]452 type ContractAddress: Get<H160>;453454 /// Mapper for token addresses to Ethereum addresses.455 type EvmTokenAddressMapping: TokenAddressMapping<H160>;456457 /// Mapper for token addresses to [`CrossAccountId`].458 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;459 }460461 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);462463 #[pallet::pallet]464 #[pallet::storage_version(STORAGE_VERSION)]465 #[pallet::generate_store(pub(super) trait Store)]466 pub struct Pallet<T>(_);467468 #[pallet::extra_constants]469 impl<T: Config> Pallet<T> {470 /// Maximum admins per collection.471 pub fn collection_admins_limit() -> u32 {472 COLLECTION_ADMINS_LIMIT473 }474 }475476 impl<T: Config> Pallet<T> {477 /// Helper function that handles deposit events478 pub fn deposit_event(event: Event<T>) {479 let event = <T as Config>::RuntimeEvent::from(event);480 let event = event.into();481 <frame_system::Pallet<T>>::deposit_event(event)482 }483 }484485 #[pallet::event]486 pub enum Event<T: Config> {487 /// New collection was created488 CollectionCreated(489 /// Globally unique identifier of newly created collection.490 CollectionId,491 /// [`CollectionMode`] converted into _u8_.492 u8,493 /// Collection owner.494 T::AccountId,495 ),496497 /// New collection was destroyed498 CollectionDestroyed(499 /// Globally unique identifier of collection.500 CollectionId,501 ),502503 /// New item was created.504 ItemCreated(505 /// Id of the collection where item was created.506 CollectionId,507 /// Id of an item. Unique within the collection.508 TokenId,509 /// Owner of newly created item510 T::CrossAccountId,511 /// Always 1 for NFT512 u128,513 ),514515 /// Collection item was burned.516 ItemDestroyed(517 /// Id of the collection where item was destroyed.518 CollectionId,519 /// Identifier of burned NFT.520 TokenId,521 /// Which user has destroyed its tokens.522 T::CrossAccountId,523 /// Amount of token pieces destroed. Always 1 for NFT.524 u128,525 ),526527 /// Item was transferred528 Transfer(529 /// Id of collection to which item is belong.530 CollectionId,531 /// Id of an item.532 TokenId,533 /// Original owner of item.534 T::CrossAccountId,535 /// New owner of item.536 T::CrossAccountId,537 /// Amount of token pieces transfered. Always 1 for NFT.538 u128,539 ),540541 /// Amount pieces of token owned by `sender` was approved for `spender`.542 Approved(543 /// Id of collection to which item is belong.544 CollectionId,545 /// Id of an item.546 TokenId,547 /// Original owner of item.548 T::CrossAccountId,549 /// Id for which the approval was granted.550 T::CrossAccountId,551 /// Amount of token pieces transfered. Always 1 for NFT.552 u128,553 ),554555 /// A `sender` approves operations on all owned tokens for `spender`.556 ApprovedForAll(557 /// Id of collection to which item is belong.558 CollectionId,559 /// Owner of a wallet.560 T::CrossAccountId,561 /// Id for which operator status was granted or rewoked.562 T::CrossAccountId,563 /// Is operator status granted or revoked?564 bool,565 ),566567 /// The colletion property has been added or edited.568 CollectionPropertySet(569 /// Id of collection to which property has been set.570 CollectionId,571 /// The property that was set.572 PropertyKey,573 ),574575 /// The property has been deleted.576 CollectionPropertyDeleted(577 /// Id of collection to which property has been deleted.578 CollectionId,579 /// The property that was deleted.580 PropertyKey,581 ),582583 /// The token property has been added or edited.584 TokenPropertySet(585 /// Identifier of the collection whose token has the property set.586 CollectionId,587 /// The token for which the property was set.588 TokenId,589 /// The property that was set.590 PropertyKey,591 ),592593 /// The token property has been deleted.594 TokenPropertyDeleted(595 /// Identifier of the collection whose token has the property deleted.596 CollectionId,597 /// The token for which the property was deleted.598 TokenId,599 /// The property that was deleted.600 PropertyKey,601 ),602603 /// The token property permission of a collection has been set.604 PropertyPermissionSet(605 /// ID of collection to which property permission has been set.606 CollectionId,607 /// The property permission that was set.608 PropertyKey,609 ),610611 /// Address was added to the allow list.612 AllowListAddressAdded(613 /// ID of the affected collection.614 CollectionId,615 /// Address of the added account.616 T::CrossAccountId,617 ),618619 /// Address was removed from the allow list.620 AllowListAddressRemoved(621 /// ID of the affected collection.622 CollectionId,623 /// Address of the removed account.624 T::CrossAccountId,625 ),626627 /// Collection admin was added.628 CollectionAdminAdded(629 /// ID of the affected collection.630 CollectionId,631 /// Admin address.632 T::CrossAccountId,633 ),634635 /// Collection admin was removed.636 CollectionAdminRemoved(637 /// ID of the affected collection.638 CollectionId,639 /// Removed admin address.640 T::CrossAccountId,641 ),642643 /// Collection limits were set.644 CollectionLimitSet(645 /// ID of the affected collection.646 CollectionId,647 ),648649 /// Collection owned was changed.650 CollectionOwnerChanged(651 /// ID of the affected collection.652 CollectionId,653 /// New owner address.654 T::AccountId,655 ),656657 /// Collection permissions were set.658 CollectionPermissionSet(659 /// ID of the affected collection.660 CollectionId,661 ),662663 /// Collection sponsor was set.664 CollectionSponsorSet(665 /// ID of the affected collection.666 CollectionId,667 /// New sponsor address.668 T::AccountId,669 ),670671 /// New sponsor was confirm.672 SponsorshipConfirmed(673 /// ID of the affected collection.674 CollectionId,675 /// New sponsor address.676 T::AccountId,677 ),678679 /// Collection sponsor was removed.680 CollectionSponsorRemoved(681 /// ID of the affected collection.682 CollectionId,683 ),684 }685686 #[pallet::error]687 pub enum Error<T> {688 /// This collection does not exist.689 CollectionNotFound,690 /// Sender parameter and item owner must be equal.691 MustBeTokenOwner,692 /// No permission to perform action693 NoPermission,694 /// Destroying only empty collections is allowed695 CantDestroyNotEmptyCollection,696 /// Collection is not in mint mode.697 PublicMintingNotAllowed,698 /// Address is not in allow list.699 AddressNotInAllowlist,700701 /// Collection name can not be longer than 63 char.702 CollectionNameLimitExceeded,703 /// Collection description can not be longer than 255 char.704 CollectionDescriptionLimitExceeded,705 /// Token prefix can not be longer than 15 char.706 CollectionTokenPrefixLimitExceeded,707 /// Total collections bound exceeded.708 TotalCollectionsLimitExceeded,709 /// Exceeded max admin count710 CollectionAdminCountExceeded,711 /// Collection limit bounds per collection exceeded712 CollectionLimitBoundsExceeded,713 /// Tried to enable permissions which are only permitted to be disabled714 OwnerPermissionsCantBeReverted,715 /// Collection settings not allowing items transferring716 TransferNotAllowed,717 /// Account token limit exceeded per collection718 AccountTokenLimitExceeded,719 /// Collection token limit exceeded720 CollectionTokenLimitExceeded,721 /// Metadata flag frozen722 MetadataFlagFrozen,723724 /// Item does not exist725 TokenNotFound,726 /// Item is balance not enough727 TokenValueTooLow,728 /// Requested value is more than the approved729 ApprovedValueTooLow,730 /// Tried to approve more than owned731 CantApproveMoreThanOwned,732 /// Only spending from eth mirror could be approved733 AddressIsNotEthMirror,734735 /// Can't transfer tokens to ethereum zero address736 AddressIsZero,737738 /// The operation is not supported739 UnsupportedOperation,740741 /// Insufficient funds to perform an action742 NotSufficientFounds,743744 /// User does not satisfy the nesting rule745 UserIsNotAllowedToNest,746 /// Only tokens from specific collections may nest tokens under this one747 SourceCollectionIsNotAllowedToNest,748749 /// Tried to store more data than allowed in collection field750 CollectionFieldSizeExceeded,751752 /// Tried to store more property data than allowed753 NoSpaceForProperty,754755 /// Tried to store more property keys than allowed756 PropertyLimitReached,757758 /// Property key is too long759 PropertyKeyIsTooLong,760761 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed762 InvalidCharacterInPropertyKey,763764 /// Empty property keys are forbidden765 EmptyPropertyKey,766767 /// Tried to access an external collection with an internal API768 CollectionIsExternal,769770 /// Tried to access an internal collection with an external API771 CollectionIsInternal,772773 /// This address is not set as sponsor, use setCollectionSponsor first.774 ConfirmSponsorshipFail,775776 /// The user is not an administrator.777 UserIsNotCollectionAdmin,778 }779780 /// Storage of the count of created collections. Essentially contains the last collection ID.781 #[pallet::storage]782 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;783784 /// Storage of the count of deleted collections.785 #[pallet::storage]786 pub type DestroyedCollectionCount<T> =787 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;788789 /// Storage of collection info.790 #[pallet::storage]791 pub type CollectionById<T> = StorageMap<792 Hasher = Blake2_128Concat,793 Key = CollectionId,794 Value = Collection<<T as frame_system::Config>::AccountId>,795 QueryKind = OptionQuery,796 >;797798 /// Storage of collection properties.799 #[pallet::storage]800 #[pallet::getter(fn collection_properties)]801 pub type CollectionProperties<T> = StorageMap<802 Hasher = Blake2_128Concat,803 Key = CollectionId,804 Value = Properties,805 QueryKind = ValueQuery,806 OnEmpty = up_data_structs::CollectionProperties,807 >;808809 /// Storage of token property permissions of a collection.810 #[pallet::storage]811 #[pallet::getter(fn property_permissions)]812 pub type CollectionPropertyPermissions<T> = StorageMap<813 Hasher = Blake2_128Concat,814 Key = CollectionId,815 Value = PropertiesPermissionMap,816 QueryKind = ValueQuery,817 >;818819 /// Storage of the amount of collection admins.820 #[pallet::storage]821 pub type AdminAmount<T> = StorageMap<822 Hasher = Blake2_128Concat,823 Key = CollectionId,824 Value = u32,825 QueryKind = ValueQuery,826 >;827828 /// List of collection admins.829 #[pallet::storage]830 pub type IsAdmin<T: Config> = StorageNMap<831 Key = (832 Key<Blake2_128Concat, CollectionId>,833 Key<Blake2_128Concat, T::CrossAccountId>,834 ),835 Value = bool,836 QueryKind = ValueQuery,837 >;838839 /// Allowlisted collection users.840 #[pallet::storage]841 pub type Allowlist<T: Config> = StorageNMap<842 Key = (843 Key<Blake2_128Concat, CollectionId>,844 Key<Blake2_128Concat, T::CrossAccountId>,845 ),846 Value = bool,847 QueryKind = ValueQuery,848 >;849850 /// Not used by code, exists only to provide some types to metadata.851 #[pallet::storage]852 pub type DummyStorageValue<T: Config> = StorageValue<853 Value = (854 CollectionStats,855 CollectionId,856 TokenId,857 TokenChild,858 PhantomType<(859 TokenData<T::CrossAccountId>,860 RpcCollection<T::AccountId>,861 // PoV Estimate Info862 PovInfo,863 )>,864 ),865 QueryKind = OptionQuery,866 >;867868 #[pallet::hooks]869 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {870 fn on_runtime_upgrade() -> Weight {871 StorageVersion::new(1).put::<Pallet<T>>();872873 Weight::zero()874 }875 }876}877878impl<T: Config> Pallet<T> {879 /// Enshure that receiver address is correct.880 ///881 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.882 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {883 ensure!(884 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,885 <Error<T>>::AddressIsZero886 );887 Ok(())888 }889890 /// Get a vector of collection admins.891 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {892 <IsAdmin<T>>::iter_prefix((collection,))893 .map(|(a, _)| a)894 .collect()895 }896897 /// Get a vector of users allowed to mint tokens.898 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {899 <Allowlist<T>>::iter_prefix((collection,))900 .map(|(a, _)| a)901 .collect()902 }903904 /// Is `user` allowed to mint token in `collection`.905 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {906 <Allowlist<T>>::get((collection, user))907 }908909 /// Get statistics of collections.910 pub fn collection_stats() -> CollectionStats {911 let created = <CreatedCollectionCount<T>>::get();912 let destroyed = <DestroyedCollectionCount<T>>::get();913 CollectionStats {914 created: created.0,915 destroyed: destroyed.0,916 alive: created.0 - destroyed.0,917 }918 }919920 /// Get the effective limits for the collection.921 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {922 let collection = <CollectionById<T>>::get(collection)?;923 let limits = collection.limits;924 let effective_limits = CollectionLimits {925 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),926 sponsored_data_size: Some(limits.sponsored_data_size()),927 sponsored_data_rate_limit: Some(928 limits929 .sponsored_data_rate_limit930 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),931 ),932 token_limit: Some(limits.token_limit()),933 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(934 match collection.mode {935 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,936 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,937 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,938 },939 )),940 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),941 owner_can_transfer: Some(limits.owner_can_transfer()),942 owner_can_destroy: Some(limits.owner_can_destroy()),943 transfers_enabled: Some(limits.transfers_enabled()),944 };945946 Some(effective_limits)947 }948949 /// Returns information about the `collection` adapted for rpc.950 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {951 let Collection {952 name,953 description,954 owner,955 mode,956 token_prefix,957 sponsorship,958 limits,959 permissions,960 flags,961 } = <CollectionById<T>>::get(collection)?;962963 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)964 .into_iter()965 .map(|(key, permission)| PropertyKeyPermission { key, permission })966 .collect();967968 let properties = <CollectionProperties<T>>::get(collection)969 .into_iter()970 .map(|(key, value)| Property { key, value })971 .collect();972973 let permissions = CollectionPermissions {974 access: Some(permissions.access()),975 mint_mode: Some(permissions.mint_mode()),976 nesting: Some(permissions.nesting().clone()),977 };978979 Some(RpcCollection {980 name: name.into_inner(),981 description: description.into_inner(),982 owner,983 mode,984 token_prefix: token_prefix.into_inner(),985 sponsorship,986 limits,987 permissions,988 token_property_permissions,989 properties,990 read_only: flags.external,991992 flags: RpcCollectionFlags {993 foreign: flags.foreign,994 erc721metadata: flags.erc721metadata,995 },996 })997 }998}9991000macro_rules! limit_default {1001 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1002 $(1003 if let Some($new) = $new.$field {1004 let $old = $old.$field($($arg)?);1005 let _ = $new;1006 let _ = $old;1007 $check1008 } else {1009 $new.$field = $old.$field1010 }1011 )*1012 }};1013}1014macro_rules! limit_default_clone {1015 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1016 $(1017 if let Some($new) = $new.$field.clone() {1018 let $old = $old.$field($($arg)?);1019 let _ = $new;1020 let _ = $old;1021 $check1022 } else {1023 $new.$field = $old.$field.clone()1024 }1025 )*1026 }};1027}10281029impl<T: Config> Pallet<T> {1030 /// Create new collection.1031 ///1032 /// * `owner` - The owner of the collection.1033 /// * `data` - Description of the created collection.1034 /// * `flags` - Extra flags to store.1035 pub fn init_collection(1036 owner: T::CrossAccountId,1037 payer: T::CrossAccountId,1038 data: CreateCollectionData<T::AccountId>,1039 flags: CollectionFlags,1040 ) -> Result<CollectionId, DispatchError> {1041 {1042 ensure!(1043 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1044 Error::<T>::CollectionTokenPrefixLimitExceeded1045 );1046 }10471048 let created_count = <CreatedCollectionCount<T>>::get()1049 .01050 .checked_add(1)1051 .ok_or(ArithmeticError::Overflow)?;1052 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1053 let id = CollectionId(created_count);10541055 // bound Total number of collections1056 ensure!(1057 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1058 <Error<T>>::TotalCollectionsLimitExceeded1059 );10601061 // =========10621063 let collection = Collection {1064 owner: owner.as_sub().clone(),1065 name: data.name,1066 mode: data.mode.clone(),1067 description: data.description,1068 token_prefix: data.token_prefix,1069 sponsorship: data1070 .pending_sponsor1071 .map(SponsorshipState::Unconfirmed)1072 .unwrap_or_default(),1073 limits: data1074 .limits1075 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1076 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1077 permissions: data1078 .permissions1079 .map(|permissions| {1080 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1081 })1082 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1083 flags,1084 };10851086 let mut collection_properties = up_data_structs::CollectionProperties::get();1087 collection_properties1088 .try_set_from_iter(data.properties.into_iter())1089 .map_err(<Error<T>>::from)?;10901091 CollectionProperties::<T>::insert(id, collection_properties);10921093 let mut token_props_permissions = PropertiesPermissionMap::new();1094 token_props_permissions1095 .try_set_from_iter(data.token_property_permissions.into_iter())1096 .map_err(<Error<T>>::from)?;10971098 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);10991100 // Take a (non-refundable) deposit of collection creation1101 {1102 let mut imbalance =1103 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1104 imbalance.subsume(1105 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1106 &T::TreasuryAccountId::get(),1107 T::CollectionCreationPrice::get(),1108 ),1109 );1110 <T as Config>::Currency::settle(1111 payer.as_sub(),1112 imbalance,1113 WithdrawReasons::TRANSFER,1114 ExistenceRequirement::KeepAlive,1115 )1116 .map_err(|_| Error::<T>::NotSufficientFounds)?;1117 }11181119 <CreatedCollectionCount<T>>::put(created_count);1120 <Pallet<T>>::deposit_event(Event::CollectionCreated(1121 id,1122 data.mode.id(),1123 owner.as_sub().clone(),1124 ));1125 <PalletEvm<T>>::deposit_log(1126 erc::CollectionHelpersEvents::CollectionCreated {1127 owner: *owner.as_eth(),1128 collection_id: eth::collection_id_to_address(id),1129 }1130 .to_log(T::ContractAddress::get()),1131 );1132 <CollectionById<T>>::insert(id, collection);1133 Ok(id)1134 }11351136 /// Destroy collection.1137 ///1138 /// * `collection` - Collection handler.1139 /// * `sender` - The owner or administrator of the collection.1140 pub fn destroy_collection(1141 collection: CollectionHandle<T>,1142 sender: &T::CrossAccountId,1143 ) -> DispatchResult {1144 ensure!(1145 collection.limits.owner_can_destroy(),1146 <Error<T>>::NoPermission,1147 );1148 collection.check_is_owner(sender)?;11491150 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1151 .01152 .checked_add(1)1153 .ok_or(ArithmeticError::Overflow)?;11541155 // =========11561157 <DestroyedCollectionCount<T>>::put(destroyed_collections);1158 <CollectionById<T>>::remove(collection.id);1159 <AdminAmount<T>>::remove(collection.id);1160 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1161 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1162 <CollectionProperties<T>>::remove(collection.id);11631164 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11651166 <PalletEvm<T>>::deposit_log(1167 erc::CollectionHelpersEvents::CollectionDestroyed {1168 collection_id: eth::collection_id_to_address(collection.id),1169 }1170 .to_log(T::ContractAddress::get()),1171 );1172 Ok(())1173 }11741175 /// This function sets or removes a collection properties according to1176 /// `properties_updates` contents:1177 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1178 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1179 ///1180 /// This function fires an event for each property change.1181 /// In case of an error, all the changes (including the events) will be reverted1182 /// since the function is transactional.1183 #[transactional]1184 fn modify_collection_properties(1185 collection: &CollectionHandle<T>,1186 sender: &T::CrossAccountId,1187 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1188 ) -> DispatchResult {1189 collection.check_is_owner_or_admin(sender)?;11901191 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11921193 for (key, value) in properties_updates {1194 match value {1195 Some(value) => {1196 stored_properties1197 .try_set(key.clone(), value)1198 .map_err(<Error<T>>::from)?;11991200 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1201 <PalletEvm<T>>::deposit_log(1202 erc::CollectionHelpersEvents::CollectionChanged {1203 collection_id: eth::collection_id_to_address(collection.id),1204 }1205 .to_log(T::ContractAddress::get()),1206 );1207 }1208 None => {1209 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12101211 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1212 <PalletEvm<T>>::deposit_log(1213 erc::CollectionHelpersEvents::CollectionChanged {1214 collection_id: eth::collection_id_to_address(collection.id),1215 }1216 .to_log(T::ContractAddress::get()),1217 );1218 }1219 }1220 }12211222 <CollectionProperties<T>>::set(collection.id, stored_properties);12231224 Ok(())1225 }12261227 /// A batch operation to add, edit or remove properties for a token.1228 /// It sets or removes a token's properties according to1229 /// `properties_updates` contents:1230 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1231 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1232 ///1233 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1234 /// - `is_token_create`: Indicates that method is called during token initialization.1235 /// Allows to bypass ownership check.1236 ///1237 /// All affected properties should have `mutable` permission1238 /// to be **deleted** or to be **set more than once**,1239 /// and the sender should have permission to edit those properties.1240 ///1241 /// This function fires an event for each property change.1242 /// In case of an error, all the changes (including the events) will be reverted1243 /// since the function is transactional.1244 pub fn modify_token_properties(1245 collection: &CollectionHandle<T>,1246 sender: &T::CrossAccountId,1247 token_id: TokenId,1248 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1249 is_token_create: bool,1250 mut stored_properties: Properties,1251 is_token_owner: impl Fn() -> Result<bool, DispatchError>,1252 set_token_properties: impl FnOnce(Properties),1253 log: evm_coder::ethereum::Log,1254 ) -> DispatchResult {1255 let is_collection_admin = collection.is_owner_or_admin(sender);1256 let permissions = Self::property_permissions(collection.id);12571258 let mut token_owner_result = None;1259 let mut is_token_owner = || -> Result<bool, DispatchError> {1260 *token_owner_result.get_or_insert_with(&is_token_owner)1261 };12621263 for (key, value) in properties_updates {1264 let permission = permissions1265 .get(&key)1266 .cloned()1267 .unwrap_or_else(PropertyPermission::none);12681269 let is_property_exists = stored_properties.get(&key).is_some();12701271 match permission {1272 PropertyPermission { mutable: false, .. } if is_property_exists => {1273 return Err(<Error<T>>::NoPermission.into());1274 }12751276 PropertyPermission {1277 collection_admin,1278 token_owner,1279 ..1280 } => {1281 //TODO: investigate threats during public minting.1282 let is_token_create =1283 is_token_create && (collection_admin || token_owner) && value.is_some();1284 if !(is_token_create1285 || (collection_admin && is_collection_admin)1286 || (token_owner && is_token_owner()?))1287 {1288 fail!(<Error<T>>::NoPermission);1289 }1290 }1291 }12921293 match value {1294 Some(value) => {1295 stored_properties1296 .try_set(key.clone(), value)1297 .map_err(<Error<T>>::from)?;12981299 Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1300 }1301 None => {1302 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13031304 Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1305 }1306 }13071308 <PalletEvm<T>>::deposit_log(log.clone());1309 }13101311 set_token_properties(stored_properties);13121313 Ok(())1314 }13151316 /// Sets or unsets the approval of a given operator.1317 ///1318 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1319 /// - `owner`: Token owner1320 /// - `operator`: Operator1321 /// - `approve`: Should operator status be granted or revoked?1322 pub fn set_allowance_for_all(1323 collection: &CollectionHandle<T>,1324 owner: &T::CrossAccountId,1325 operator: &T::CrossAccountId,1326 approve: bool,1327 set_allowance: impl FnOnce(),1328 log: evm_coder::ethereum::Log,1329 ) -> DispatchResult {1330 if collection.permissions.access() == AccessMode::AllowList {1331 collection.check_allowlist(owner)?;1332 collection.check_allowlist(operator)?;1333 }13341335 Self::ensure_correct_receiver(operator)?;13361337 set_allowance();13381339 <PalletEvm<T>>::deposit_log(log);1340 Self::deposit_event(Event::ApprovedForAll(1341 collection.id,1342 owner.clone(),1343 operator.clone(),1344 approve,1345 ));1346 Ok(())1347 }13481349 /// Set collection property.1350 ///1351 /// * `collection` - Collection handler.1352 /// * `sender` - The owner or administrator of the collection.1353 /// * `property` - The property to set.1354 pub fn set_collection_property(1355 collection: &CollectionHandle<T>,1356 sender: &T::CrossAccountId,1357 property: Property,1358 ) -> DispatchResult {1359 Self::set_collection_properties(collection, sender, [property].into_iter())1360 }13611362 /// Set a scoped collection property, where the scope is a special prefix1363 /// prohibiting a user access to change the property directly.1364 ///1365 /// * `collection_id` - ID of the collection for which the property is being set.1366 /// * `scope` - Property scope.1367 /// * `property` - The property to set.1368 pub fn set_scoped_collection_property(1369 collection_id: CollectionId,1370 scope: PropertyScope,1371 property: Property,1372 ) -> DispatchResult {1373 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1374 properties.try_scoped_set(scope, property.key, property.value)1375 })1376 .map_err(<Error<T>>::from)?;13771378 Ok(())1379 }13801381 /// Set scoped collection properties, where the scope is a special prefix1382 /// prohibiting a user access to change the properties directly.1383 ///1384 /// * `collection_id` - ID of the collection for which the properties is being set.1385 /// * `scope` - Property scope.1386 /// * `properties` - The properties to set.1387 pub fn set_scoped_collection_properties(1388 collection_id: CollectionId,1389 scope: PropertyScope,1390 properties: impl Iterator<Item = Property>,1391 ) -> DispatchResult {1392 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1393 stored_properties.try_scoped_set_from_iter(scope, properties)1394 })1395 .map_err(<Error<T>>::from)?;13961397 Ok(())1398 }13991400 /// Set collection properties.1401 ///1402 /// * `collection` - Collection handler.1403 /// * `sender` - The owner or administrator of the collection.1404 /// * `properties` - The properties to set.1405 pub fn set_collection_properties(1406 collection: &CollectionHandle<T>,1407 sender: &T::CrossAccountId,1408 properties: impl Iterator<Item = Property>,1409 ) -> DispatchResult {1410 Self::modify_collection_properties(1411 collection,1412 sender,1413 properties.map(|property| (property.key, Some(property.value))),1414 )1415 }14161417 /// Delete collection property.1418 ///1419 /// * `collection` - Collection handler.1420 /// * `sender` - The owner or administrator of the collection.1421 /// * `property` - The property to delete.1422 pub fn delete_collection_property(1423 collection: &CollectionHandle<T>,1424 sender: &T::CrossAccountId,1425 property_key: PropertyKey,1426 ) -> DispatchResult {1427 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1428 }14291430 /// Delete collection properties.1431 ///1432 /// * `collection` - Collection handler.1433 /// * `sender` - The owner or administrator of the collection.1434 /// * `properties` - The properties to delete.1435 pub fn delete_collection_properties(1436 collection: &CollectionHandle<T>,1437 sender: &T::CrossAccountId,1438 property_keys: impl Iterator<Item = PropertyKey>,1439 ) -> DispatchResult {1440 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1441 }14421443 /// Set collection propetry permission without any checks.1444 ///1445 /// Used for migrations.1446 ///1447 /// * `collection` - Collection handler.1448 /// * `property_permissions` - Property permissions.1449 pub fn set_property_permission_unchecked(1450 collection: CollectionId,1451 property_permission: PropertyKeyPermission,1452 ) -> DispatchResult {1453 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1454 permissions.try_set(property_permission.key, property_permission.permission)1455 })1456 .map_err(<Error<T>>::from)?;1457 Ok(())1458 }14591460 /// Set collection property permission.1461 ///1462 /// * `collection` - Collection handler.1463 /// * `sender` - The owner or administrator of the collection.1464 /// * `property_permission` - Property permission.1465 pub fn set_property_permission(1466 collection: &CollectionHandle<T>,1467 sender: &T::CrossAccountId,1468 property_permission: PropertyKeyPermission,1469 ) -> DispatchResult {1470 Self::set_scoped_property_permission(1471 collection,1472 sender,1473 PropertyScope::None,1474 property_permission,1475 )1476 }14771478 /// Set collection property permission with scope.1479 ///1480 /// * `collection` - Collection handler.1481 /// * `sender` - The owner or administrator of the collection.1482 /// * `scope` - Property scope.1483 /// * `property_permission` - Property permission.1484 pub fn set_scoped_property_permission(1485 collection: &CollectionHandle<T>,1486 sender: &T::CrossAccountId,1487 scope: PropertyScope,1488 property_permission: PropertyKeyPermission,1489 ) -> DispatchResult {1490 collection.check_is_owner_or_admin(sender)?;14911492 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1493 let current_permission = all_permissions.get(&property_permission.key);1494 if matches![1495 current_permission,1496 Some(PropertyPermission { mutable: false, .. })1497 ] {1498 return Err(<Error<T>>::NoPermission.into());1499 }15001501 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1502 let property_permission = property_permission.clone();1503 permissions.try_scoped_set(1504 scope,1505 property_permission.key,1506 property_permission.permission,1507 )1508 })1509 .map_err(<Error<T>>::from)?;15101511 Self::deposit_event(Event::PropertyPermissionSet(1512 collection.id,1513 property_permission.key,1514 ));1515 <PalletEvm<T>>::deposit_log(1516 erc::CollectionHelpersEvents::CollectionChanged {1517 collection_id: eth::collection_id_to_address(collection.id),1518 }1519 .to_log(T::ContractAddress::get()),1520 );15211522 Ok(())1523 }15241525 /// Set token property permission.1526 ///1527 /// * `collection` - Collection handler.1528 /// * `sender` - The owner or administrator of the collection.1529 /// * `property_permissions` - Property permissions.1530 #[transactional]1531 pub fn set_token_property_permissions(1532 collection: &CollectionHandle<T>,1533 sender: &T::CrossAccountId,1534 property_permissions: Vec<PropertyKeyPermission>,1535 ) -> DispatchResult {1536 Self::set_scoped_token_property_permissions(1537 collection,1538 sender,1539 PropertyScope::None,1540 property_permissions,1541 )1542 }15431544 /// Set token property permission with scope.1545 ///1546 /// * `collection` - Collection handler.1547 /// * `sender` - The owner or administrator of the collection.1548 /// * `scope` - Property scope.1549 /// * `property_permissions` - Property permissions.1550 #[transactional]1551 pub fn set_scoped_token_property_permissions(1552 collection: &CollectionHandle<T>,1553 sender: &T::CrossAccountId,1554 scope: PropertyScope,1555 property_permissions: Vec<PropertyKeyPermission>,1556 ) -> DispatchResult {1557 for prop_pemission in property_permissions {1558 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1559 }15601561 Ok(())1562 }15631564 /// Get collection property.1565 pub fn get_collection_property(1566 collection_id: CollectionId,1567 key: &PropertyKey,1568 ) -> Option<PropertyValue> {1569 Self::collection_properties(collection_id).get(key).cloned()1570 }15711572 /// Convert byte vector to property key vector.1573 pub fn bytes_keys_to_property_keys(1574 keys: Vec<Vec<u8>>,1575 ) -> Result<Vec<PropertyKey>, DispatchError> {1576 keys.into_iter()1577 .map(|key| -> Result<PropertyKey, DispatchError> {1578 key.try_into()1579 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1580 })1581 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1582 }15831584 /// Get properties according to given keys.1585 pub fn filter_collection_properties(1586 collection_id: CollectionId,1587 keys: Option<Vec<PropertyKey>>,1588 ) -> Result<Vec<Property>, DispatchError> {1589 let properties = Self::collection_properties(collection_id);15901591 let properties = keys1592 .map(|keys| {1593 keys.into_iter()1594 .filter_map(|key| {1595 properties.get(&key).map(|value| Property {1596 key,1597 value: value.clone(),1598 })1599 })1600 .collect()1601 })1602 .unwrap_or_else(|| {1603 properties1604 .into_iter()1605 .map(|(key, value)| Property { key, value })1606 .collect()1607 });16081609 Ok(properties)1610 }16111612 /// Get property permissions according to given keys.1613 pub fn filter_property_permissions(1614 collection_id: CollectionId,1615 keys: Option<Vec<PropertyKey>>,1616 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1617 let permissions = Self::property_permissions(collection_id);16181619 let key_permissions = keys1620 .map(|keys| {1621 keys.into_iter()1622 .filter_map(|key| {1623 permissions1624 .get(&key)1625 .map(|permission| PropertyKeyPermission {1626 key,1627 permission: permission.clone(),1628 })1629 })1630 .collect()1631 })1632 .unwrap_or_else(|| {1633 permissions1634 .into_iter()1635 .map(|(key, permission)| PropertyKeyPermission { key, permission })1636 .collect()1637 });16381639 Ok(key_permissions)1640 }16411642 /// Toggle `user` participation in the `collection`'s allow list.1643 /// #### Store read/writes1644 /// 1 writes1645 pub fn toggle_allowlist(1646 collection: &CollectionHandle<T>,1647 sender: &T::CrossAccountId,1648 user: &T::CrossAccountId,1649 allowed: bool,1650 ) -> DispatchResult {1651 collection.check_is_owner_or_admin(sender)?;16521653 // =========16541655 if allowed {1656 <Allowlist<T>>::insert((collection.id, user), true);1657 Self::deposit_event(Event::<T>::AllowListAddressAdded(1658 collection.id,1659 user.clone(),1660 ));1661 } else {1662 <Allowlist<T>>::remove((collection.id, user));1663 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1664 collection.id,1665 user.clone(),1666 ));1667 }16681669 <PalletEvm<T>>::deposit_log(1670 erc::CollectionHelpersEvents::CollectionChanged {1671 collection_id: eth::collection_id_to_address(collection.id),1672 }1673 .to_log(T::ContractAddress::get()),1674 );16751676 Ok(())1677 }16781679 /// Toggle `user` participation in the `collection`'s admin list.1680 /// #### Store read/writes1681 /// 2 reads, 2 writes1682 pub fn toggle_admin(1683 collection: &CollectionHandle<T>,1684 sender: &T::CrossAccountId,1685 user: &T::CrossAccountId,1686 admin: bool,1687 ) -> DispatchResult {1688 collection.check_is_internal()?;1689 collection.check_is_owner(sender)?;16901691 let is_admin = <IsAdmin<T>>::get((collection.id, user));1692 if is_admin == admin {1693 if admin {1694 return Ok(());1695 } else {1696 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1697 }1698 }1699 let amount = <AdminAmount<T>>::get(collection.id);17001701 // =========17021703 if admin {1704 let amount = amount1705 .checked_add(1)1706 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1707 ensure!(1708 amount <= Self::collection_admins_limit(),1709 <Error<T>>::CollectionAdminCountExceeded,1710 );17111712 <AdminAmount<T>>::insert(collection.id, amount);1713 <IsAdmin<T>>::insert((collection.id, user), true);17141715 Self::deposit_event(Event::<T>::CollectionAdminAdded(1716 collection.id,1717 user.clone(),1718 ));1719 } else {1720 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1721 <IsAdmin<T>>::remove((collection.id, user));17221723 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1724 collection.id,1725 user.clone(),1726 ));1727 }17281729 <PalletEvm<T>>::deposit_log(1730 erc::CollectionHelpersEvents::CollectionChanged {1731 collection_id: eth::collection_id_to_address(collection.id),1732 }1733 .to_log(T::ContractAddress::get()),1734 );17351736 Ok(())1737 }17381739 /// Update collection limits.1740 pub fn update_limits(1741 user: &T::CrossAccountId,1742 collection: &mut CollectionHandle<T>,1743 new_limit: CollectionLimits,1744 ) -> DispatchResult {1745 collection.check_is_internal()?;1746 collection.check_is_owner_or_admin(user)?;17471748 collection.limits =1749 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17501751 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1752 <PalletEvm<T>>::deposit_log(1753 erc::CollectionHelpersEvents::CollectionChanged {1754 collection_id: eth::collection_id_to_address(collection.id),1755 }1756 .to_log(T::ContractAddress::get()),1757 );17581759 collection.save()1760 }17611762 /// Merge set fields from `new_limit` to `old_limit`.1763 fn clamp_limits(1764 mode: CollectionMode,1765 old_limit: &CollectionLimits,1766 mut new_limit: CollectionLimits,1767 ) -> Result<CollectionLimits, DispatchError> {1768 let limits = old_limit;1769 limit_default!(old_limit, new_limit,1770 account_token_ownership_limit => ensure!(1771 new_limit <= MAX_TOKEN_OWNERSHIP,1772 <Error<T>>::CollectionLimitBoundsExceeded,1773 ),1774 sponsored_data_size => ensure!(1775 new_limit <= CUSTOM_DATA_LIMIT,1776 <Error<T>>::CollectionLimitBoundsExceeded,1777 ),17781779 sponsored_data_rate_limit => {},1780 token_limit => ensure!(1781 old_limit >= new_limit && new_limit > 0,1782 <Error<T>>::CollectionTokenLimitExceeded1783 ),17841785 sponsor_transfer_timeout(match mode {1786 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1787 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1788 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1789 }) => ensure!(1790 new_limit <= MAX_SPONSOR_TIMEOUT,1791 <Error<T>>::CollectionLimitBoundsExceeded,1792 ),1793 sponsor_approve_timeout => {},1794 owner_can_transfer => ensure!(1795 !limits.owner_can_transfer_instaled() ||1796 old_limit || !new_limit,1797 <Error<T>>::OwnerPermissionsCantBeReverted,1798 ),1799 owner_can_destroy => ensure!(1800 old_limit || !new_limit,1801 <Error<T>>::OwnerPermissionsCantBeReverted,1802 ),1803 transfers_enabled => {},1804 );1805 Ok(new_limit)1806 }18071808 /// Update collection permissions.1809 pub fn update_permissions(1810 user: &T::CrossAccountId,1811 collection: &mut CollectionHandle<T>,1812 new_permission: CollectionPermissions,1813 ) -> DispatchResult {1814 collection.check_is_internal()?;1815 collection.check_is_owner_or_admin(user)?;1816 collection.permissions = Self::clamp_permissions(1817 collection.mode.clone(),1818 &collection.permissions,1819 new_permission,1820 )?;18211822 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1823 <PalletEvm<T>>::deposit_log(1824 erc::CollectionHelpersEvents::CollectionChanged {1825 collection_id: eth::collection_id_to_address(collection.id),1826 }1827 .to_log(T::ContractAddress::get()),1828 );18291830 collection.save()1831 }18321833 /// Merge set fields from `new_permission` to `old_permission`.1834 fn clamp_permissions(1835 _mode: CollectionMode,1836 old_permission: &CollectionPermissions,1837 mut new_permission: CollectionPermissions,1838 ) -> Result<CollectionPermissions, DispatchError> {1839 limit_default_clone!(old_permission, new_permission,1840 access => {},1841 mint_mode => {},1842 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1843 );1844 Ok(new_permission)1845 }18461847 /// Repair possibly broken properties of a collection.1848 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1849 CollectionProperties::<T>::mutate(collection_id, |properties| {1850 properties.recompute_consumed_space();1851 });18521853 Ok(())1854 }1855}18561857/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1858#[macro_export]1859macro_rules! unsupported {1860 ($runtime:path) => {1861 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1862 };1863}18641865/// Return weights for various worst-case operations.1866pub trait CommonWeightInfo<CrossAccountId> {1867 /// Weight of item creation.1868 fn create_item(data: &CreateItemData) -> Weight {1869 Self::create_multiple_items(from_ref(data))1870 }18711872 /// Weight of items creation.1873 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18741875 /// Weight of items creation.1876 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18771878 /// The weight of the burning item.1879 fn burn_item() -> Weight;18801881 /// Property setting weight.1882 ///1883 /// * `amount`- The number of properties to set.1884 fn set_collection_properties(amount: u32) -> Weight;18851886 /// Collection property deletion weight.1887 ///1888 /// * `amount`- The number of properties to set.1889 fn delete_collection_properties(amount: u32) -> Weight;18901891 /// Token property setting weight.1892 ///1893 /// * `amount`- The number of properties to set.1894 fn set_token_properties(amount: u32) -> Weight;18951896 /// Token property deletion weight.1897 ///1898 /// * `amount`- The number of properties to delete.1899 fn delete_token_properties(amount: u32) -> Weight;19001901 /// Token property permissions set weight.1902 ///1903 /// * `amount`- The number of property permissions to set.1904 fn set_token_property_permissions(amount: u32) -> Weight;19051906 /// Transfer price of the token or its parts.1907 fn transfer() -> Weight;19081909 /// The price of setting the permission of the operation from another user.1910 fn approve() -> Weight;19111912 /// The price of setting the permission of the operation from another user for eth mirror.1913 fn approve_from() -> Weight;19141915 /// Transfer price from another user.1916 fn transfer_from() -> Weight;19171918 /// The price of burning a token from another user.1919 fn burn_from() -> Weight;19201921 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1922 /// whole users's balance.1923 ///1924 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1925 fn burn_recursively_self_raw() -> Weight;19261927 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1928 ///1929 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1930 fn burn_recursively_breadth_raw(amount: u32) -> Weight;19311932 /// The price of recursive burning a token.1933 ///1934 /// `max_selfs` - The maximum burning weight of the token itself.1935 /// `max_breadth` - The maximum number of nested tokens to burn.1936 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1937 Self::burn_recursively_self_raw()1938 .saturating_mul(max_selfs.max(1) as u64)1939 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1940 }19411942 /// The price of retrieving token owner1943 fn token_owner() -> Weight;19441945 /// The price of setting approval for all1946 fn set_allowance_for_all() -> Weight;19471948 /// The price of repairing an item.1949 fn force_repair_item() -> Weight;1950}19511952/// Weight info extension trait for refungible pallet.1953pub trait RefungibleExtensionsWeightInfo {1954 /// Weight of token repartition.1955 fn repartition() -> Weight;1956}19571958/// Common collection operations.1959///1960/// It wraps methods in Fungible, Nonfungible and Refungible pallets1961/// and adds weight info.1962pub trait CommonCollectionOperations<T: Config> {1963 /// Create token.1964 ///1965 /// * `sender` - The user who mint the token and pays for the transaction.1966 /// * `to` - The user who will own the token.1967 /// * `data` - Token data.1968 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1969 fn create_item(1970 &self,1971 sender: T::CrossAccountId,1972 to: T::CrossAccountId,1973 data: CreateItemData,1974 nesting_budget: &dyn Budget,1975 ) -> DispatchResultWithPostInfo;19761977 /// Create multiple tokens.1978 ///1979 /// * `sender` - The user who mint the token and pays for the transaction.1980 /// * `to` - The user who will own the token.1981 /// * `data` - Token data.1982 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1983 fn create_multiple_items(1984 &self,1985 sender: T::CrossAccountId,1986 to: T::CrossAccountId,1987 data: Vec<CreateItemData>,1988 nesting_budget: &dyn Budget,1989 ) -> DispatchResultWithPostInfo;19901991 /// Create multiple tokens.1992 ///1993 /// * `sender` - The user who mint the token and pays for the transaction.1994 /// * `to` - The user who will own the token.1995 /// * `data` - Token data.1996 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1997 fn create_multiple_items_ex(1998 &self,1999 sender: T::CrossAccountId,2000 data: CreateItemExData<T::CrossAccountId>,2001 nesting_budget: &dyn Budget,2002 ) -> DispatchResultWithPostInfo;20032004 /// Burn token.2005 ///2006 /// * `sender` - The user who owns the token.2007 /// * `token` - Token id that will burned.2008 /// * `amount` - The number of parts of the token that will be burned.2009 fn burn_item(2010 &self,2011 sender: T::CrossAccountId,2012 token: TokenId,2013 amount: u128,2014 ) -> DispatchResultWithPostInfo;20152016 /// Burn token and all nested tokens recursievly.2017 ///2018 /// * `sender` - The user who owns the token.2019 /// * `token` - Token id that will burned.2020 /// * `self_budget` - The budget that can be spent on burning tokens.2021 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2022 fn burn_item_recursively(2023 &self,2024 sender: T::CrossAccountId,2025 token: TokenId,2026 self_budget: &dyn Budget,2027 breadth_budget: &dyn Budget,2028 ) -> DispatchResultWithPostInfo;20292030 /// Set collection properties.2031 ///2032 /// * `sender` - Must be either the owner of the collection or its admin.2033 /// * `properties` - Properties to be set.2034 fn set_collection_properties(2035 &self,2036 sender: T::CrossAccountId,2037 properties: Vec<Property>,2038 ) -> DispatchResultWithPostInfo;20392040 /// Delete collection properties.2041 ///2042 /// * `sender` - Must be either the owner of the collection or its admin.2043 /// * `properties` - The properties to be removed.2044 fn delete_collection_properties(2045 &self,2046 sender: &T::CrossAccountId,2047 property_keys: Vec<PropertyKey>,2048 ) -> DispatchResultWithPostInfo;20492050 /// Set token properties.2051 ///2052 /// The appropriate [`PropertyPermission`] for the token property2053 /// must be set with [`Self::set_token_property_permissions`].2054 ///2055 /// * `sender` - Must be either the owner of the token or its admin.2056 /// * `token_id` - The token for which the properties are being set.2057 /// * `properties` - Properties to be set.2058 /// * `budget` - Budget for setting properties.2059 fn set_token_properties(2060 &self,2061 sender: T::CrossAccountId,2062 token_id: TokenId,2063 properties: Vec<Property>,2064 budget: &dyn Budget,2065 ) -> DispatchResultWithPostInfo;20662067 /// Remove token properties.2068 ///2069 /// The appropriate [`PropertyPermission`] for the token property2070 /// must be set with [`Self::set_token_property_permissions`].2071 ///2072 /// * `sender` - Must be either the owner of the token or its admin.2073 /// * `token_id` - The token for which the properties are being remove.2074 /// * `property_keys` - Keys to remove corresponding properties.2075 /// * `budget` - Budget for removing properties.2076 fn delete_token_properties(2077 &self,2078 sender: T::CrossAccountId,2079 token_id: TokenId,2080 property_keys: Vec<PropertyKey>,2081 budget: &dyn Budget,2082 ) -> DispatchResultWithPostInfo;20832084 /// Set token property permissions.2085 ///2086 /// * `sender` - Must be either the owner of the token or its admin.2087 /// * `token_id` - The token for which the properties are being set.2088 /// * `property_permissions` - Property permissions to be set.2089 /// * `budget` - Budget for setting properties.2090 fn set_token_property_permissions(2091 &self,2092 sender: &T::CrossAccountId,2093 property_permissions: Vec<PropertyKeyPermission>,2094 ) -> DispatchResultWithPostInfo;20952096 /// Transfer amount of token pieces.2097 ///2098 /// * `sender` - Donor user.2099 /// * `to` - Recepient user.2100 /// * `token` - The token of which parts are being sent.2101 /// * `amount` - The number of parts of the token that will be transferred.2102 /// * `budget` - The maximum budget that can be spent on the transfer.2103 fn transfer(2104 &self,2105 sender: T::CrossAccountId,2106 to: T::CrossAccountId,2107 token: TokenId,2108 amount: u128,2109 budget: &dyn Budget,2110 ) -> DispatchResultWithPostInfo;21112112 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2113 ///2114 /// * `sender` - The user who grants access to the token.2115 /// * `spender` - The user to whom the rights are granted.2116 /// * `token` - The token to which access is granted.2117 /// * `amount` - The amount of pieces that another user can dispose of.2118 fn approve(2119 &self,2120 sender: T::CrossAccountId,2121 spender: T::CrossAccountId,2122 token: TokenId,2123 amount: u128,2124 ) -> DispatchResultWithPostInfo;21252126 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2127 ///2128 /// * `sender` - The user who grants access to the token.2129 /// * `from` - Spender's eth mirror.2130 /// * `to` - The user to whom the rights are granted.2131 /// * `token` - The token to which access is granted.2132 /// * `amount` - The amount of pieces that another user can dispose of.2133 fn approve_from(2134 &self,2135 sender: T::CrossAccountId,2136 from: T::CrossAccountId,2137 to: T::CrossAccountId,2138 token: TokenId,2139 amount: u128,2140 ) -> DispatchResultWithPostInfo;21412142 /// Send parts of a token owned by another user.2143 ///2144 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2145 ///2146 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2147 /// * `from` - The user who owns the token.2148 /// * `to` - Recepient user.2149 /// * `token` - The token of which parts are being sent.2150 /// * `amount` - The number of parts of the token that will be transferred.2151 /// * `budget` - The maximum budget that can be spent on the transfer.2152 fn transfer_from(2153 &self,2154 sender: T::CrossAccountId,2155 from: T::CrossAccountId,2156 to: T::CrossAccountId,2157 token: TokenId,2158 amount: u128,2159 budget: &dyn Budget,2160 ) -> DispatchResultWithPostInfo;21612162 /// Burn parts of a token owned by another user.2163 ///2164 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2165 ///2166 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2167 /// * `from` - The user who owns the token.2168 /// * `token` - The token of which parts are being sent.2169 /// * `amount` - The number of parts of the token that will be transferred.2170 /// * `budget` - The maximum budget that can be spent on the burn.2171 fn burn_from(2172 &self,2173 sender: T::CrossAccountId,2174 from: T::CrossAccountId,2175 token: TokenId,2176 amount: u128,2177 budget: &dyn Budget,2178 ) -> DispatchResultWithPostInfo;21792180 /// Check permission to nest token.2181 ///2182 /// * `sender` - The user who initiated the check.2183 /// * `from` - The token that is checked for embedding.2184 /// * `under` - Token under which to check.2185 /// * `budget` - The maximum budget that can be spent on the check.2186 fn check_nesting(2187 &self,2188 sender: T::CrossAccountId,2189 from: (CollectionId, TokenId),2190 under: TokenId,2191 budget: &dyn Budget,2192 ) -> DispatchResult;21932194 /// Nest one token into another.2195 ///2196 /// * `under` - Token holder.2197 /// * `to_nest` - Nested token.2198 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21992200 /// Unnest token.2201 ///2202 /// * `under` - Token holder.2203 /// * `to_nest` - Token to unnest.2204 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22052206 /// Get all user tokens.2207 ///2208 /// * `account` - Account for which you need to get tokens.2209 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22102211 /// Get all the tokens in the collection.2212 fn collection_tokens(&self) -> Vec<TokenId>;22132214 /// Check if the token exists.2215 ///2216 /// * `token` - Id token to check.2217 fn token_exists(&self, token: TokenId) -> bool;22182219 /// Get the id of the last minted token.2220 fn last_token_id(&self) -> TokenId;22212222 /// Get the owner of the token.2223 ///2224 /// * `token` - The token for which you need to find out the owner.2225 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22262227 /// Returns 10 tokens owners in no particular order.2228 ///2229 /// * `token` - The token for which you need to find out the owners.2230 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22312232 /// Get the value of the token property by key.2233 ///2234 /// * `token` - Token with the property to get.2235 /// * `key` - Property name.2236 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22372238 /// Get a set of token properties by key vector.2239 ///2240 /// * `token` - Token with the property to get.2241 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2242 /// then all properties are returned.2243 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22442245 /// Amount of unique collection tokens2246 fn total_supply(&self) -> u32;22472248 /// Amount of different tokens account has.2249 ///2250 /// * `account` - The account for which need to get the balance.2251 fn account_balance(&self, account: T::CrossAccountId) -> u32;22522253 /// Amount of specific token account have.2254 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22552256 /// Amount of token pieces2257 fn total_pieces(&self, token: TokenId) -> Option<u128>;22582259 /// Get the number of parts of the token that a trusted user can manage.2260 ///2261 /// * `sender` - Trusted user.2262 /// * `spender` - Owner of the token.2263 /// * `token` - The token for which to get the value.2264 fn allowance(2265 &self,2266 sender: T::CrossAccountId,2267 spender: T::CrossAccountId,2268 token: TokenId,2269 ) -> u128;22702271 /// Get extension for RFT collection.2272 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22732274 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2275 /// * `owner` - Token owner2276 /// * `operator` - Operator2277 /// * `approve` - Should operator status be granted or revoked?2278 fn set_allowance_for_all(2279 &self,2280 owner: T::CrossAccountId,2281 operator: T::CrossAccountId,2282 approve: bool,2283 ) -> DispatchResultWithPostInfo;22842285 /// Tells whether the given `owner` approves the `operator`.2286 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22872288 /// Repairs a possibly broken item.2289 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2290}22912292/// Extension for RFT collection.2293pub trait RefungibleExtensions<T>2294where2295 T: Config,2296{2297 /// Change the number of parts of the token.2298 ///2299 /// When the value changes down, this function is equivalent to burning parts of the token.2300 ///2301 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2302 /// * `token` - The token for which you want to change the number of parts.2303 /// * `amount` - The new value of the parts of the token.2304 fn repartition(2305 &self,2306 sender: &T::CrossAccountId,2307 token: TokenId,2308 amount: u128,2309 ) -> DispatchResultWithPostInfo;2310}23112312/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2313///2314/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2315pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2316 let post_info = PostDispatchInfo {2317 actual_weight: Some(weight),2318 pays_fee: Pays::Yes,2319 };2320 match res {2321 Ok(()) => Ok(post_info),2322 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2323 }2324}23252326impl<T: Config> From<PropertiesError> for Error<T> {2327 fn from(error: PropertiesError) -> Self {2328 match error {2329 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2330 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2331 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2332 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2333 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2334 }2335 }2336}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::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68 dispatch::Pays,69 transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73 AccessMode, COLLECTION_NUMBER_LIMIT, Collection, RpcCollection, CollectionFlags,74 RpcCollectionFlags, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,75 COLLECTION_ADMINS_LIMIT, TokenId, TokenChild, CollectionStats, MAX_TOKEN_OWNERSHIP,76 CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,77 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,78 CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit, budget::Budget,79 PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyValue,80 PropertyPermission, PropertiesError, TokenOwnerError, PropertyKeyPermission, TokenData,81 TrySetProperty, PropertyScope, CollectionPermissions,82};83use up_pov_estimate_rpc::PovInfo;8485pub use pallet::*;86use sp_core::H160;87use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};8889#[cfg(feature = "runtime-benchmarks")]90pub mod benchmarking;91pub mod dispatch;92pub mod erc;93pub mod eth;94pub mod weights;9596/// Weight info.97pub type SelfWeightOf<T> = <T as Config>::WeightInfo;9899/// Collection handle contains information about collection data and id.100/// Also provides functionality to count consumed gas.101///102/// CollectionHandle is used as a generic wrapper for collections of all types.103/// It allows to perform common operations and queries on any collection type,104/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].105#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]106pub struct CollectionHandle<T: Config> {107 /// Collection id108 pub id: CollectionId,109 collection: Collection<T::AccountId>,110 /// Substrate recorder for counting consumed gas111 pub recorder: SubstrateRecorder<T>,112}113114impl<T: Config> WithRecorder<T> for CollectionHandle<T> {115 fn recorder(&self) -> &SubstrateRecorder<T> {116 &self.recorder117 }118 fn into_recorder(self) -> SubstrateRecorder<T> {119 self.recorder120 }121}122123impl<T: Config> CollectionHandle<T> {124 /// Same as [CollectionHandle::new] but with an explicit gas limit.125 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {126 <CollectionById<T>>::get(id).map(|collection| Self {127 id,128 collection,129 recorder: SubstrateRecorder::new(gas_limit),130 })131 }132133 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].134 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {135 <CollectionById<T>>::get(id).map(|collection| Self {136 id,137 collection,138 recorder,139 })140 }141142 /// Retrives collection data from storage and creates collection handle with default parameters.143 /// If collection not found return `None`144 pub fn new(id: CollectionId) -> Option<Self> {145 Self::new_with_gas_limit(id, u64::MAX)146 }147148 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.149 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {150 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)151 }152153 /// Consume gas for reading.154 pub fn consume_store_reads(155 &self,156 reads: u64,157 ) -> pallet_evm_coder_substrate::execution::Result<()> {158 self.recorder159 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(160 <T as frame_system::Config>::DbWeight::get()161 .read162 .saturating_mul(reads),163 )))164 }165166 /// Consume gas for writing.167 pub fn consume_store_writes(168 &self,169 writes: u64,170 ) -> pallet_evm_coder_substrate::execution::Result<()> {171 self.recorder172 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(173 <T as frame_system::Config>::DbWeight::get()174 .write175 .saturating_mul(writes),176 )))177 }178179 /// Consume gas for reading and writing.180 pub fn consume_store_reads_and_writes(181 &self,182 reads: u64,183 writes: u64,184 ) -> pallet_evm_coder_substrate::execution::Result<()> {185 let weight = <T as frame_system::Config>::DbWeight::get();186 let reads = weight.read.saturating_mul(reads);187 let writes = weight.read.saturating_mul(writes);188 self.recorder189 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(190 reads.saturating_add(writes),191 )))192 }193194 /// Save collection to storage.195 pub fn save(&self) -> DispatchResult {196 <CollectionById<T>>::insert(self.id, &self.collection);197 Ok(())198 }199200 /// Set collection sponsor.201 ///202 /// Unique collections allows sponsoring for certain actions.203 /// This method allows you to set the sponsor of the collection.204 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].205 pub fn set_sponsor(206 &mut self,207 sender: &T::CrossAccountId,208 sponsor: T::AccountId,209 ) -> DispatchResult {210 self.check_is_internal()?;211 self.check_is_owner_or_admin(sender)?;212213 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());214215 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));216 <PalletEvm<T>>::deposit_log(217 erc::CollectionHelpersEvents::CollectionChanged {218 collection_id: eth::collection_id_to_address(self.id),219 }220 .to_log(T::ContractAddress::get()),221 );222223 self.save()224 }225226 /// Force set `sponsor`.227 ///228 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation229 /// from the `sponsor` is not required.230 ///231 /// # Arguments232 ///233 /// * `sender`: Caller's account.234 /// * `sponsor`: ID of the account of the sponsor-to-be.235 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {236 self.check_is_internal()?;237238 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());239240 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));241 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));242 <PalletEvm<T>>::deposit_log(243 erc::CollectionHelpersEvents::CollectionChanged {244 collection_id: eth::collection_id_to_address(self.id),245 }246 .to_log(T::ContractAddress::get()),247 );248249 self.save()250 }251252 /// Confirm sponsorship253 ///254 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.255 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].256 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {257 self.check_is_internal()?;258 ensure!(259 self.collection.sponsorship.pending_sponsor() == Some(sender),260 Error::<T>::ConfirmSponsorshipFail261 );262263 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());264265 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));266 <PalletEvm<T>>::deposit_log(267 erc::CollectionHelpersEvents::CollectionChanged {268 collection_id: eth::collection_id_to_address(self.id),269 }270 .to_log(T::ContractAddress::get()),271 );272273 self.save()274 }275276 /// Remove collection sponsor.277 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {278 self.check_is_internal()?;279 self.check_is_owner_or_admin(sender)?;280281 self.collection.sponsorship = SponsorshipState::Disabled;282283 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));284 <PalletEvm<T>>::deposit_log(285 erc::CollectionHelpersEvents::CollectionChanged {286 collection_id: eth::collection_id_to_address(self.id),287 }288 .to_log(T::ContractAddress::get()),289 );290 self.save()291 }292293 /// Force remove `sponsor`.294 ///295 /// Differs from `remove_sponsor` in that296 /// it doesn't require consent from the `owner` of the collection.297 pub fn force_remove_sponsor(&mut self) -> DispatchResult {298 self.check_is_internal()?;299300 self.collection.sponsorship = SponsorshipState::Disabled;301302 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));303 <PalletEvm<T>>::deposit_log(304 erc::CollectionHelpersEvents::CollectionChanged {305 collection_id: eth::collection_id_to_address(self.id),306 }307 .to_log(T::ContractAddress::get()),308 );309 self.save()310 }311312 /// Checks that the collection was created with, and must be operated upon through **Unique API**.313 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.314 pub fn check_is_internal(&self) -> DispatchResult {315 if self.flags.external {316 return Err(<Error<T>>::CollectionIsExternal)?;317 }318319 Ok(())320 }321322 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.323 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.324 pub fn check_is_external(&self) -> DispatchResult {325 if !self.flags.external {326 return Err(<Error<T>>::CollectionIsInternal)?;327 }328329 Ok(())330 }331}332333impl<T: Config> Deref for CollectionHandle<T> {334 type Target = Collection<T::AccountId>;335336 fn deref(&self) -> &Self::Target {337 &self.collection338 }339}340341impl<T: Config> DerefMut for CollectionHandle<T> {342 fn deref_mut(&mut self) -> &mut Self::Target {343 &mut self.collection344 }345}346347impl<T: Config> CollectionHandle<T> {348 /// Checks if the `user` is the owner of the collection.349 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {350 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);351 Ok(())352 }353354 /// Returns **true** if the `user` is the owner or administrator of the collection.355 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {356 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))357 }358359 /// Checks if the `user` is the owner or administrator of the collection.360 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {361 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);362 Ok(())363 }364365 /// Returns **true** if366 /// * the `user`is a collection owner or admin367 /// * the collection limits allow the owner/admins to transfer/burn any collection token368 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {369 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)370 }371372 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.373 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {374 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)375 }376377 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.378 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {379 ensure!(380 <Allowlist<T>>::get((self.id, user)),381 <Error<T>>::AddressNotInAllowlist382 );383 Ok(())384 }385386 /// Changes collection owner to another account387 /// #### Store read/writes388 /// 1 writes389 pub fn change_owner(390 &mut self,391 caller: T::CrossAccountId,392 new_owner: T::CrossAccountId,393 ) -> DispatchResult {394 self.check_is_internal()?;395 self.check_is_owner(&caller)?;396 self.collection.owner = new_owner.as_sub().clone();397398 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(399 self.id,400 new_owner.as_sub().clone(),401 ));402 <PalletEvm<T>>::deposit_log(403 erc::CollectionHelpersEvents::CollectionChanged {404 collection_id: eth::collection_id_to_address(self.id),405 }406 .to_log(T::ContractAddress::get()),407 );408409 self.save()410 }411}412413#[frame_support::pallet]414pub mod pallet {415 use super::*;416 use dispatch::CollectionDispatch;417 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};418 use frame_system::pallet_prelude::*;419 use frame_support::traits::Currency;420 use up_data_structs::{TokenId, mapping::TokenAddressMapping};421 use scale_info::TypeInfo;422 use weights::WeightInfo;423424 #[pallet::config]425 pub trait Config:426 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo427 {428 /// Weight information for functions of this pallet.429 type WeightInfo: WeightInfo;430431 /// Events compatible with [`frame_system::Config::Event`].432 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;433434 /// Handler of accounts and payment.435 type Currency: Currency<Self::AccountId>;436437 /// Set price to create a collection.438 #[pallet::constant]439 type CollectionCreationPrice: Get<440 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,441 >;442443 /// Dispatcher of operations on collections.444 type CollectionDispatch: CollectionDispatch<Self>;445446 /// Account which holds the chain's treasury.447 type TreasuryAccountId: Get<Self::AccountId>;448449 /// Address under which the CollectionHelper contract would be available.450 #[pallet::constant]451 type ContractAddress: Get<H160>;452453 /// Mapper for token addresses to Ethereum addresses.454 type EvmTokenAddressMapping: TokenAddressMapping<H160>;455456 /// Mapper for token addresses to [`CrossAccountId`].457 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;458 }459460 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);461462 #[pallet::pallet]463 #[pallet::storage_version(STORAGE_VERSION)]464 #[pallet::generate_store(pub(super) trait Store)]465 pub struct Pallet<T>(_);466467 #[pallet::extra_constants]468 impl<T: Config> Pallet<T> {469 /// Maximum admins per collection.470 pub fn collection_admins_limit() -> u32 {471 COLLECTION_ADMINS_LIMIT472 }473 }474475 impl<T: Config> Pallet<T> {476 /// Helper function that handles deposit events477 pub fn deposit_event(event: Event<T>) {478 let event = <T as Config>::RuntimeEvent::from(event);479 let event = event.into();480 <frame_system::Pallet<T>>::deposit_event(event)481 }482 }483484 #[pallet::event]485 pub enum Event<T: Config> {486 /// New collection was created487 CollectionCreated(488 /// Globally unique identifier of newly created collection.489 CollectionId,490 /// [`CollectionMode`] converted into _u8_.491 u8,492 /// Collection owner.493 T::AccountId,494 ),495496 /// New collection was destroyed497 CollectionDestroyed(498 /// Globally unique identifier of collection.499 CollectionId,500 ),501502 /// New item was created.503 ItemCreated(504 /// Id of the collection where item was created.505 CollectionId,506 /// Id of an item. Unique within the collection.507 TokenId,508 /// Owner of newly created item509 T::CrossAccountId,510 /// Always 1 for NFT511 u128,512 ),513514 /// Collection item was burned.515 ItemDestroyed(516 /// Id of the collection where item was destroyed.517 CollectionId,518 /// Identifier of burned NFT.519 TokenId,520 /// Which user has destroyed its tokens.521 T::CrossAccountId,522 /// Amount of token pieces destroed. Always 1 for NFT.523 u128,524 ),525526 /// Item was transferred527 Transfer(528 /// Id of collection to which item is belong.529 CollectionId,530 /// Id of an item.531 TokenId,532 /// Original owner of item.533 T::CrossAccountId,534 /// New owner of item.535 T::CrossAccountId,536 /// Amount of token pieces transfered. Always 1 for NFT.537 u128,538 ),539540 /// Amount pieces of token owned by `sender` was approved for `spender`.541 Approved(542 /// Id of collection to which item is belong.543 CollectionId,544 /// Id of an item.545 TokenId,546 /// Original owner of item.547 T::CrossAccountId,548 /// Id for which the approval was granted.549 T::CrossAccountId,550 /// Amount of token pieces transfered. Always 1 for NFT.551 u128,552 ),553554 /// A `sender` approves operations on all owned tokens for `spender`.555 ApprovedForAll(556 /// Id of collection to which item is belong.557 CollectionId,558 /// Owner of a wallet.559 T::CrossAccountId,560 /// Id for which operator status was granted or rewoked.561 T::CrossAccountId,562 /// Is operator status granted or revoked?563 bool,564 ),565566 /// The colletion property has been added or edited.567 CollectionPropertySet(568 /// Id of collection to which property has been set.569 CollectionId,570 /// The property that was set.571 PropertyKey,572 ),573574 /// The property has been deleted.575 CollectionPropertyDeleted(576 /// Id of collection to which property has been deleted.577 CollectionId,578 /// The property that was deleted.579 PropertyKey,580 ),581582 /// The token property has been added or edited.583 TokenPropertySet(584 /// Identifier of the collection whose token has the property set.585 CollectionId,586 /// The token for which the property was set.587 TokenId,588 /// The property that was set.589 PropertyKey,590 ),591592 /// The token property has been deleted.593 TokenPropertyDeleted(594 /// Identifier of the collection whose token has the property deleted.595 CollectionId,596 /// The token for which the property was deleted.597 TokenId,598 /// The property that was deleted.599 PropertyKey,600 ),601602 /// The token property permission of a collection has been set.603 PropertyPermissionSet(604 /// ID of collection to which property permission has been set.605 CollectionId,606 /// The property permission that was set.607 PropertyKey,608 ),609610 /// Address was added to the allow list.611 AllowListAddressAdded(612 /// ID of the affected collection.613 CollectionId,614 /// Address of the added account.615 T::CrossAccountId,616 ),617618 /// Address was removed from the allow list.619 AllowListAddressRemoved(620 /// ID of the affected collection.621 CollectionId,622 /// Address of the removed account.623 T::CrossAccountId,624 ),625626 /// Collection admin was added.627 CollectionAdminAdded(628 /// ID of the affected collection.629 CollectionId,630 /// Admin address.631 T::CrossAccountId,632 ),633634 /// Collection admin was removed.635 CollectionAdminRemoved(636 /// ID of the affected collection.637 CollectionId,638 /// Removed admin address.639 T::CrossAccountId,640 ),641642 /// Collection limits were set.643 CollectionLimitSet(644 /// ID of the affected collection.645 CollectionId,646 ),647648 /// Collection owned was changed.649 CollectionOwnerChanged(650 /// ID of the affected collection.651 CollectionId,652 /// New owner address.653 T::AccountId,654 ),655656 /// Collection permissions were set.657 CollectionPermissionSet(658 /// ID of the affected collection.659 CollectionId,660 ),661662 /// Collection sponsor was set.663 CollectionSponsorSet(664 /// ID of the affected collection.665 CollectionId,666 /// New sponsor address.667 T::AccountId,668 ),669670 /// New sponsor was confirm.671 SponsorshipConfirmed(672 /// ID of the affected collection.673 CollectionId,674 /// New sponsor address.675 T::AccountId,676 ),677678 /// Collection sponsor was removed.679 CollectionSponsorRemoved(680 /// ID of the affected collection.681 CollectionId,682 ),683 }684685 #[pallet::error]686 pub enum Error<T> {687 /// This collection does not exist.688 CollectionNotFound,689 /// Sender parameter and item owner must be equal.690 MustBeTokenOwner,691 /// No permission to perform action692 NoPermission,693 /// Destroying only empty collections is allowed694 CantDestroyNotEmptyCollection,695 /// Collection is not in mint mode.696 PublicMintingNotAllowed,697 /// Address is not in allow list.698 AddressNotInAllowlist,699700 /// Collection name can not be longer than 63 char.701 CollectionNameLimitExceeded,702 /// Collection description can not be longer than 255 char.703 CollectionDescriptionLimitExceeded,704 /// Token prefix can not be longer than 15 char.705 CollectionTokenPrefixLimitExceeded,706 /// Total collections bound exceeded.707 TotalCollectionsLimitExceeded,708 /// Exceeded max admin count709 CollectionAdminCountExceeded,710 /// Collection limit bounds per collection exceeded711 CollectionLimitBoundsExceeded,712 /// Tried to enable permissions which are only permitted to be disabled713 OwnerPermissionsCantBeReverted,714 /// Collection settings not allowing items transferring715 TransferNotAllowed,716 /// Account token limit exceeded per collection717 AccountTokenLimitExceeded,718 /// Collection token limit exceeded719 CollectionTokenLimitExceeded,720 /// Metadata flag frozen721 MetadataFlagFrozen,722723 /// Item does not exist724 TokenNotFound,725 /// Item is balance not enough726 TokenValueTooLow,727 /// Requested value is more than the approved728 ApprovedValueTooLow,729 /// Tried to approve more than owned730 CantApproveMoreThanOwned,731 /// Only spending from eth mirror could be approved732 AddressIsNotEthMirror,733734 /// Can't transfer tokens to ethereum zero address735 AddressIsZero,736737 /// The operation is not supported738 UnsupportedOperation,739740 /// Insufficient funds to perform an action741 NotSufficientFounds,742743 /// User does not satisfy the nesting rule744 UserIsNotAllowedToNest,745 /// Only tokens from specific collections may nest tokens under this one746 SourceCollectionIsNotAllowedToNest,747748 /// Tried to store more data than allowed in collection field749 CollectionFieldSizeExceeded,750751 /// Tried to store more property data than allowed752 NoSpaceForProperty,753754 /// Tried to store more property keys than allowed755 PropertyLimitReached,756757 /// Property key is too long758 PropertyKeyIsTooLong,759760 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed761 InvalidCharacterInPropertyKey,762763 /// Empty property keys are forbidden764 EmptyPropertyKey,765766 /// Tried to access an external collection with an internal API767 CollectionIsExternal,768769 /// Tried to access an internal collection with an external API770 CollectionIsInternal,771772 /// This address is not set as sponsor, use setCollectionSponsor first.773 ConfirmSponsorshipFail,774775 /// The user is not an administrator.776 UserIsNotCollectionAdmin,777 }778779 /// Storage of the count of created collections. Essentially contains the last collection ID.780 #[pallet::storage]781 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;782783 /// Storage of the count of deleted collections.784 #[pallet::storage]785 pub type DestroyedCollectionCount<T> =786 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;787788 /// Storage of collection info.789 #[pallet::storage]790 pub type CollectionById<T> = StorageMap<791 Hasher = Blake2_128Concat,792 Key = CollectionId,793 Value = Collection<<T as frame_system::Config>::AccountId>,794 QueryKind = OptionQuery,795 >;796797 /// Storage of collection properties.798 #[pallet::storage]799 #[pallet::getter(fn collection_properties)]800 pub type CollectionProperties<T> = StorageMap<801 Hasher = Blake2_128Concat,802 Key = CollectionId,803 Value = Properties,804 QueryKind = ValueQuery,805 OnEmpty = up_data_structs::CollectionProperties,806 >;807808 /// Storage of token property permissions of a collection.809 #[pallet::storage]810 #[pallet::getter(fn property_permissions)]811 pub type CollectionPropertyPermissions<T> = StorageMap<812 Hasher = Blake2_128Concat,813 Key = CollectionId,814 Value = PropertiesPermissionMap,815 QueryKind = ValueQuery,816 >;817818 /// Storage of the amount of collection admins.819 #[pallet::storage]820 pub type AdminAmount<T> = StorageMap<821 Hasher = Blake2_128Concat,822 Key = CollectionId,823 Value = u32,824 QueryKind = ValueQuery,825 >;826827 /// List of collection admins.828 #[pallet::storage]829 pub type IsAdmin<T: Config> = StorageNMap<830 Key = (831 Key<Blake2_128Concat, CollectionId>,832 Key<Blake2_128Concat, T::CrossAccountId>,833 ),834 Value = bool,835 QueryKind = ValueQuery,836 >;837838 /// Allowlisted collection users.839 #[pallet::storage]840 pub type Allowlist<T: Config> = StorageNMap<841 Key = (842 Key<Blake2_128Concat, CollectionId>,843 Key<Blake2_128Concat, T::CrossAccountId>,844 ),845 Value = bool,846 QueryKind = ValueQuery,847 >;848849 /// Not used by code, exists only to provide some types to metadata.850 #[pallet::storage]851 pub type DummyStorageValue<T: Config> = StorageValue<852 Value = (853 CollectionStats,854 CollectionId,855 TokenId,856 TokenChild,857 PhantomType<(858 TokenData<T::CrossAccountId>,859 RpcCollection<T::AccountId>,860 // PoV Estimate Info861 PovInfo,862 )>,863 ),864 QueryKind = OptionQuery,865 >;866867 #[pallet::hooks]868 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {869 fn on_runtime_upgrade() -> Weight {870 StorageVersion::new(1).put::<Pallet<T>>();871872 Weight::zero()873 }874 }875}876877impl<T: Config> Pallet<T> {878 /// Enshure that receiver address is correct.879 ///880 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.881 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {882 ensure!(883 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,884 <Error<T>>::AddressIsZero885 );886 Ok(())887 }888889 /// Get a vector of collection admins.890 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {891 <IsAdmin<T>>::iter_prefix((collection,))892 .map(|(a, _)| a)893 .collect()894 }895896 /// Get a vector of users allowed to mint tokens.897 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {898 <Allowlist<T>>::iter_prefix((collection,))899 .map(|(a, _)| a)900 .collect()901 }902903 /// Is `user` allowed to mint token in `collection`.904 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {905 <Allowlist<T>>::get((collection, user))906 }907908 /// Get statistics of collections.909 pub fn collection_stats() -> CollectionStats {910 let created = <CreatedCollectionCount<T>>::get();911 let destroyed = <DestroyedCollectionCount<T>>::get();912 CollectionStats {913 created: created.0,914 destroyed: destroyed.0,915 alive: created.0 - destroyed.0,916 }917 }918919 /// Get the effective limits for the collection.920 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {921 let collection = <CollectionById<T>>::get(collection)?;922 let limits = collection.limits;923 let effective_limits = CollectionLimits {924 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),925 sponsored_data_size: Some(limits.sponsored_data_size()),926 sponsored_data_rate_limit: Some(927 limits928 .sponsored_data_rate_limit929 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),930 ),931 token_limit: Some(limits.token_limit()),932 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(933 match collection.mode {934 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,935 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,936 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,937 },938 )),939 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),940 owner_can_transfer: Some(limits.owner_can_transfer()),941 owner_can_destroy: Some(limits.owner_can_destroy()),942 transfers_enabled: Some(limits.transfers_enabled()),943 };944945 Some(effective_limits)946 }947948 /// Returns information about the `collection` adapted for rpc.949 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {950 let Collection {951 name,952 description,953 owner,954 mode,955 token_prefix,956 sponsorship,957 limits,958 permissions,959 flags,960 } = <CollectionById<T>>::get(collection)?;961962 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)963 .into_iter()964 .map(|(key, permission)| PropertyKeyPermission { key, permission })965 .collect();966967 let properties = <CollectionProperties<T>>::get(collection)968 .into_iter()969 .map(|(key, value)| Property { key, value })970 .collect();971972 let permissions = CollectionPermissions {973 access: Some(permissions.access()),974 mint_mode: Some(permissions.mint_mode()),975 nesting: Some(permissions.nesting().clone()),976 };977978 Some(RpcCollection {979 name: name.into_inner(),980 description: description.into_inner(),981 owner,982 mode,983 token_prefix: token_prefix.into_inner(),984 sponsorship,985 limits,986 permissions,987 token_property_permissions,988 properties,989 read_only: flags.external,990991 flags: RpcCollectionFlags {992 foreign: flags.foreign,993 erc721metadata: flags.erc721metadata,994 },995 })996 }997}998999macro_rules! limit_default {1000 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1001 $(1002 if let Some($new) = $new.$field {1003 let $old = $old.$field($($arg)?);1004 let _ = $new;1005 let _ = $old;1006 $check1007 } else {1008 $new.$field = $old.$field1009 }1010 )*1011 }};1012}1013macro_rules! limit_default_clone {1014 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1015 $(1016 if let Some($new) = $new.$field.clone() {1017 let $old = $old.$field($($arg)?);1018 let _ = $new;1019 let _ = $old;1020 $check1021 } else {1022 $new.$field = $old.$field.clone()1023 }1024 )*1025 }};1026}10271028impl<T: Config> Pallet<T> {1029 /// Create new collection.1030 ///1031 /// * `owner` - The owner of the collection.1032 /// * `data` - Description of the created collection.1033 /// * `flags` - Extra flags to store.1034 pub fn init_collection(1035 owner: T::CrossAccountId,1036 payer: T::CrossAccountId,1037 data: CreateCollectionData<T::AccountId>,1038 flags: CollectionFlags,1039 ) -> Result<CollectionId, DispatchError> {1040 {1041 ensure!(1042 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1043 Error::<T>::CollectionTokenPrefixLimitExceeded1044 );1045 }10461047 let created_count = <CreatedCollectionCount<T>>::get()1048 .01049 .checked_add(1)1050 .ok_or(ArithmeticError::Overflow)?;1051 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1052 let id = CollectionId(created_count);10531054 // bound Total number of collections1055 ensure!(1056 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1057 <Error<T>>::TotalCollectionsLimitExceeded1058 );10591060 // =========10611062 let collection = Collection {1063 owner: owner.as_sub().clone(),1064 name: data.name,1065 mode: data.mode.clone(),1066 description: data.description,1067 token_prefix: data.token_prefix,1068 sponsorship: data1069 .pending_sponsor1070 .map(SponsorshipState::Unconfirmed)1071 .unwrap_or_default(),1072 limits: data1073 .limits1074 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1075 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1076 permissions: data1077 .permissions1078 .map(|permissions| {1079 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1080 })1081 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1082 flags,1083 };10841085 let mut collection_properties = up_data_structs::CollectionProperties::get();1086 collection_properties1087 .try_set_from_iter(data.properties.into_iter())1088 .map_err(<Error<T>>::from)?;10891090 CollectionProperties::<T>::insert(id, collection_properties);10911092 let mut token_props_permissions = PropertiesPermissionMap::new();1093 token_props_permissions1094 .try_set_from_iter(data.token_property_permissions.into_iter())1095 .map_err(<Error<T>>::from)?;10961097 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);10981099 // Take a (non-refundable) deposit of collection creation1100 {1101 let mut imbalance =1102 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1103 imbalance.subsume(1104 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1105 &T::TreasuryAccountId::get(),1106 T::CollectionCreationPrice::get(),1107 ),1108 );1109 <T as Config>::Currency::settle(1110 payer.as_sub(),1111 imbalance,1112 WithdrawReasons::TRANSFER,1113 ExistenceRequirement::KeepAlive,1114 )1115 .map_err(|_| Error::<T>::NotSufficientFounds)?;1116 }11171118 <CreatedCollectionCount<T>>::put(created_count);1119 <Pallet<T>>::deposit_event(Event::CollectionCreated(1120 id,1121 data.mode.id(),1122 owner.as_sub().clone(),1123 ));1124 <PalletEvm<T>>::deposit_log(1125 erc::CollectionHelpersEvents::CollectionCreated {1126 owner: *owner.as_eth(),1127 collection_id: eth::collection_id_to_address(id),1128 }1129 .to_log(T::ContractAddress::get()),1130 );1131 <CollectionById<T>>::insert(id, collection);1132 Ok(id)1133 }11341135 /// Destroy collection.1136 ///1137 /// * `collection` - Collection handler.1138 /// * `sender` - The owner or administrator of the collection.1139 pub fn destroy_collection(1140 collection: CollectionHandle<T>,1141 sender: &T::CrossAccountId,1142 ) -> DispatchResult {1143 ensure!(1144 collection.limits.owner_can_destroy(),1145 <Error<T>>::NoPermission,1146 );1147 collection.check_is_owner(sender)?;11481149 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1150 .01151 .checked_add(1)1152 .ok_or(ArithmeticError::Overflow)?;11531154 // =========11551156 <DestroyedCollectionCount<T>>::put(destroyed_collections);1157 <CollectionById<T>>::remove(collection.id);1158 <AdminAmount<T>>::remove(collection.id);1159 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1160 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1161 <CollectionProperties<T>>::remove(collection.id);11621163 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11641165 <PalletEvm<T>>::deposit_log(1166 erc::CollectionHelpersEvents::CollectionDestroyed {1167 collection_id: eth::collection_id_to_address(collection.id),1168 }1169 .to_log(T::ContractAddress::get()),1170 );1171 Ok(())1172 }11731174 /// This function sets or removes a collection properties according to1175 /// `properties_updates` contents:1176 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1177 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1178 ///1179 /// This function fires an event for each property change.1180 /// In case of an error, all the changes (including the events) will be reverted1181 /// since the function is transactional.1182 #[transactional]1183 fn modify_collection_properties(1184 collection: &CollectionHandle<T>,1185 sender: &T::CrossAccountId,1186 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1187 ) -> DispatchResult {1188 collection.check_is_owner_or_admin(sender)?;11891190 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);11911192 for (key, value) in properties_updates {1193 match value {1194 Some(value) => {1195 stored_properties1196 .try_set(key.clone(), value)1197 .map_err(<Error<T>>::from)?;11981199 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1200 <PalletEvm<T>>::deposit_log(1201 erc::CollectionHelpersEvents::CollectionChanged {1202 collection_id: eth::collection_id_to_address(collection.id),1203 }1204 .to_log(T::ContractAddress::get()),1205 );1206 }1207 None => {1208 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12091210 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1211 <PalletEvm<T>>::deposit_log(1212 erc::CollectionHelpersEvents::CollectionChanged {1213 collection_id: eth::collection_id_to_address(collection.id),1214 }1215 .to_log(T::ContractAddress::get()),1216 );1217 }1218 }1219 }12201221 <CollectionProperties<T>>::set(collection.id, stored_properties);12221223 Ok(())1224 }12251226 /// A batch operation to add, edit or remove properties for a token.1227 /// It sets or removes a token's properties according to1228 /// `properties_updates` contents:1229 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1230 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1231 ///1232 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1233 /// - `is_token_create`: Indicates that method is called during token initialization.1234 /// Allows to bypass ownership check.1235 ///1236 /// All affected properties should have `mutable` permission1237 /// to be **deleted** or to be **set more than once**,1238 /// and the sender should have permission to edit those properties.1239 ///1240 /// This function fires an event for each property change.1241 /// In case of an error, all the changes (including the events) will be reverted1242 /// since the function is transactional.1243 pub fn modify_token_properties(1244 collection: &CollectionHandle<T>,1245 sender: &T::CrossAccountId,1246 token_id: TokenId,1247 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1248 is_token_create: bool,1249 mut stored_properties: Properties,1250 is_token_owner: impl Fn() -> Result<bool, DispatchError>,1251 set_token_properties: impl FnOnce(Properties),1252 log: evm_coder::ethereum::Log,1253 ) -> DispatchResult {1254 let is_collection_admin = collection.is_owner_or_admin(sender);1255 let permissions = Self::property_permissions(collection.id);12561257 let mut token_owner_result = None;1258 let mut is_token_owner = || -> Result<bool, DispatchError> {1259 *token_owner_result.get_or_insert_with(&is_token_owner)1260 };12611262 for (key, value) in properties_updates {1263 let permission = permissions1264 .get(&key)1265 .cloned()1266 .unwrap_or_else(PropertyPermission::none);12671268 let is_property_exists = stored_properties.get(&key).is_some();12691270 match permission {1271 PropertyPermission { mutable: false, .. } if is_property_exists => {1272 return Err(<Error<T>>::NoPermission.into());1273 }12741275 PropertyPermission {1276 collection_admin,1277 token_owner,1278 ..1279 } => {1280 //TODO: investigate threats during public minting.1281 let is_token_create =1282 is_token_create && (collection_admin || token_owner) && value.is_some();1283 if !(is_token_create1284 || (collection_admin && is_collection_admin)1285 || (token_owner && is_token_owner()?))1286 {1287 fail!(<Error<T>>::NoPermission);1288 }1289 }1290 }12911292 match value {1293 Some(value) => {1294 stored_properties1295 .try_set(key.clone(), value)1296 .map_err(<Error<T>>::from)?;12971298 Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1299 }1300 None => {1301 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13021303 Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1304 }1305 }13061307 <PalletEvm<T>>::deposit_log(log.clone());1308 }13091310 set_token_properties(stored_properties);13111312 Ok(())1313 }13141315 /// Sets or unsets the approval of a given operator.1316 ///1317 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1318 /// - `owner`: Token owner1319 /// - `operator`: Operator1320 /// - `approve`: Should operator status be granted or revoked?1321 pub fn set_allowance_for_all(1322 collection: &CollectionHandle<T>,1323 owner: &T::CrossAccountId,1324 operator: &T::CrossAccountId,1325 approve: bool,1326 set_allowance: impl FnOnce(),1327 log: evm_coder::ethereum::Log,1328 ) -> DispatchResult {1329 if collection.permissions.access() == AccessMode::AllowList {1330 collection.check_allowlist(owner)?;1331 collection.check_allowlist(operator)?;1332 }13331334 Self::ensure_correct_receiver(operator)?;13351336 set_allowance();13371338 <PalletEvm<T>>::deposit_log(log);1339 Self::deposit_event(Event::ApprovedForAll(1340 collection.id,1341 owner.clone(),1342 operator.clone(),1343 approve,1344 ));1345 Ok(())1346 }13471348 /// Set collection property.1349 ///1350 /// * `collection` - Collection handler.1351 /// * `sender` - The owner or administrator of the collection.1352 /// * `property` - The property to set.1353 pub fn set_collection_property(1354 collection: &CollectionHandle<T>,1355 sender: &T::CrossAccountId,1356 property: Property,1357 ) -> DispatchResult {1358 Self::set_collection_properties(collection, sender, [property].into_iter())1359 }13601361 /// Set a scoped collection property, where the scope is a special prefix1362 /// prohibiting a user access to change the property directly.1363 ///1364 /// * `collection_id` - ID of the collection for which the property is being set.1365 /// * `scope` - Property scope.1366 /// * `property` - The property to set.1367 pub fn set_scoped_collection_property(1368 collection_id: CollectionId,1369 scope: PropertyScope,1370 property: Property,1371 ) -> DispatchResult {1372 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1373 properties.try_scoped_set(scope, property.key, property.value)1374 })1375 .map_err(<Error<T>>::from)?;13761377 Ok(())1378 }13791380 /// Set scoped collection properties, where the scope is a special prefix1381 /// prohibiting a user access to change the properties directly.1382 ///1383 /// * `collection_id` - ID of the collection for which the properties is being set.1384 /// * `scope` - Property scope.1385 /// * `properties` - The properties to set.1386 pub fn set_scoped_collection_properties(1387 collection_id: CollectionId,1388 scope: PropertyScope,1389 properties: impl Iterator<Item = Property>,1390 ) -> DispatchResult {1391 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1392 stored_properties.try_scoped_set_from_iter(scope, properties)1393 })1394 .map_err(<Error<T>>::from)?;13951396 Ok(())1397 }13981399 /// Set collection properties.1400 ///1401 /// * `collection` - Collection handler.1402 /// * `sender` - The owner or administrator of the collection.1403 /// * `properties` - The properties to set.1404 pub fn set_collection_properties(1405 collection: &CollectionHandle<T>,1406 sender: &T::CrossAccountId,1407 properties: impl Iterator<Item = Property>,1408 ) -> DispatchResult {1409 Self::modify_collection_properties(1410 collection,1411 sender,1412 properties.map(|property| (property.key, Some(property.value))),1413 )1414 }14151416 /// Delete collection property.1417 ///1418 /// * `collection` - Collection handler.1419 /// * `sender` - The owner or administrator of the collection.1420 /// * `property` - The property to delete.1421 pub fn delete_collection_property(1422 collection: &CollectionHandle<T>,1423 sender: &T::CrossAccountId,1424 property_key: PropertyKey,1425 ) -> DispatchResult {1426 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1427 }14281429 /// Delete collection properties.1430 ///1431 /// * `collection` - Collection handler.1432 /// * `sender` - The owner or administrator of the collection.1433 /// * `properties` - The properties to delete.1434 pub fn delete_collection_properties(1435 collection: &CollectionHandle<T>,1436 sender: &T::CrossAccountId,1437 property_keys: impl Iterator<Item = PropertyKey>,1438 ) -> DispatchResult {1439 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1440 }14411442 /// Set collection propetry permission without any checks.1443 ///1444 /// Used for migrations.1445 ///1446 /// * `collection` - Collection handler.1447 /// * `property_permissions` - Property permissions.1448 pub fn set_property_permission_unchecked(1449 collection: CollectionId,1450 property_permission: PropertyKeyPermission,1451 ) -> DispatchResult {1452 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1453 permissions.try_set(property_permission.key, property_permission.permission)1454 })1455 .map_err(<Error<T>>::from)?;1456 Ok(())1457 }14581459 /// Set collection property permission.1460 ///1461 /// * `collection` - Collection handler.1462 /// * `sender` - The owner or administrator of the collection.1463 /// * `property_permission` - Property permission.1464 pub fn set_property_permission(1465 collection: &CollectionHandle<T>,1466 sender: &T::CrossAccountId,1467 property_permission: PropertyKeyPermission,1468 ) -> DispatchResult {1469 Self::set_scoped_property_permission(1470 collection,1471 sender,1472 PropertyScope::None,1473 property_permission,1474 )1475 }14761477 /// Set collection property permission with scope.1478 ///1479 /// * `collection` - Collection handler.1480 /// * `sender` - The owner or administrator of the collection.1481 /// * `scope` - Property scope.1482 /// * `property_permission` - Property permission.1483 pub fn set_scoped_property_permission(1484 collection: &CollectionHandle<T>,1485 sender: &T::CrossAccountId,1486 scope: PropertyScope,1487 property_permission: PropertyKeyPermission,1488 ) -> DispatchResult {1489 collection.check_is_owner_or_admin(sender)?;14901491 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1492 let current_permission = all_permissions.get(&property_permission.key);1493 if matches![1494 current_permission,1495 Some(PropertyPermission { mutable: false, .. })1496 ] {1497 return Err(<Error<T>>::NoPermission.into());1498 }14991500 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1501 let property_permission = property_permission.clone();1502 permissions.try_scoped_set(1503 scope,1504 property_permission.key,1505 property_permission.permission,1506 )1507 })1508 .map_err(<Error<T>>::from)?;15091510 Self::deposit_event(Event::PropertyPermissionSet(1511 collection.id,1512 property_permission.key,1513 ));1514 <PalletEvm<T>>::deposit_log(1515 erc::CollectionHelpersEvents::CollectionChanged {1516 collection_id: eth::collection_id_to_address(collection.id),1517 }1518 .to_log(T::ContractAddress::get()),1519 );15201521 Ok(())1522 }15231524 /// Set token property permission.1525 ///1526 /// * `collection` - Collection handler.1527 /// * `sender` - The owner or administrator of the collection.1528 /// * `property_permissions` - Property permissions.1529 #[transactional]1530 pub fn set_token_property_permissions(1531 collection: &CollectionHandle<T>,1532 sender: &T::CrossAccountId,1533 property_permissions: Vec<PropertyKeyPermission>,1534 ) -> DispatchResult {1535 Self::set_scoped_token_property_permissions(1536 collection,1537 sender,1538 PropertyScope::None,1539 property_permissions,1540 )1541 }15421543 /// Set token property permission with scope.1544 ///1545 /// * `collection` - Collection handler.1546 /// * `sender` - The owner or administrator of the collection.1547 /// * `scope` - Property scope.1548 /// * `property_permissions` - Property permissions.1549 #[transactional]1550 pub fn set_scoped_token_property_permissions(1551 collection: &CollectionHandle<T>,1552 sender: &T::CrossAccountId,1553 scope: PropertyScope,1554 property_permissions: Vec<PropertyKeyPermission>,1555 ) -> DispatchResult {1556 for prop_pemission in property_permissions {1557 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1558 }15591560 Ok(())1561 }15621563 /// Get collection property.1564 pub fn get_collection_property(1565 collection_id: CollectionId,1566 key: &PropertyKey,1567 ) -> Option<PropertyValue> {1568 Self::collection_properties(collection_id).get(key).cloned()1569 }15701571 /// Convert byte vector to property key vector.1572 pub fn bytes_keys_to_property_keys(1573 keys: Vec<Vec<u8>>,1574 ) -> Result<Vec<PropertyKey>, DispatchError> {1575 keys.into_iter()1576 .map(|key| -> Result<PropertyKey, DispatchError> {1577 key.try_into()1578 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1579 })1580 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1581 }15821583 /// Get properties according to given keys.1584 pub fn filter_collection_properties(1585 collection_id: CollectionId,1586 keys: Option<Vec<PropertyKey>>,1587 ) -> Result<Vec<Property>, DispatchError> {1588 let properties = Self::collection_properties(collection_id);15891590 let properties = keys1591 .map(|keys| {1592 keys.into_iter()1593 .filter_map(|key| {1594 properties.get(&key).map(|value| Property {1595 key,1596 value: value.clone(),1597 })1598 })1599 .collect()1600 })1601 .unwrap_or_else(|| {1602 properties1603 .into_iter()1604 .map(|(key, value)| Property { key, value })1605 .collect()1606 });16071608 Ok(properties)1609 }16101611 /// Get property permissions according to given keys.1612 pub fn filter_property_permissions(1613 collection_id: CollectionId,1614 keys: Option<Vec<PropertyKey>>,1615 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1616 let permissions = Self::property_permissions(collection_id);16171618 let key_permissions = keys1619 .map(|keys| {1620 keys.into_iter()1621 .filter_map(|key| {1622 permissions1623 .get(&key)1624 .map(|permission| PropertyKeyPermission {1625 key,1626 permission: permission.clone(),1627 })1628 })1629 .collect()1630 })1631 .unwrap_or_else(|| {1632 permissions1633 .into_iter()1634 .map(|(key, permission)| PropertyKeyPermission { key, permission })1635 .collect()1636 });16371638 Ok(key_permissions)1639 }16401641 /// Toggle `user` participation in the `collection`'s allow list.1642 /// #### Store read/writes1643 /// 1 writes1644 pub fn toggle_allowlist(1645 collection: &CollectionHandle<T>,1646 sender: &T::CrossAccountId,1647 user: &T::CrossAccountId,1648 allowed: bool,1649 ) -> DispatchResult {1650 collection.check_is_owner_or_admin(sender)?;16511652 // =========16531654 if allowed {1655 <Allowlist<T>>::insert((collection.id, user), true);1656 Self::deposit_event(Event::<T>::AllowListAddressAdded(1657 collection.id,1658 user.clone(),1659 ));1660 } else {1661 <Allowlist<T>>::remove((collection.id, user));1662 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1663 collection.id,1664 user.clone(),1665 ));1666 }16671668 <PalletEvm<T>>::deposit_log(1669 erc::CollectionHelpersEvents::CollectionChanged {1670 collection_id: eth::collection_id_to_address(collection.id),1671 }1672 .to_log(T::ContractAddress::get()),1673 );16741675 Ok(())1676 }16771678 /// Toggle `user` participation in the `collection`'s admin list.1679 /// #### Store read/writes1680 /// 2 reads, 2 writes1681 pub fn toggle_admin(1682 collection: &CollectionHandle<T>,1683 sender: &T::CrossAccountId,1684 user: &T::CrossAccountId,1685 admin: bool,1686 ) -> DispatchResult {1687 collection.check_is_internal()?;1688 collection.check_is_owner(sender)?;16891690 let is_admin = <IsAdmin<T>>::get((collection.id, user));1691 if is_admin == admin {1692 if admin {1693 return Ok(());1694 } else {1695 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1696 }1697 }1698 let amount = <AdminAmount<T>>::get(collection.id);16991700 // =========17011702 if admin {1703 let amount = amount1704 .checked_add(1)1705 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1706 ensure!(1707 amount <= Self::collection_admins_limit(),1708 <Error<T>>::CollectionAdminCountExceeded,1709 );17101711 <AdminAmount<T>>::insert(collection.id, amount);1712 <IsAdmin<T>>::insert((collection.id, user), true);17131714 Self::deposit_event(Event::<T>::CollectionAdminAdded(1715 collection.id,1716 user.clone(),1717 ));1718 } else {1719 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1720 <IsAdmin<T>>::remove((collection.id, user));17211722 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1723 collection.id,1724 user.clone(),1725 ));1726 }17271728 <PalletEvm<T>>::deposit_log(1729 erc::CollectionHelpersEvents::CollectionChanged {1730 collection_id: eth::collection_id_to_address(collection.id),1731 }1732 .to_log(T::ContractAddress::get()),1733 );17341735 Ok(())1736 }17371738 /// Update collection limits.1739 pub fn update_limits(1740 user: &T::CrossAccountId,1741 collection: &mut CollectionHandle<T>,1742 new_limit: CollectionLimits,1743 ) -> DispatchResult {1744 collection.check_is_internal()?;1745 collection.check_is_owner_or_admin(user)?;17461747 collection.limits =1748 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17491750 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1751 <PalletEvm<T>>::deposit_log(1752 erc::CollectionHelpersEvents::CollectionChanged {1753 collection_id: eth::collection_id_to_address(collection.id),1754 }1755 .to_log(T::ContractAddress::get()),1756 );17571758 collection.save()1759 }17601761 /// Merge set fields from `new_limit` to `old_limit`.1762 fn clamp_limits(1763 mode: CollectionMode,1764 old_limit: &CollectionLimits,1765 mut new_limit: CollectionLimits,1766 ) -> Result<CollectionLimits, DispatchError> {1767 let limits = old_limit;1768 limit_default!(old_limit, new_limit,1769 account_token_ownership_limit => ensure!(1770 new_limit <= MAX_TOKEN_OWNERSHIP,1771 <Error<T>>::CollectionLimitBoundsExceeded,1772 ),1773 sponsored_data_size => ensure!(1774 new_limit <= CUSTOM_DATA_LIMIT,1775 <Error<T>>::CollectionLimitBoundsExceeded,1776 ),17771778 sponsored_data_rate_limit => {},1779 token_limit => ensure!(1780 old_limit >= new_limit && new_limit > 0,1781 <Error<T>>::CollectionTokenLimitExceeded1782 ),17831784 sponsor_transfer_timeout(match mode {1785 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1786 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1787 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1788 }) => ensure!(1789 new_limit <= MAX_SPONSOR_TIMEOUT,1790 <Error<T>>::CollectionLimitBoundsExceeded,1791 ),1792 sponsor_approve_timeout => {},1793 owner_can_transfer => ensure!(1794 !limits.owner_can_transfer_instaled() ||1795 old_limit || !new_limit,1796 <Error<T>>::OwnerPermissionsCantBeReverted,1797 ),1798 owner_can_destroy => ensure!(1799 old_limit || !new_limit,1800 <Error<T>>::OwnerPermissionsCantBeReverted,1801 ),1802 transfers_enabled => {},1803 );1804 Ok(new_limit)1805 }18061807 /// Update collection permissions.1808 pub fn update_permissions(1809 user: &T::CrossAccountId,1810 collection: &mut CollectionHandle<T>,1811 new_permission: CollectionPermissions,1812 ) -> DispatchResult {1813 collection.check_is_internal()?;1814 collection.check_is_owner_or_admin(user)?;1815 collection.permissions = Self::clamp_permissions(1816 collection.mode.clone(),1817 &collection.permissions,1818 new_permission,1819 )?;18201821 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1822 <PalletEvm<T>>::deposit_log(1823 erc::CollectionHelpersEvents::CollectionChanged {1824 collection_id: eth::collection_id_to_address(collection.id),1825 }1826 .to_log(T::ContractAddress::get()),1827 );18281829 collection.save()1830 }18311832 /// Merge set fields from `new_permission` to `old_permission`.1833 fn clamp_permissions(1834 _mode: CollectionMode,1835 old_permission: &CollectionPermissions,1836 mut new_permission: CollectionPermissions,1837 ) -> Result<CollectionPermissions, DispatchError> {1838 limit_default_clone!(old_permission, new_permission,1839 access => {},1840 mint_mode => {},1841 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1842 );1843 Ok(new_permission)1844 }18451846 /// Repair possibly broken properties of a collection.1847 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1848 CollectionProperties::<T>::mutate(collection_id, |properties| {1849 properties.recompute_consumed_space();1850 });18511852 Ok(())1853 }1854}18551856/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1857#[macro_export]1858macro_rules! unsupported {1859 ($runtime:path) => {1860 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1861 };1862}18631864/// Return weights for various worst-case operations.1865pub trait CommonWeightInfo<CrossAccountId> {1866 /// Weight of item creation.1867 fn create_item(data: &CreateItemData) -> Weight {1868 Self::create_multiple_items(from_ref(data))1869 }18701871 /// Weight of items creation.1872 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;18731874 /// Weight of items creation.1875 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;18761877 /// The weight of the burning item.1878 fn burn_item() -> Weight;18791880 /// Property setting weight.1881 ///1882 /// * `amount`- The number of properties to set.1883 fn set_collection_properties(amount: u32) -> Weight;18841885 /// Collection property deletion weight.1886 ///1887 /// * `amount`- The number of properties to set.1888 fn delete_collection_properties(amount: u32) -> Weight;18891890 /// Token property setting weight.1891 ///1892 /// * `amount`- The number of properties to set.1893 fn set_token_properties(amount: u32) -> Weight;18941895 /// Token property deletion weight.1896 ///1897 /// * `amount`- The number of properties to delete.1898 fn delete_token_properties(amount: u32) -> Weight;18991900 /// Token property permissions set weight.1901 ///1902 /// * `amount`- The number of property permissions to set.1903 fn set_token_property_permissions(amount: u32) -> Weight;19041905 /// Transfer price of the token or its parts.1906 fn transfer() -> Weight;19071908 /// The price of setting the permission of the operation from another user.1909 fn approve() -> Weight;19101911 /// The price of setting the permission of the operation from another user for eth mirror.1912 fn approve_from() -> Weight;19131914 /// Transfer price from another user.1915 fn transfer_from() -> Weight;19161917 /// The price of burning a token from another user.1918 fn burn_from() -> Weight;19191920 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1921 /// whole users's balance.1922 ///1923 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1924 fn burn_recursively_self_raw() -> Weight;19251926 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1927 ///1928 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1929 fn burn_recursively_breadth_raw(amount: u32) -> Weight;19301931 /// The price of recursive burning a token.1932 ///1933 /// `max_selfs` - The maximum burning weight of the token itself.1934 /// `max_breadth` - The maximum number of nested tokens to burn.1935 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1936 Self::burn_recursively_self_raw()1937 .saturating_mul(max_selfs.max(1) as u64)1938 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1939 }19401941 /// The price of retrieving token owner1942 fn token_owner() -> Weight;19431944 /// The price of setting approval for all1945 fn set_allowance_for_all() -> Weight;19461947 /// The price of repairing an item.1948 fn force_repair_item() -> Weight;1949}19501951/// Weight info extension trait for refungible pallet.1952pub trait RefungibleExtensionsWeightInfo {1953 /// Weight of token repartition.1954 fn repartition() -> Weight;1955}19561957/// Common collection operations.1958///1959/// It wraps methods in Fungible, Nonfungible and Refungible pallets1960/// and adds weight info.1961pub trait CommonCollectionOperations<T: Config> {1962 /// Create token.1963 ///1964 /// * `sender` - The user who mint the token and pays for the transaction.1965 /// * `to` - The user who will own the token.1966 /// * `data` - Token data.1967 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1968 fn create_item(1969 &self,1970 sender: T::CrossAccountId,1971 to: T::CrossAccountId,1972 data: CreateItemData,1973 nesting_budget: &dyn Budget,1974 ) -> DispatchResultWithPostInfo;19751976 /// Create multiple tokens.1977 ///1978 /// * `sender` - The user who mint the token and pays for the transaction.1979 /// * `to` - The user who will own the token.1980 /// * `data` - Token data.1981 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1982 fn create_multiple_items(1983 &self,1984 sender: T::CrossAccountId,1985 to: T::CrossAccountId,1986 data: Vec<CreateItemData>,1987 nesting_budget: &dyn Budget,1988 ) -> DispatchResultWithPostInfo;19891990 /// Create multiple tokens.1991 ///1992 /// * `sender` - The user who mint the token and pays for the transaction.1993 /// * `to` - The user who will own the token.1994 /// * `data` - Token data.1995 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1996 fn create_multiple_items_ex(1997 &self,1998 sender: T::CrossAccountId,1999 data: CreateItemExData<T::CrossAccountId>,2000 nesting_budget: &dyn Budget,2001 ) -> DispatchResultWithPostInfo;20022003 /// Burn token.2004 ///2005 /// * `sender` - The user who owns the token.2006 /// * `token` - Token id that will burned.2007 /// * `amount` - The number of parts of the token that will be burned.2008 fn burn_item(2009 &self,2010 sender: T::CrossAccountId,2011 token: TokenId,2012 amount: u128,2013 ) -> DispatchResultWithPostInfo;20142015 /// Burn token and all nested tokens recursievly.2016 ///2017 /// * `sender` - The user who owns the token.2018 /// * `token` - Token id that will burned.2019 /// * `self_budget` - The budget that can be spent on burning tokens.2020 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2021 fn burn_item_recursively(2022 &self,2023 sender: T::CrossAccountId,2024 token: TokenId,2025 self_budget: &dyn Budget,2026 breadth_budget: &dyn Budget,2027 ) -> DispatchResultWithPostInfo;20282029 /// Set collection properties.2030 ///2031 /// * `sender` - Must be either the owner of the collection or its admin.2032 /// * `properties` - Properties to be set.2033 fn set_collection_properties(2034 &self,2035 sender: T::CrossAccountId,2036 properties: Vec<Property>,2037 ) -> DispatchResultWithPostInfo;20382039 /// Delete collection properties.2040 ///2041 /// * `sender` - Must be either the owner of the collection or its admin.2042 /// * `properties` - The properties to be removed.2043 fn delete_collection_properties(2044 &self,2045 sender: &T::CrossAccountId,2046 property_keys: Vec<PropertyKey>,2047 ) -> DispatchResultWithPostInfo;20482049 /// Set token properties.2050 ///2051 /// The appropriate [`PropertyPermission`] for the token property2052 /// must be set with [`Self::set_token_property_permissions`].2053 ///2054 /// * `sender` - Must be either the owner of the token or its admin.2055 /// * `token_id` - The token for which the properties are being set.2056 /// * `properties` - Properties to be set.2057 /// * `budget` - Budget for setting properties.2058 fn set_token_properties(2059 &self,2060 sender: T::CrossAccountId,2061 token_id: TokenId,2062 properties: Vec<Property>,2063 budget: &dyn Budget,2064 ) -> DispatchResultWithPostInfo;20652066 /// Remove token properties.2067 ///2068 /// The appropriate [`PropertyPermission`] for the token property2069 /// must be set with [`Self::set_token_property_permissions`].2070 ///2071 /// * `sender` - Must be either the owner of the token or its admin.2072 /// * `token_id` - The token for which the properties are being remove.2073 /// * `property_keys` - Keys to remove corresponding properties.2074 /// * `budget` - Budget for removing properties.2075 fn delete_token_properties(2076 &self,2077 sender: T::CrossAccountId,2078 token_id: TokenId,2079 property_keys: Vec<PropertyKey>,2080 budget: &dyn Budget,2081 ) -> DispatchResultWithPostInfo;20822083 /// Set token property permissions.2084 ///2085 /// * `sender` - Must be either the owner of the token or its admin.2086 /// * `token_id` - The token for which the properties are being set.2087 /// * `property_permissions` - Property permissions to be set.2088 /// * `budget` - Budget for setting properties.2089 fn set_token_property_permissions(2090 &self,2091 sender: &T::CrossAccountId,2092 property_permissions: Vec<PropertyKeyPermission>,2093 ) -> DispatchResultWithPostInfo;20942095 /// Transfer amount of token pieces.2096 ///2097 /// * `sender` - Donor user.2098 /// * `to` - Recepient user.2099 /// * `token` - The token of which parts are being sent.2100 /// * `amount` - The number of parts of the token that will be transferred.2101 /// * `budget` - The maximum budget that can be spent on the transfer.2102 fn transfer(2103 &self,2104 sender: T::CrossAccountId,2105 to: T::CrossAccountId,2106 token: TokenId,2107 amount: u128,2108 budget: &dyn Budget,2109 ) -> DispatchResultWithPostInfo;21102111 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2112 ///2113 /// * `sender` - The user who grants access to the token.2114 /// * `spender` - The user to whom the rights are granted.2115 /// * `token` - The token to which access is granted.2116 /// * `amount` - The amount of pieces that another user can dispose of.2117 fn approve(2118 &self,2119 sender: T::CrossAccountId,2120 spender: T::CrossAccountId,2121 token: TokenId,2122 amount: u128,2123 ) -> DispatchResultWithPostInfo;21242125 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2126 ///2127 /// * `sender` - The user who grants access to the token.2128 /// * `from` - Spender's eth mirror.2129 /// * `to` - The user to whom the rights are granted.2130 /// * `token` - The token to which access is granted.2131 /// * `amount` - The amount of pieces that another user can dispose of.2132 fn approve_from(2133 &self,2134 sender: T::CrossAccountId,2135 from: T::CrossAccountId,2136 to: T::CrossAccountId,2137 token: TokenId,2138 amount: u128,2139 ) -> DispatchResultWithPostInfo;21402141 /// Send parts of a token owned by another user.2142 ///2143 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2144 ///2145 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2146 /// * `from` - The user who owns the token.2147 /// * `to` - Recepient user.2148 /// * `token` - The token of which parts are being sent.2149 /// * `amount` - The number of parts of the token that will be transferred.2150 /// * `budget` - The maximum budget that can be spent on the transfer.2151 fn transfer_from(2152 &self,2153 sender: T::CrossAccountId,2154 from: T::CrossAccountId,2155 to: T::CrossAccountId,2156 token: TokenId,2157 amount: u128,2158 budget: &dyn Budget,2159 ) -> DispatchResultWithPostInfo;21602161 /// Burn parts of a token owned by another user.2162 ///2163 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2164 ///2165 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2166 /// * `from` - The user who owns the token.2167 /// * `token` - The token of which parts are being sent.2168 /// * `amount` - The number of parts of the token that will be transferred.2169 /// * `budget` - The maximum budget that can be spent on the burn.2170 fn burn_from(2171 &self,2172 sender: T::CrossAccountId,2173 from: T::CrossAccountId,2174 token: TokenId,2175 amount: u128,2176 budget: &dyn Budget,2177 ) -> DispatchResultWithPostInfo;21782179 /// Check permission to nest token.2180 ///2181 /// * `sender` - The user who initiated the check.2182 /// * `from` - The token that is checked for embedding.2183 /// * `under` - Token under which to check.2184 /// * `budget` - The maximum budget that can be spent on the check.2185 fn check_nesting(2186 &self,2187 sender: T::CrossAccountId,2188 from: (CollectionId, TokenId),2189 under: TokenId,2190 budget: &dyn Budget,2191 ) -> DispatchResult;21922193 /// Nest one token into another.2194 ///2195 /// * `under` - Token holder.2196 /// * `to_nest` - Nested token.2197 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21982199 /// Unnest token.2200 ///2201 /// * `under` - Token holder.2202 /// * `to_nest` - Token to unnest.2203 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22042205 /// Get all user tokens.2206 ///2207 /// * `account` - Account for which you need to get tokens.2208 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22092210 /// Get all the tokens in the collection.2211 fn collection_tokens(&self) -> Vec<TokenId>;22122213 /// Check if the token exists.2214 ///2215 /// * `token` - Id token to check.2216 fn token_exists(&self, token: TokenId) -> bool;22172218 /// Get the id of the last minted token.2219 fn last_token_id(&self) -> TokenId;22202221 /// Get the owner of the token.2222 ///2223 /// * `token` - The token for which you need to find out the owner.2224 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22252226 /// Returns 10 tokens owners in no particular order.2227 ///2228 /// * `token` - The token for which you need to find out the owners.2229 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22302231 /// Get the value of the token property by key.2232 ///2233 /// * `token` - Token with the property to get.2234 /// * `key` - Property name.2235 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22362237 /// Get a set of token properties by key vector.2238 ///2239 /// * `token` - Token with the property to get.2240 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2241 /// then all properties are returned.2242 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22432244 /// Amount of unique collection tokens2245 fn total_supply(&self) -> u32;22462247 /// Amount of different tokens account has.2248 ///2249 /// * `account` - The account for which need to get the balance.2250 fn account_balance(&self, account: T::CrossAccountId) -> u32;22512252 /// Amount of specific token account have.2253 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;22542255 /// Amount of token pieces2256 fn total_pieces(&self, token: TokenId) -> Option<u128>;22572258 /// Get the number of parts of the token that a trusted user can manage.2259 ///2260 /// * `sender` - Trusted user.2261 /// * `spender` - Owner of the token.2262 /// * `token` - The token for which to get the value.2263 fn allowance(2264 &self,2265 sender: T::CrossAccountId,2266 spender: T::CrossAccountId,2267 token: TokenId,2268 ) -> u128;22692270 /// Get extension for RFT collection.2271 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;22722273 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2274 /// * `owner` - Token owner2275 /// * `operator` - Operator2276 /// * `approve` - Should operator status be granted or revoked?2277 fn set_allowance_for_all(2278 &self,2279 owner: T::CrossAccountId,2280 operator: T::CrossAccountId,2281 approve: bool,2282 ) -> DispatchResultWithPostInfo;22832284 /// Tells whether the given `owner` approves the `operator`.2285 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22862287 /// Repairs a possibly broken item.2288 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2289}22902291/// Extension for RFT collection.2292pub trait RefungibleExtensions<T>2293where2294 T: Config,2295{2296 /// Change the number of parts of the token.2297 ///2298 /// When the value changes down, this function is equivalent to burning parts of the token.2299 ///2300 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2301 /// * `token` - The token for which you want to change the number of parts.2302 /// * `amount` - The new value of the parts of the token.2303 fn repartition(2304 &self,2305 sender: &T::CrossAccountId,2306 token: TokenId,2307 amount: u128,2308 ) -> DispatchResultWithPostInfo;2309}23102311/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2312///2313/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2314pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2315 let post_info = PostDispatchInfo {2316 actual_weight: Some(weight),2317 pays_fee: Pays::Yes,2318 };2319 match res {2320 Ok(()) => Ok(post_info),2321 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2322 }2323}23242325impl<T: Config> From<PropertiesError> for Error<T> {2326 fn from(error: PropertiesError) -> Self {2327 match error {2328 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2329 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2330 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2331 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2332 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2333 }2334 }2335}pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -1,751 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-/// @dev common stubs holder
-contract Dummy {
- uint8 dummy;
- string stub_error = "this contract is implemented in native";
-}
-
-contract ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID) external view returns (bool) {
- require(false, stub_error);
- interfaceID;
- return true;
- }
-}
-
-/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
-contract Collection is Dummy, ERC165 {
- // /// Set collection property.
- // ///
- // /// @param key Property key.
- // /// @param value Propery value.
- // /// @dev EVM selector for this function is: 0x2f073f66,
- // /// or in textual repr: setCollectionProperty(string,bytes)
- // function setCollectionProperty(string memory key, bytes memory value) public {
- // require(false, stub_error);
- // key;
- // value;
- // dummy = 0;
- // }
-
- /// Set collection properties.
- ///
- /// @param properties Vector of properties key/value pair.
- /// @dev EVM selector for this function is: 0x50b26b2a,
- /// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Property[] memory properties) public {
- require(false, stub_error);
- properties;
- dummy = 0;
- }
-
- // /// Delete collection property.
- // ///
- // /// @param key Property key.
- // /// @dev EVM selector for this function is: 0x7b7debce,
- // /// or in textual repr: deleteCollectionProperty(string)
- // function deleteCollectionProperty(string memory key) public {
- // require(false, stub_error);
- // key;
- // dummy = 0;
- // }
-
- /// Delete collection properties.
- ///
- /// @param keys Properties keys.
- /// @dev EVM selector for this function is: 0xee206ee3,
- /// or in textual repr: deleteCollectionProperties(string[])
- function deleteCollectionProperties(string[] memory keys) public {
- require(false, stub_error);
- keys;
- dummy = 0;
- }
-
- /// Get collection property.
- ///
- /// @dev Throws error if key not found.
- ///
- /// @param key Property key.
- /// @return bytes The property corresponding to the key.
- /// @dev EVM selector for this function is: 0xcf24fd6d,
- /// or in textual repr: collectionProperty(string)
- function collectionProperty(string memory key) public view returns (bytes memory) {
- require(false, stub_error);
- key;
- dummy;
- return hex"";
- }
-
- /// Get collection properties.
- ///
- /// @param keys Properties keys. Empty keys for all propertyes.
- /// @return Vector of properties key/value pairs.
- /// @dev EVM selector for this function is: 0x285fb8e6,
- /// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) public view returns (Property[] memory) {
- require(false, stub_error);
- keys;
- dummy;
- return new Property[](0);
- }
-
- // /// Set the sponsor of the collection.
- // ///
- // /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- // ///
- // /// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
- // /// @dev EVM selector for this function is: 0x7623402e,
- // /// or in textual repr: setCollectionSponsor(address)
- // function setCollectionSponsor(address sponsor) public {
- // require(false, stub_error);
- // sponsor;
- // dummy = 0;
- // }
-
- /// Set the sponsor of the collection.
- ///
- /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- ///
- /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
- /// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(CrossAddress memory sponsor) public {
- require(false, stub_error);
- sponsor;
- dummy = 0;
- }
-
- /// Whether there is a pending sponsor.
- /// @dev EVM selector for this function is: 0x058ac185,
- /// or in textual repr: hasCollectionPendingSponsor()
- function hasCollectionPendingSponsor() public view returns (bool) {
- require(false, stub_error);
- dummy;
- return false;
- }
-
- /// Collection sponsorship confirmation.
- ///
- /// @dev After setting the sponsor for the collection, it must be confirmed with this function.
- /// @dev EVM selector for this function is: 0x3c50e97a,
- /// or in textual repr: confirmCollectionSponsorship()
- function confirmCollectionSponsorship() public {
- require(false, stub_error);
- dummy = 0;
- }
-
- /// Remove collection sponsor.
- /// @dev EVM selector for this function is: 0x6e0326a3,
- /// or in textual repr: removeCollectionSponsor()
- function removeCollectionSponsor() public {
- require(false, stub_error);
- dummy = 0;
- }
-
- /// Get current sponsor.
- ///
- /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
- /// @dev EVM selector for this function is: 0x6ec0a9f1,
- /// or in textual repr: collectionSponsor()
- function collectionSponsor() public view returns (CrossAddress memory) {
- require(false, stub_error);
- dummy;
- return CrossAddress(0x0000000000000000000000000000000000000000, 0);
- }
-
- /// Get current collection limits.
- ///
- /// @return Array of collection limits
- /// @dev EVM selector for this function is: 0xf63bc572,
- /// or in textual repr: collectionLimits()
- function collectionLimits() public view returns (CollectionLimit[] memory) {
- require(false, stub_error);
- dummy;
- return new CollectionLimit[](0);
- }
-
- /// Set limits for the collection.
- /// @dev Throws error if limit not found.
- /// @param limit Some limit.
- /// @dev EVM selector for this function is: 0x2316ee74,
- /// or in textual repr: setCollectionLimit((uint8,(bool,uint256)))
- function setCollectionLimit(CollectionLimit memory limit) public {
- require(false, stub_error);
- limit;
- dummy = 0;
- }
-
- /// Get contract address.
- /// @dev EVM selector for this function is: 0xf6b4dfb4,
- /// or in textual repr: contractAddress()
- function contractAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-
- /// Add collection admin.
- /// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
- /// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(CrossAddress memory newAdmin) public {
- require(false, stub_error);
- newAdmin;
- dummy = 0;
- }
-
- /// Remove collection admin.
- /// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
- /// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(CrossAddress memory admin) public {
- require(false, stub_error);
- admin;
- dummy = 0;
- }
-
- // /// Add collection admin.
- // /// @param newAdmin Address of the added administrator.
- // /// @dev EVM selector for this function is: 0x92e462c7,
- // /// or in textual repr: addCollectionAdmin(address)
- // function addCollectionAdmin(address newAdmin) public {
- // require(false, stub_error);
- // newAdmin;
- // dummy = 0;
- // }
-
- // /// Remove collection admin.
- // ///
- // /// @param admin Address of the removed administrator.
- // /// @dev EVM selector for this function is: 0xfafd7b42,
- // /// or in textual repr: removeCollectionAdmin(address)
- // function removeCollectionAdmin(address admin) public {
- // require(false, stub_error);
- // admin;
- // dummy = 0;
- // }
-
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) public {
- require(false, stub_error);
- enable;
- dummy = 0;
- }
-
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) public {
- require(false, stub_error);
- enable;
- collections;
- dummy = 0;
- }
-
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() public view returns (CollectionNesting memory) {
- require(false, stub_error);
- dummy;
- return CollectionNesting(false, new uint256[](0));
- }
-
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() public view returns (CollectionNestingPermission[] memory) {
- require(false, stub_error);
- dummy;
- return new CollectionNestingPermission[](0);
- }
-
- /// Set the collection access method.
- /// @param mode Access mode
- /// @dev EVM selector for this function is: 0x41835d4c,
- /// or in textual repr: setCollectionAccess(uint8)
- function setCollectionAccess(AccessMode mode) public {
- require(false, stub_error);
- mode;
- dummy = 0;
- }
-
- /// Checks that user allowed to operate with collection.
- ///
- /// @param user User address to check.
- /// @dev EVM selector for this function is: 0x91b6df49,
- /// or in textual repr: allowlistedCross((address,uint256))
- function allowlistedCross(CrossAddress memory user) public view returns (bool) {
- require(false, stub_error);
- user;
- dummy;
- return false;
- }
-
- // /// Add the user to the allowed list.
- // ///
- // /// @param user Address of a trusted user.
- // /// @dev EVM selector for this function is: 0x67844fe6,
- // /// or in textual repr: addToCollectionAllowList(address)
- // function addToCollectionAllowList(address user) public {
- // require(false, stub_error);
- // user;
- // dummy = 0;
- // }
-
- /// Add user to allowed list.
- ///
- /// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
- /// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(CrossAddress memory user) public {
- require(false, stub_error);
- user;
- dummy = 0;
- }
-
- // /// Remove the user from the allowed list.
- // ///
- // /// @param user Address of a removed user.
- // /// @dev EVM selector for this function is: 0x85c51acb,
- // /// or in textual repr: removeFromCollectionAllowList(address)
- // function removeFromCollectionAllowList(address user) public {
- // require(false, stub_error);
- // user;
- // dummy = 0;
- // }
-
- /// Remove user from allowed list.
- ///
- /// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
- /// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(CrossAddress memory user) public {
- require(false, stub_error);
- user;
- dummy = 0;
- }
-
- /// Switch permission for minting.
- ///
- /// @param mode Enable if "true".
- /// @dev EVM selector for this function is: 0x00018e84,
- /// or in textual repr: setCollectionMintMode(bool)
- function setCollectionMintMode(bool mode) public {
- require(false, stub_error);
- mode;
- dummy = 0;
- }
-
- // /// Check that account is the owner or admin of the collection
- // ///
- // /// @param user account to verify
- // /// @return "true" if account is the owner or admin
- // /// @dev EVM selector for this function is: 0x9811b0c7,
- // /// or in textual repr: isOwnerOrAdmin(address)
- // function isOwnerOrAdmin(address user) public view returns (bool) {
- // require(false, stub_error);
- // user;
- // dummy;
- // return false;
- // }
-
- /// Check that account is the owner or admin of the collection
- ///
- /// @param user User cross account to verify
- /// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
- /// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(CrossAddress memory user) public view returns (bool) {
- require(false, stub_error);
- user;
- dummy;
- return false;
- }
-
- /// Returns collection type
- ///
- /// @return `Fungible` or `NFT` or `ReFungible`
- /// @dev EVM selector for this function is: 0xd34b55b8,
- /// or in textual repr: uniqueCollectionType()
- function uniqueCollectionType() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// Get collection owner.
- ///
- /// @return Tuble with sponsor address and his substrate mirror.
- /// If address is canonical then substrate mirror is zero and vice versa.
- /// @dev EVM selector for this function is: 0xdf727d3b,
- /// or in textual repr: collectionOwner()
- function collectionOwner() public view returns (CrossAddress memory) {
- require(false, stub_error);
- dummy;
- return CrossAddress(0x0000000000000000000000000000000000000000, 0);
- }
-
- // /// Changes collection owner to another account
- // ///
- // /// @dev Owner can be changed only by current owner
- // /// @param newOwner new owner account
- // /// @dev EVM selector for this function is: 0x4f53e226,
- // /// or in textual repr: changeCollectionOwner(address)
- // function changeCollectionOwner(address newOwner) public {
- // require(false, stub_error);
- // newOwner;
- // dummy = 0;
- // }
-
- /// Get collection administrators
- ///
- /// @return Vector of tuples with admins address and his substrate mirror.
- /// If address is canonical then substrate mirror is zero and vice versa.
- /// @dev EVM selector for this function is: 0x5813216b,
- /// or in textual repr: collectionAdmins()
- function collectionAdmins() public view returns (CrossAddress[] memory) {
- require(false, stub_error);
- dummy;
- return new CrossAddress[](0);
- }
-
- /// Changes collection owner to another account
- ///
- /// @dev Owner can be changed only by current owner
- /// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0x6496c497,
- /// or in textual repr: changeCollectionOwnerCross((address,uint256))
- function changeCollectionOwnerCross(CrossAddress memory newOwner) public {
- require(false, stub_error);
- newOwner;
- dummy = 0;
- }
-}
-
-/// Cross account struct
-struct CrossAddress {
- address eth;
- uint256 sub;
-}
-
-/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).
-enum AccessMode {
- /// Access grant for owner and admins. Used as default.
- Normal,
- /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.
- AllowList
-}
-
-/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.
-struct CollectionNestingPermission {
- CollectionPermissionField field;
- bool value;
-}
-
-/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.
-enum CollectionPermissionField {
- /// Owner of token can nest tokens under it.
- TokenOwner,
- /// Admin of token collection can nest tokens under token.
- CollectionAdmin
-}
-
-/// Nested collections.
-struct CollectionNesting {
- bool token_owner;
- uint256[] ids;
-}
-
-/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
-struct CollectionLimit {
- CollectionLimitField field;
- OptionUint256 value;
-}
-
-/// Optional value
-struct OptionUint256 {
- /// Shows the status of accessibility of value
- bool status;
- /// Actual value if `status` is true
- uint256 value;
-}
-
-/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
-enum CollectionLimitField {
- /// How many tokens can a user have on one account.
- AccountTokenOwnership,
- /// How many bytes of data are available for sponsorship.
- SponsoredDataSize,
- /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
- SponsoredDataRateLimit,
- /// How many tokens can be mined into this collection.
- TokenLimit,
- /// Timeouts for transfer sponsoring.
- SponsorTransferTimeout,
- /// Timeout for sponsoring an approval in passed blocks.
- SponsorApproveTimeout,
- /// Whether the collection owner of the collection can send tokens (which belong to other users).
- OwnerCanTransfer,
- /// Can the collection owner burn other people's tokens.
- OwnerCanDestroy,
- /// Is it possible to send tokens from this collection between users.
- TransferEnabled
-}
-
-/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
-struct Property {
- string key;
- bytes value;
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
-contract ERC20UniqueExtensions is Dummy, ERC165 {
- /// @dev Function to check the amount of tokens that an owner allowed to a spender.
- /// @param owner crossAddress The address which owns the funds.
- /// @param spender crossAddress The address which will spend the funds.
- /// @return A uint256 specifying the amount of tokens still available for the spender.
- /// @dev EVM selector for this function is: 0xe0af4bd7,
- /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
- function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
- require(false, stub_error);
- owner;
- spender;
- dummy;
- return 0;
- }
-
- /// @notice A description for the collection.
- /// @dev EVM selector for this function is: 0x7284e416,
- /// or in textual repr: description()
- function description() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @dev EVM selector for this function is: 0x269e6158,
- /// or in textual repr: mintCross((address,uint256),uint256)
- function mintCross(CrossAddress memory to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
- /// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(CrossAddress memory spender, uint256 amount) public returns (bool) {
- require(false, stub_error);
- spender;
- amount;
- dummy = 0;
- return false;
- }
-
- // /// Burn tokens from account
- // /// @dev Function that burns an `amount` of the tokens of a given account,
- // /// deducting from the sender's allowance for said account.
- // /// @param from The account whose tokens will be burnt.
- // /// @param amount The amount that will be burnt.
- // /// @dev EVM selector for this function is: 0x79cc6790,
- // /// or in textual repr: burnFrom(address,uint256)
- // function burnFrom(address from, uint256 amount) public returns (bool) {
- // require(false, stub_error);
- // from;
- // amount;
- // dummy = 0;
- // return false;
- // }
-
- /// Burn tokens from account
- /// @dev Function that burns an `amount` of the tokens of a given account,
- /// deducting from the sender's allowance for said account.
- /// @param from The account whose tokens will be burnt.
- /// @param amount The amount that will be burnt.
- /// @dev EVM selector for this function is: 0xbb2f5a58,
- /// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(CrossAddress memory from, uint256 amount) public returns (bool) {
- require(false, stub_error);
- from;
- amount;
- dummy = 0;
- return false;
- }
-
- /// Mint tokens for multiple accounts.
- /// @param amounts array of pairs of account address and amount
- /// @dev EVM selector for this function is: 0x1acf2d55,
- /// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(AmountForAddress[] memory amounts) public returns (bool) {
- require(false, stub_error);
- amounts;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0x2ada85ff,
- /// or in textual repr: transferCross((address,uint256),uint256)
- function transferCross(CrossAddress memory to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
- function transferFromCross(
- CrossAddress memory from,
- CrossAddress memory to,
- uint256 amount
- ) public returns (bool) {
- require(false, stub_error);
- from;
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() public view returns (address) {
- require(false, stub_error);
- dummy;
- return 0x0000000000000000000000000000000000000000;
- }
-}
-
-struct AmountForAddress {
- address to;
- uint256 amount;
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x40c10f19
-contract ERC20Mintable is Dummy, ERC165 {
- /// Mint tokens for `to` account.
- /// @param to account that will receive minted tokens
- /// @param amount amount of tokens to mint
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-}
-
-/// @dev inlined interface
-contract ERC20Events {
- event Transfer(address indexed from, address indexed to, uint256 value);
- event Approval(address indexed owner, address indexed spender, uint256 value);
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x942e8b22
-contract ERC20 is Dummy, ERC165, ERC20Events {
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- /// @dev EVM selector for this function is: 0x18160ddd,
- /// or in textual repr: totalSupply()
- function totalSupply() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- /// @dev EVM selector for this function is: 0x313ce567,
- /// or in textual repr: decimals()
- function decimals() public view returns (uint8) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- /// @dev EVM selector for this function is: 0x70a08231,
- /// or in textual repr: balanceOf(address)
- function balanceOf(address owner) public view returns (uint256) {
- require(false, stub_error);
- owner;
- dummy;
- return 0;
- }
-
- /// @dev EVM selector for this function is: 0xa9059cbb,
- /// or in textual repr: transfer(address,uint256)
- function transfer(address to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0x23b872dd,
- /// or in textual repr: transferFrom(address,address,uint256)
- function transferFrom(
- address from,
- address to,
- uint256 amount
- ) public returns (bool) {
- require(false, stub_error);
- from;
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0x095ea7b3,
- /// or in textual repr: approve(address,uint256)
- function approve(address spender, uint256 amount) public returns (bool) {
- require(false, stub_error);
- spender;
- amount;
- dummy = 0;
- return false;
- }
-
- /// @dev EVM selector for this function is: 0xdd62ed3e,
- /// or in textual repr: allowance(address,address)
- function allowance(address owner, address spender) public view returns (uint256) {
- require(false, stub_error);
- owner;
- spender;
- dummy;
- return 0;
- }
-}
-
-contract UniqueFungible is Dummy, ERC165, ERC20, ERC20Mintable, ERC20UniqueExtensions, Collection {}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -623,7 +623,6 @@
is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
erc::ERC721TokenEvent::TokenChanged {
- collection_id: collection_id_to_address(collection.id),
token_id: token_id.into(),
}
.to_log(T::ContractAddress::get()),
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -572,7 +572,6 @@
is_token_owner,
|properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
erc::ERC721TokenEvent::TokenChanged {
- collection_id: collection_id_to_address(collection.id),
token_id: token_id.into(),
}
.to_log(T::ContractAddress::get()),
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -1,485 +0,0 @@
-// SPDX-License-Identifier: OTHER
-// This code is automatically generated
-
-pragma solidity >=0.8.0 <0.9.0;
-
-/// @dev common stubs holder
-interface Dummy {
-
-}
-
-interface ERC165 is Dummy {
- function supportsInterface(bytes4 interfaceID) external view returns (bool);
-}
-
-/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0x2a14cfd1
-interface Collection is Dummy, ERC165 {
- // /// Set collection property.
- // ///
- // /// @param key Property key.
- // /// @param value Propery value.
- // /// @dev EVM selector for this function is: 0x2f073f66,
- // /// or in textual repr: setCollectionProperty(string,bytes)
- // function setCollectionProperty(string memory key, bytes memory value) external;
-
- /// Set collection properties.
- ///
- /// @param properties Vector of properties key/value pair.
- /// @dev EVM selector for this function is: 0x50b26b2a,
- /// or in textual repr: setCollectionProperties((string,bytes)[])
- function setCollectionProperties(Property[] memory properties) external;
-
- // /// Delete collection property.
- // ///
- // /// @param key Property key.
- // /// @dev EVM selector for this function is: 0x7b7debce,
- // /// or in textual repr: deleteCollectionProperty(string)
- // function deleteCollectionProperty(string memory key) external;
-
- /// Delete collection properties.
- ///
- /// @param keys Properties keys.
- /// @dev EVM selector for this function is: 0xee206ee3,
- /// or in textual repr: deleteCollectionProperties(string[])
- function deleteCollectionProperties(string[] memory keys) external;
-
- /// Get collection property.
- ///
- /// @dev Throws error if key not found.
- ///
- /// @param key Property key.
- /// @return bytes The property corresponding to the key.
- /// @dev EVM selector for this function is: 0xcf24fd6d,
- /// or in textual repr: collectionProperty(string)
- function collectionProperty(string memory key) external view returns (bytes memory);
-
- /// Get collection properties.
- ///
- /// @param keys Properties keys. Empty keys for all propertyes.
- /// @return Vector of properties key/value pairs.
- /// @dev EVM selector for this function is: 0x285fb8e6,
- /// or in textual repr: collectionProperties(string[])
- function collectionProperties(string[] memory keys) external view returns (Property[] memory);
-
- // /// Set the sponsor of the collection.
- // ///
- // /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- // ///
- // /// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
- // /// @dev EVM selector for this function is: 0x7623402e,
- // /// or in textual repr: setCollectionSponsor(address)
- // function setCollectionSponsor(address sponsor) external;
-
- /// Set the sponsor of the collection.
- ///
- /// @dev In order for sponsorship to work, it must be confirmed on behalf of the sponsor.
- ///
- /// @param sponsor Cross account address of the sponsor from whose account funds will be debited for operations with the contract.
- /// @dev EVM selector for this function is: 0x84a1d5a8,
- /// or in textual repr: setCollectionSponsorCross((address,uint256))
- function setCollectionSponsorCross(CrossAddress memory sponsor) external;
-
- /// Whether there is a pending sponsor.
- /// @dev EVM selector for this function is: 0x058ac185,
- /// or in textual repr: hasCollectionPendingSponsor()
- function hasCollectionPendingSponsor() external view returns (bool);
-
- /// Collection sponsorship confirmation.
- ///
- /// @dev After setting the sponsor for the collection, it must be confirmed with this function.
- /// @dev EVM selector for this function is: 0x3c50e97a,
- /// or in textual repr: confirmCollectionSponsorship()
- function confirmCollectionSponsorship() external;
-
- /// Remove collection sponsor.
- /// @dev EVM selector for this function is: 0x6e0326a3,
- /// or in textual repr: removeCollectionSponsor()
- function removeCollectionSponsor() external;
-
- /// Get current sponsor.
- ///
- /// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
- /// @dev EVM selector for this function is: 0x6ec0a9f1,
- /// or in textual repr: collectionSponsor()
- function collectionSponsor() external view returns (CrossAddress memory);
-
- /// Get current collection limits.
- ///
- /// @return Array of collection limits
- /// @dev EVM selector for this function is: 0xf63bc572,
- /// or in textual repr: collectionLimits()
- function collectionLimits() external view returns (CollectionLimit[] memory);
-
- /// Set limits for the collection.
- /// @dev Throws error if limit not found.
- /// @param limit Some limit.
- /// @dev EVM selector for this function is: 0x2316ee74,
- /// or in textual repr: setCollectionLimit((uint8,(bool,uint256)))
- function setCollectionLimit(CollectionLimit memory limit) external;
-
- /// Get contract address.
- /// @dev EVM selector for this function is: 0xf6b4dfb4,
- /// or in textual repr: contractAddress()
- function contractAddress() external view returns (address);
-
- /// Add collection admin.
- /// @param newAdmin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x859aa7d6,
- /// or in textual repr: addCollectionAdminCross((address,uint256))
- function addCollectionAdminCross(CrossAddress memory newAdmin) external;
-
- /// Remove collection admin.
- /// @param admin Cross account administrator address.
- /// @dev EVM selector for this function is: 0x6c0cd173,
- /// or in textual repr: removeCollectionAdminCross((address,uint256))
- function removeCollectionAdminCross(CrossAddress memory admin) external;
-
- // /// Add collection admin.
- // /// @param newAdmin Address of the added administrator.
- // /// @dev EVM selector for this function is: 0x92e462c7,
- // /// or in textual repr: addCollectionAdmin(address)
- // function addCollectionAdmin(address newAdmin) external;
-
- // /// Remove collection admin.
- // ///
- // /// @param admin Address of the removed administrator.
- // /// @dev EVM selector for this function is: 0xfafd7b42,
- // /// or in textual repr: removeCollectionAdmin(address)
- // function removeCollectionAdmin(address admin) external;
-
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
- /// @dev EVM selector for this function is: 0x112d4586,
- /// or in textual repr: setCollectionNesting(bool)
- function setCollectionNesting(bool enable) external;
-
- /// Toggle accessibility of collection nesting.
- ///
- /// @param enable If "true" degenerates to nesting: {OwnerRestricted: [1, 2, 3]} else to nesting: 'Disabled'
- /// @param collections Addresses of collections that will be available for nesting.
- /// @dev EVM selector for this function is: 0x64872396,
- /// or in textual repr: setCollectionNesting(bool,address[])
- function setCollectionNesting(bool enable, address[] memory collections) external;
-
- /// Returns nesting for a collection
- /// @dev EVM selector for this function is: 0x22d25bfe,
- /// or in textual repr: collectionNestingRestrictedCollectionIds()
- function collectionNestingRestrictedCollectionIds() external view returns (CollectionNesting memory);
-
- /// Returns permissions for a collection
- /// @dev EVM selector for this function is: 0x5b2eaf4b,
- /// or in textual repr: collectionNestingPermissions()
- function collectionNestingPermissions() external view returns (CollectionNestingPermission[] memory);
-
- /// Set the collection access method.
- /// @param mode Access mode
- /// @dev EVM selector for this function is: 0x41835d4c,
- /// or in textual repr: setCollectionAccess(uint8)
- function setCollectionAccess(AccessMode mode) external;
-
- /// Checks that user allowed to operate with collection.
- ///
- /// @param user User address to check.
- /// @dev EVM selector for this function is: 0x91b6df49,
- /// or in textual repr: allowlistedCross((address,uint256))
- function allowlistedCross(CrossAddress memory user) external view returns (bool);
-
- // /// Add the user to the allowed list.
- // ///
- // /// @param user Address of a trusted user.
- // /// @dev EVM selector for this function is: 0x67844fe6,
- // /// or in textual repr: addToCollectionAllowList(address)
- // function addToCollectionAllowList(address user) external;
-
- /// Add user to allowed list.
- ///
- /// @param user User cross account address.
- /// @dev EVM selector for this function is: 0xa0184a3a,
- /// or in textual repr: addToCollectionAllowListCross((address,uint256))
- function addToCollectionAllowListCross(CrossAddress memory user) external;
-
- // /// Remove the user from the allowed list.
- // ///
- // /// @param user Address of a removed user.
- // /// @dev EVM selector for this function is: 0x85c51acb,
- // /// or in textual repr: removeFromCollectionAllowList(address)
- // function removeFromCollectionAllowList(address user) external;
-
- /// Remove user from allowed list.
- ///
- /// @param user User cross account address.
- /// @dev EVM selector for this function is: 0x09ba452a,
- /// or in textual repr: removeFromCollectionAllowListCross((address,uint256))
- function removeFromCollectionAllowListCross(CrossAddress memory user) external;
-
- /// Switch permission for minting.
- ///
- /// @param mode Enable if "true".
- /// @dev EVM selector for this function is: 0x00018e84,
- /// or in textual repr: setCollectionMintMode(bool)
- function setCollectionMintMode(bool mode) external;
-
- // /// Check that account is the owner or admin of the collection
- // ///
- // /// @param user account to verify
- // /// @return "true" if account is the owner or admin
- // /// @dev EVM selector for this function is: 0x9811b0c7,
- // /// or in textual repr: isOwnerOrAdmin(address)
- // function isOwnerOrAdmin(address user) external view returns (bool);
-
- /// Check that account is the owner or admin of the collection
- ///
- /// @param user User cross account to verify
- /// @return "true" if account is the owner or admin
- /// @dev EVM selector for this function is: 0x3e75a905,
- /// or in textual repr: isOwnerOrAdminCross((address,uint256))
- function isOwnerOrAdminCross(CrossAddress memory user) external view returns (bool);
-
- /// Returns collection type
- ///
- /// @return `Fungible` or `NFT` or `ReFungible`
- /// @dev EVM selector for this function is: 0xd34b55b8,
- /// or in textual repr: uniqueCollectionType()
- function uniqueCollectionType() external view returns (string memory);
-
- /// Get collection owner.
- ///
- /// @return Tuble with sponsor address and his substrate mirror.
- /// If address is canonical then substrate mirror is zero and vice versa.
- /// @dev EVM selector for this function is: 0xdf727d3b,
- /// or in textual repr: collectionOwner()
- function collectionOwner() external view returns (CrossAddress memory);
-
- // /// Changes collection owner to another account
- // ///
- // /// @dev Owner can be changed only by current owner
- // /// @param newOwner new owner account
- // /// @dev EVM selector for this function is: 0x4f53e226,
- // /// or in textual repr: changeCollectionOwner(address)
- // function changeCollectionOwner(address newOwner) external;
-
- /// Get collection administrators
- ///
- /// @return Vector of tuples with admins address and his substrate mirror.
- /// If address is canonical then substrate mirror is zero and vice versa.
- /// @dev EVM selector for this function is: 0x5813216b,
- /// or in textual repr: collectionAdmins()
- function collectionAdmins() external view returns (CrossAddress[] memory);
-
- /// Changes collection owner to another account
- ///
- /// @dev Owner can be changed only by current owner
- /// @param newOwner new owner cross account
- /// @dev EVM selector for this function is: 0x6496c497,
- /// or in textual repr: changeCollectionOwnerCross((address,uint256))
- function changeCollectionOwnerCross(CrossAddress memory newOwner) external;
-}
-
-/// Cross account struct
-struct CrossAddress {
- address eth;
- uint256 sub;
-}
-
-/// Ethereum representation of `AccessMode` (see [`up_data_structs::AccessMode`]).
-enum AccessMode {
- /// Access grant for owner and admins. Used as default.
- Normal,
- /// Like a [`Normal`](AccessMode::Normal) but also users in allow list.
- AllowList
-}
-
-/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) field.
-struct CollectionNestingPermission {
- CollectionPermissionField field;
- bool value;
-}
-
-/// Ethereum representation of `NestingPermissions` (see [`up_data_structs::NestingPermissions`]) fields as an enumeration.
-enum CollectionPermissionField {
- /// Owner of token can nest tokens under it.
- TokenOwner,
- /// Admin of token collection can nest tokens under token.
- CollectionAdmin
-}
-
-/// Nested collections.
-struct CollectionNesting {
- bool token_owner;
- uint256[] ids;
-}
-
-/// [`CollectionLimits`](up_data_structs::CollectionLimits) field representation for EVM.
-struct CollectionLimit {
- CollectionLimitField field;
- OptionUint256 value;
-}
-
-/// Optional value
-struct OptionUint256 {
- /// Shows the status of accessibility of value
- bool status;
- /// Actual value if `status` is true
- uint256 value;
-}
-
-/// [`CollectionLimits`](up_data_structs::CollectionLimits) fields representation for EVM.
-enum CollectionLimitField {
- /// How many tokens can a user have on one account.
- AccountTokenOwnership,
- /// How many bytes of data are available for sponsorship.
- SponsoredDataSize,
- /// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]
- SponsoredDataRateLimit,
- /// How many tokens can be mined into this collection.
- TokenLimit,
- /// Timeouts for transfer sponsoring.
- SponsorTransferTimeout,
- /// Timeout for sponsoring an approval in passed blocks.
- SponsorApproveTimeout,
- /// Whether the collection owner of the collection can send tokens (which belong to other users).
- OwnerCanTransfer,
- /// Can the collection owner burn other people's tokens.
- OwnerCanDestroy,
- /// Is it possible to send tokens from this collection between users.
- TransferEnabled
-}
-
-/// Ethereum representation of collection [`PropertyKey`](up_data_structs::PropertyKey) and [`PropertyValue`](up_data_structs::PropertyValue).
-struct Property {
- string key;
- bytes value;
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
-interface ERC20UniqueExtensions is Dummy, ERC165 {
- /// @dev Function to check the amount of tokens that an owner allowed to a spender.
- /// @param owner crossAddress The address which owns the funds.
- /// @param spender crossAddress The address which will spend the funds.
- /// @return A uint256 specifying the amount of tokens still available for the spender.
- /// @dev EVM selector for this function is: 0xe0af4bd7,
- /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
- function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
-
- /// @notice A description for the collection.
- /// @dev EVM selector for this function is: 0x7284e416,
- /// or in textual repr: description()
- function description() external view returns (string memory);
-
- /// @dev EVM selector for this function is: 0x269e6158,
- /// or in textual repr: mintCross((address,uint256),uint256)
- function mintCross(CrossAddress memory to, uint256 amount) external returns (bool);
-
- /// @dev EVM selector for this function is: 0x0ecd0ab0,
- /// or in textual repr: approveCross((address,uint256),uint256)
- function approveCross(CrossAddress memory spender, uint256 amount) external returns (bool);
-
- // /// Burn tokens from account
- // /// @dev Function that burns an `amount` of the tokens of a given account,
- // /// deducting from the sender's allowance for said account.
- // /// @param from The account whose tokens will be burnt.
- // /// @param amount The amount that will be burnt.
- // /// @dev EVM selector for this function is: 0x79cc6790,
- // /// or in textual repr: burnFrom(address,uint256)
- // function burnFrom(address from, uint256 amount) external returns (bool);
-
- /// Burn tokens from account
- /// @dev Function that burns an `amount` of the tokens of a given account,
- /// deducting from the sender's allowance for said account.
- /// @param from The account whose tokens will be burnt.
- /// @param amount The amount that will be burnt.
- /// @dev EVM selector for this function is: 0xbb2f5a58,
- /// or in textual repr: burnFromCross((address,uint256),uint256)
- function burnFromCross(CrossAddress memory from, uint256 amount) external returns (bool);
-
- /// Mint tokens for multiple accounts.
- /// @param amounts array of pairs of account address and amount
- /// @dev EVM selector for this function is: 0x1acf2d55,
- /// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(AmountForAddress[] memory amounts) external returns (bool);
-
- /// @dev EVM selector for this function is: 0x2ada85ff,
- /// or in textual repr: transferCross((address,uint256),uint256)
- function transferCross(CrossAddress memory to, uint256 amount) external returns (bool);
-
- /// @dev EVM selector for this function is: 0xd5cf430b,
- /// or in textual repr: transferFromCross((address,uint256),(address,uint256),uint256)
- function transferFromCross(
- CrossAddress memory from,
- CrossAddress memory to,
- uint256 amount
- ) external returns (bool);
-
- /// @notice Returns collection helper contract address
- /// @dev EVM selector for this function is: 0x1896cce6,
- /// or in textual repr: collectionHelperAddress()
- function collectionHelperAddress() external view returns (address);
-}
-
-struct AmountForAddress {
- address to;
- uint256 amount;
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x40c10f19
-interface ERC20Mintable is Dummy, ERC165 {
- /// Mint tokens for `to` account.
- /// @param to account that will receive minted tokens
- /// @param amount amount of tokens to mint
- /// @dev EVM selector for this function is: 0x40c10f19,
- /// or in textual repr: mint(address,uint256)
- function mint(address to, uint256 amount) external returns (bool);
-}
-
-/// @dev inlined interface
-interface ERC20Events {
- event Transfer(address indexed from, address indexed to, uint256 value);
- event Approval(address indexed owner, address indexed spender, uint256 value);
-}
-
-/// @dev the ERC-165 identifier for this interface is 0x942e8b22
-interface ERC20 is Dummy, ERC165, ERC20Events {
- /// @dev EVM selector for this function is: 0x06fdde03,
- /// or in textual repr: name()
- function name() external view returns (string memory);
-
- /// @dev EVM selector for this function is: 0x95d89b41,
- /// or in textual repr: symbol()
- function symbol() external view returns (string memory);
-
- /// @dev EVM selector for this function is: 0x18160ddd,
- /// or in textual repr: totalSupply()
- function totalSupply() external view returns (uint256);
-
- /// @dev EVM selector for this function is: 0x313ce567,
- /// or in textual repr: decimals()
- function decimals() external view returns (uint8);
-
- /// @dev EVM selector for this function is: 0x70a08231,
- /// or in textual repr: balanceOf(address)
- function balanceOf(address owner) external view returns (uint256);
-
- /// @dev EVM selector for this function is: 0xa9059cbb,
- /// or in textual repr: transfer(address,uint256)
- function transfer(address to, uint256 amount) external returns (bool);
-
- /// @dev EVM selector for this function is: 0x23b872dd,
- /// or in textual repr: transferFrom(address,address,uint256)
- function transferFrom(
- address from,
- address to,
- uint256 amount
- ) external returns (bool);
-
- /// @dev EVM selector for this function is: 0x095ea7b3,
- /// or in textual repr: approve(address,uint256)
- function approve(address spender, uint256 amount) external returns (bool);
-
- /// @dev EVM selector for this function is: 0xdd62ed3e,
- /// or in textual repr: allowance(address,address)
- function allowance(address owner, address spender) external view returns (uint256);
-}
-
-interface UniqueFungible is Dummy, ERC165, ERC20, ERC20Mintable, ERC20UniqueExtensions, Collection {}