difftreelog
feat add ApproveFrom eth mirror
in: master
26 files changed
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118use up_pov_estimate_rpc::PovInfo;119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135///136/// CollectionHandle is used as a generic wrapper for collections of all types.137/// It allows to perform common operations and queries on any collection type,138/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].139#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]140pub struct CollectionHandle<T: Config> {141 /// Collection id142 pub id: CollectionId,143 collection: Collection<T::AccountId>,144 /// Substrate recorder for counting consumed gas145 pub recorder: SubstrateRecorder<T>,146}147148impl<T: Config> WithRecorder<T> for CollectionHandle<T> {149 fn recorder(&self) -> &SubstrateRecorder<T> {150 &self.recorder151 }152 fn into_recorder(self) -> SubstrateRecorder<T> {153 self.recorder154 }155}156157impl<T: Config> CollectionHandle<T> {158 /// Same as [CollectionHandle::new] but with an explicit gas limit.159 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {160 <CollectionById<T>>::get(id).map(|collection| Self {161 id,162 collection,163 recorder: SubstrateRecorder::new(gas_limit),164 })165 }166167 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].168 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {169 <CollectionById<T>>::get(id).map(|collection| Self {170 id,171 collection,172 recorder,173 })174 }175176 /// Retrives collection data from storage and creates collection handle with default parameters.177 /// If collection not found return `None`178 pub fn new(id: CollectionId) -> Option<Self> {179 Self::new_with_gas_limit(id, u64::MAX)180 }181182 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.183 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {184 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)185 }186187 /// Consume gas for reading.188 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 <T as frame_system::Config>::DbWeight::get()192 .read193 .saturating_mul(reads),194 )))195 }196197 /// Consume gas for writing.198 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199 self.recorder200 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(201 <T as frame_system::Config>::DbWeight::get()202 .write203 .saturating_mul(writes),204 )))205 }206207 /// Consume gas for reading and writing.208 pub fn consume_store_reads_and_writes(209 &self,210 reads: u64,211 writes: u64,212 ) -> evm_coder::execution::Result<()> {213 let weight = <T as frame_system::Config>::DbWeight::get();214 let reads = weight.read.saturating_mul(reads);215 let writes = weight.read.saturating_mul(writes);216 self.recorder217 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(218 reads.saturating_add(writes),219 )))220 }221222 /// Save collection to storage.223 pub fn save(&self) -> DispatchResult {224 <CollectionById<T>>::insert(self.id, &self.collection);225 Ok(())226 }227228 /// Set collection sponsor.229 ///230 /// Unique collections allows sponsoring for certain actions.231 /// This method allows you to set the sponsor of the collection.232 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].233 pub fn set_sponsor(234 &mut self,235 sender: &T::CrossAccountId,236 sponsor: T::AccountId,237 ) -> DispatchResult {238 self.check_is_internal()?;239 self.check_is_owner_or_admin(sender)?;240241 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());242243 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));244 <PalletEvm<T>>::deposit_log(245 erc::CollectionHelpersEvents::CollectionChanged {246 collection_id: eth::collection_id_to_address(self.id),247 }248 .to_log(T::ContractAddress::get()),249 );250251 self.save()252 }253254 /// Force set `sponsor`.255 ///256 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation257 /// from the `sponsor` is not required.258 ///259 /// # Arguments260 ///261 /// * `sender`: Caller's account.262 /// * `sponsor`: ID of the account of the sponsor-to-be.263 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {264 self.check_is_internal()?;265266 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());267268 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));269 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));270 <PalletEvm<T>>::deposit_log(271 erc::CollectionHelpersEvents::CollectionChanged {272 collection_id: eth::collection_id_to_address(self.id),273 }274 .to_log(T::ContractAddress::get()),275 );276277 self.save()278 }279280 /// Confirm sponsorship281 ///282 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.283 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].284 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {285 self.check_is_internal()?;286 ensure!(287 self.collection.sponsorship.pending_sponsor() == Some(sender),288 Error::<T>::ConfirmSponsorshipFail289 );290291 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());292293 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));294 <PalletEvm<T>>::deposit_log(295 erc::CollectionHelpersEvents::CollectionChanged {296 collection_id: eth::collection_id_to_address(self.id),297 }298 .to_log(T::ContractAddress::get()),299 );300301 self.save()302 }303304 /// Remove collection sponsor.305 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {306 self.check_is_internal()?;307 self.check_is_owner_or_admin(sender)?;308309 self.collection.sponsorship = SponsorshipState::Disabled;310311 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));312 <PalletEvm<T>>::deposit_log(313 erc::CollectionHelpersEvents::CollectionChanged {314 collection_id: eth::collection_id_to_address(self.id),315 }316 .to_log(T::ContractAddress::get()),317 );318 self.save()319 }320321 /// Force remove `sponsor`.322 ///323 /// Differs from `remove_sponsor` in that324 /// it doesn't require consent from the `owner` of the collection.325 pub fn force_remove_sponsor(&mut self) -> DispatchResult {326 self.check_is_internal()?;327328 self.collection.sponsorship = SponsorshipState::Disabled;329330 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));331 <PalletEvm<T>>::deposit_log(332 erc::CollectionHelpersEvents::CollectionChanged {333 collection_id: eth::collection_id_to_address(self.id),334 }335 .to_log(T::ContractAddress::get()),336 );337 self.save()338 }339340 /// Checks that the collection was created with, and must be operated upon through **Unique API**.341 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.342 pub fn check_is_internal(&self) -> DispatchResult {343 if self.flags.external {344 return Err(<Error<T>>::CollectionIsExternal)?;345 }346347 Ok(())348 }349350 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.351 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.352 pub fn check_is_external(&self) -> DispatchResult {353 if !self.flags.external {354 return Err(<Error<T>>::CollectionIsInternal)?;355 }356357 Ok(())358 }359}360361impl<T: Config> Deref for CollectionHandle<T> {362 type Target = Collection<T::AccountId>;363364 fn deref(&self) -> &Self::Target {365 &self.collection366 }367}368369impl<T: Config> DerefMut for CollectionHandle<T> {370 fn deref_mut(&mut self) -> &mut Self::Target {371 &mut self.collection372 }373}374375impl<T: Config> CollectionHandle<T> {376 /// Checks if the `user` is the owner of the collection.377 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {378 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);379 Ok(())380 }381382 /// Returns **true** if the `user` is the owner or administrator of the collection.383 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {384 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))385 }386387 /// Checks if the `user` is the owner or administrator of the collection.388 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {389 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);390 Ok(())391 }392393 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.394 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {395 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)396 }397398 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.399 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {400 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)401 }402403 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.404 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {405 ensure!(406 <Allowlist<T>>::get((self.id, user)),407 <Error<T>>::AddressNotInAllowlist408 );409 Ok(())410 }411412 /// Changes collection owner to another account413 /// #### Store read/writes414 /// 1 writes415 pub fn change_owner(416 &mut self,417 caller: T::CrossAccountId,418 new_owner: T::CrossAccountId,419 ) -> DispatchResult {420 self.check_is_internal()?;421 self.check_is_owner(&caller)?;422 self.collection.owner = new_owner.as_sub().clone();423424 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(425 self.id,426 new_owner.as_sub().clone(),427 ));428 <PalletEvm<T>>::deposit_log(429 erc::CollectionHelpersEvents::CollectionChanged {430 collection_id: eth::collection_id_to_address(self.id),431 }432 .to_log(T::ContractAddress::get()),433 );434435 self.save()436 }437}438439#[frame_support::pallet]440pub mod pallet {441 use super::*;442 use dispatch::CollectionDispatch;443 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};444 use frame_system::pallet_prelude::*;445 use frame_support::traits::Currency;446 use up_data_structs::{TokenId, mapping::TokenAddressMapping};447 use scale_info::TypeInfo;448 use weights::WeightInfo;449450 #[pallet::config]451 pub trait Config:452 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo453 {454 /// Weight information for functions of this pallet.455 type WeightInfo: WeightInfo;456457 /// Events compatible with [`frame_system::Config::Event`].458 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;459460 /// Handler of accounts and payment.461 type Currency: Currency<Self::AccountId>;462463 /// Set price to create a collection.464 #[pallet::constant]465 type CollectionCreationPrice: Get<466 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,467 >;468469 /// Dispatcher of operations on collections.470 type CollectionDispatch: CollectionDispatch<Self>;471472 /// Account which holds the chain's treasury.473 type TreasuryAccountId: Get<Self::AccountId>;474475 /// Address under which the CollectionHelper contract would be available.476 #[pallet::constant]477 type ContractAddress: Get<H160>;478479 /// Mapper for token addresses to Ethereum addresses.480 type EvmTokenAddressMapping: TokenAddressMapping<H160>;481482 /// Mapper for token addresses to [`CrossAccountId`].483 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;484 }485486 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);487488 #[pallet::pallet]489 #[pallet::storage_version(STORAGE_VERSION)]490 #[pallet::generate_store(pub(super) trait Store)]491 pub struct Pallet<T>(_);492493 #[pallet::extra_constants]494 impl<T: Config> Pallet<T> {495 /// Maximum admins per collection.496 pub fn collection_admins_limit() -> u32 {497 COLLECTION_ADMINS_LIMIT498 }499 }500501 #[pallet::event]502 #[pallet::generate_deposit(pub fn deposit_event)]503 pub enum Event<T: Config> {504 /// New collection was created505 CollectionCreated(506 /// Globally unique identifier of newly created collection.507 CollectionId,508 /// [`CollectionMode`] converted into _u8_.509 u8,510 /// Collection owner.511 T::AccountId,512 ),513514 /// New collection was destroyed515 CollectionDestroyed(516 /// Globally unique identifier of collection.517 CollectionId,518 ),519520 /// New item was created.521 ItemCreated(522 /// Id of the collection where item was created.523 CollectionId,524 /// Id of an item. Unique within the collection.525 TokenId,526 /// Owner of newly created item527 T::CrossAccountId,528 /// Always 1 for NFT529 u128,530 ),531532 /// Collection item was burned.533 ItemDestroyed(534 /// Id of the collection where item was destroyed.535 CollectionId,536 /// Identifier of burned NFT.537 TokenId,538 /// Which user has destroyed its tokens.539 T::CrossAccountId,540 /// Amount of token pieces destroed. Always 1 for NFT.541 u128,542 ),543544 /// Item was transferred545 Transfer(546 /// Id of collection to which item is belong.547 CollectionId,548 /// Id of an item.549 TokenId,550 /// Original owner of item.551 T::CrossAccountId,552 /// New owner of item.553 T::CrossAccountId,554 /// Amount of token pieces transfered. Always 1 for NFT.555 u128,556 ),557558 /// Amount pieces of token owned by `sender` was approved for `spender`.559 Approved(560 /// Id of collection to which item is belong.561 CollectionId,562 /// Id of an item.563 TokenId,564 /// Original owner of item.565 T::CrossAccountId,566 /// Id for which the approval was granted.567 T::CrossAccountId,568 /// Amount of token pieces transfered. Always 1 for NFT.569 u128,570 ),571572 /// A `sender` approves operations on all owned tokens for `spender`.573 ApprovedForAll(574 /// Id of collection to which item is belong.575 CollectionId,576 /// Owner of a wallet.577 T::CrossAccountId,578 /// Id for which operator status was granted or rewoked.579 T::CrossAccountId,580 /// Is operator status granted or revoked?581 bool,582 ),583584 /// The colletion property has been added or edited.585 CollectionPropertySet(586 /// Id of collection to which property has been set.587 CollectionId,588 /// The property that was set.589 PropertyKey,590 ),591592 /// The property has been deleted.593 CollectionPropertyDeleted(594 /// Id of collection to which property has been deleted.595 CollectionId,596 /// The property that was deleted.597 PropertyKey,598 ),599600 /// The token property has been added or edited.601 TokenPropertySet(602 /// Identifier of the collection whose token has the property set.603 CollectionId,604 /// The token for which the property was set.605 TokenId,606 /// The property that was set.607 PropertyKey,608 ),609610 /// The token property has been deleted.611 TokenPropertyDeleted(612 /// Identifier of the collection whose token has the property deleted.613 CollectionId,614 /// The token for which the property was deleted.615 TokenId,616 /// The property that was deleted.617 PropertyKey,618 ),619620 /// The token property permission of a collection has been set.621 PropertyPermissionSet(622 /// ID of collection to which property permission has been set.623 CollectionId,624 /// The property permission that was set.625 PropertyKey,626 ),627628 /// Address was added to the allow list.629 AllowListAddressAdded(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the added account.633 T::CrossAccountId,634 ),635636 /// Address was removed from the allow list.637 AllowListAddressRemoved(638 /// ID of the affected collection.639 CollectionId,640 /// Address of the removed account.641 T::CrossAccountId,642 ),643644 /// Collection admin was added.645 CollectionAdminAdded(646 /// ID of the affected collection.647 CollectionId,648 /// Admin address.649 T::CrossAccountId,650 ),651652 /// Collection admin was removed.653 CollectionAdminRemoved(654 /// ID of the affected collection.655 CollectionId,656 /// Removed admin address.657 T::CrossAccountId,658 ),659660 /// Collection limits were set.661 CollectionLimitSet(662 /// ID of the affected collection.663 CollectionId,664 ),665666 /// Collection owned was changed.667 CollectionOwnerChanged(668 /// ID of the affected collection.669 CollectionId,670 /// New owner address.671 T::AccountId,672 ),673674 /// Collection permissions were set.675 CollectionPermissionSet(676 /// ID of the affected collection.677 CollectionId,678 ),679680 /// Collection sponsor was set.681 CollectionSponsorSet(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// New sponsor was confirm.689 SponsorshipConfirmed(690 /// ID of the affected collection.691 CollectionId,692 /// New sponsor address.693 T::AccountId,694 ),695696 /// Collection sponsor was removed.697 CollectionSponsorRemoved(698 /// ID of the affected collection.699 CollectionId,700 ),701 }702703 #[pallet::error]704 pub enum Error<T> {705 /// This collection does not exist.706 CollectionNotFound,707 /// Sender parameter and item owner must be equal.708 MustBeTokenOwner,709 /// No permission to perform action710 NoPermission,711 /// Destroying only empty collections is allowed712 CantDestroyNotEmptyCollection,713 /// Collection is not in mint mode.714 PublicMintingNotAllowed,715 /// Address is not in allow list.716 AddressNotInAllowlist,717718 /// Collection name can not be longer than 63 char.719 CollectionNameLimitExceeded,720 /// Collection description can not be longer than 255 char.721 CollectionDescriptionLimitExceeded,722 /// Token prefix can not be longer than 15 char.723 CollectionTokenPrefixLimitExceeded,724 /// Total collections bound exceeded.725 TotalCollectionsLimitExceeded,726 /// Exceeded max admin count727 CollectionAdminCountExceeded,728 /// Collection limit bounds per collection exceeded729 CollectionLimitBoundsExceeded,730 /// Tried to enable permissions which are only permitted to be disabled731 OwnerPermissionsCantBeReverted,732 /// Collection settings not allowing items transferring733 TransferNotAllowed,734 /// Account token limit exceeded per collection735 AccountTokenLimitExceeded,736 /// Collection token limit exceeded737 CollectionTokenLimitExceeded,738 /// Metadata flag frozen739 MetadataFlagFrozen,740741 /// Item does not exist742 TokenNotFound,743 /// Item is balance not enough744 TokenValueTooLow,745 /// Requested value is more than the approved746 ApprovedValueTooLow,747 /// Tried to approve more than owned748 CantApproveMoreThanOwned,749750 /// Can't transfer tokens to ethereum zero address751 AddressIsZero,752753 /// The operation is not supported754 UnsupportedOperation,755756 /// Insufficient funds to perform an action757 NotSufficientFounds,758759 /// User does not satisfy the nesting rule760 UserIsNotAllowedToNest,761 /// Only tokens from specific collections may nest tokens under this one762 SourceCollectionIsNotAllowedToNest,763764 /// Tried to store more data than allowed in collection field765 CollectionFieldSizeExceeded,766767 /// Tried to store more property data than allowed768 NoSpaceForProperty,769770 /// Tried to store more property keys than allowed771 PropertyLimitReached,772773 /// Property key is too long774 PropertyKeyIsTooLong,775776 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed777 InvalidCharacterInPropertyKey,778779 /// Empty property keys are forbidden780 EmptyPropertyKey,781782 /// Tried to access an external collection with an internal API783 CollectionIsExternal,784785 /// Tried to access an internal collection with an external API786 CollectionIsInternal,787788 /// This address is not set as sponsor, use setCollectionSponsor first.789 ConfirmSponsorshipFail,790791 /// The user is not an administrator.792 UserIsNotCollectionAdmin,793 }794795 /// Storage of the count of created collections. Essentially contains the last collection ID.796 #[pallet::storage]797 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;798799 /// Storage of the count of deleted collections.800 #[pallet::storage]801 pub type DestroyedCollectionCount<T> =802 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;803804 /// Storage of collection info.805 #[pallet::storage]806 pub type CollectionById<T> = StorageMap<807 Hasher = Blake2_128Concat,808 Key = CollectionId,809 Value = Collection<<T as frame_system::Config>::AccountId>,810 QueryKind = OptionQuery,811 >;812813 /// Storage of collection properties.814 #[pallet::storage]815 #[pallet::getter(fn collection_properties)]816 pub type CollectionProperties<T> = StorageMap<817 Hasher = Blake2_128Concat,818 Key = CollectionId,819 Value = Properties,820 QueryKind = ValueQuery,821 OnEmpty = up_data_structs::CollectionProperties,822 >;823824 /// Storage of token property permissions of a collection.825 #[pallet::storage]826 #[pallet::getter(fn property_permissions)]827 pub type CollectionPropertyPermissions<T> = StorageMap<828 Hasher = Blake2_128Concat,829 Key = CollectionId,830 Value = PropertiesPermissionMap,831 QueryKind = ValueQuery,832 >;833834 /// Storage of the amount of collection admins.835 #[pallet::storage]836 pub type AdminAmount<T> = StorageMap<837 Hasher = Blake2_128Concat,838 Key = CollectionId,839 Value = u32,840 QueryKind = ValueQuery,841 >;842843 /// List of collection admins.844 #[pallet::storage]845 pub type IsAdmin<T: Config> = StorageNMap<846 Key = (847 Key<Blake2_128Concat, CollectionId>,848 Key<Blake2_128Concat, T::CrossAccountId>,849 ),850 Value = bool,851 QueryKind = ValueQuery,852 >;853854 /// Allowlisted collection users.855 #[pallet::storage]856 pub type Allowlist<T: Config> = StorageNMap<857 Key = (858 Key<Blake2_128Concat, CollectionId>,859 Key<Blake2_128Concat, T::CrossAccountId>,860 ),861 Value = bool,862 QueryKind = ValueQuery,863 >;864865 /// Not used by code, exists only to provide some types to metadata.866 #[pallet::storage]867 pub type DummyStorageValue<T: Config> = StorageValue<868 Value = (869 CollectionStats,870 CollectionId,871 TokenId,872 TokenChild,873 PhantomType<(874 TokenData<T::CrossAccountId>,875 RpcCollection<T::AccountId>,876 // RMRK877 RmrkCollectionInfo<T::AccountId>,878 RmrkInstanceInfo<T::AccountId>,879 RmrkResourceInfo,880 RmrkPropertyInfo,881 RmrkBaseInfo<T::AccountId>,882 RmrkPartType,883 RmrkBoundedTheme,884 RmrkNftChild,885 // PoV Estimate Info886 PovInfo,887 )>,888 ),889 QueryKind = OptionQuery,890 >;891892 #[pallet::hooks]893 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {894 fn on_runtime_upgrade() -> Weight {895 StorageVersion::new(1).put::<Pallet<T>>();896897 Weight::zero()898 }899 }900}901902impl<T: Config> Pallet<T> {903 /// Enshure that receiver address is correct.904 ///905 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.906 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {907 ensure!(908 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,909 <Error<T>>::AddressIsZero910 );911 Ok(())912 }913914 /// Get a vector of collection admins.915 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {916 <IsAdmin<T>>::iter_prefix((collection,))917 .map(|(a, _)| a)918 .collect()919 }920921 /// Get a vector of users allowed to mint tokens.922 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {923 <Allowlist<T>>::iter_prefix((collection,))924 .map(|(a, _)| a)925 .collect()926 }927928 /// Is `user` allowed to mint token in `collection`.929 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {930 <Allowlist<T>>::get((collection, user))931 }932933 /// Get statistics of collections.934 pub fn collection_stats() -> CollectionStats {935 let created = <CreatedCollectionCount<T>>::get();936 let destroyed = <DestroyedCollectionCount<T>>::get();937 CollectionStats {938 created: created.0,939 destroyed: destroyed.0,940 alive: created.0 - destroyed.0,941 }942 }943944 /// Get the effective limits for the collection.945 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {946 let collection = <CollectionById<T>>::get(collection)?;947 let limits = collection.limits;948 let effective_limits = CollectionLimits {949 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),950 sponsored_data_size: Some(limits.sponsored_data_size()),951 sponsored_data_rate_limit: Some(952 limits953 .sponsored_data_rate_limit954 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),955 ),956 token_limit: Some(limits.token_limit()),957 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(958 match collection.mode {959 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,960 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,961 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,962 },963 )),964 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),965 owner_can_transfer: Some(limits.owner_can_transfer()),966 owner_can_destroy: Some(limits.owner_can_destroy()),967 transfers_enabled: Some(limits.transfers_enabled()),968 };969970 Some(effective_limits)971 }972973 /// Returns information about the `collection` adapted for rpc.974 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {975 let Collection {976 name,977 description,978 owner,979 mode,980 token_prefix,981 sponsorship,982 limits,983 permissions,984 flags,985 } = <CollectionById<T>>::get(collection)?;986987 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)988 .into_iter()989 .map(|(key, permission)| PropertyKeyPermission { key, permission })990 .collect();991992 let properties = <CollectionProperties<T>>::get(collection)993 .into_iter()994 .map(|(key, value)| Property { key, value })995 .collect();996997 let permissions = CollectionPermissions {998 access: Some(permissions.access()),999 mint_mode: Some(permissions.mint_mode()),1000 nesting: Some(permissions.nesting().clone()),1001 };10021003 Some(RpcCollection {1004 name: name.into_inner(),1005 description: description.into_inner(),1006 owner,1007 mode,1008 token_prefix: token_prefix.into_inner(),1009 sponsorship,1010 limits,1011 permissions,1012 token_property_permissions,1013 properties,1014 read_only: flags.external,10151016 flags: RpcCollectionFlags {1017 foreign: flags.foreign,1018 erc721metadata: flags.erc721metadata,1019 },1020 })1021 }1022}10231024macro_rules! limit_default {1025 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1026 $(1027 if let Some($new) = $new.$field {1028 let $old = $old.$field($($arg)?);1029 let _ = $new;1030 let _ = $old;1031 $check1032 } else {1033 $new.$field = $old.$field1034 }1035 )*1036 }};1037}1038macro_rules! limit_default_clone {1039 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1040 $(1041 if let Some($new) = $new.$field.clone() {1042 let $old = $old.$field($($arg)?);1043 let _ = $new;1044 let _ = $old;1045 $check1046 } else {1047 $new.$field = $old.$field.clone()1048 }1049 )*1050 }};1051}10521053impl<T: Config> Pallet<T> {1054 /// Create new collection.1055 ///1056 /// * `owner` - The owner of the collection.1057 /// * `data` - Description of the created collection.1058 /// * `flags` - Extra flags to store.1059 pub fn init_collection(1060 owner: T::CrossAccountId,1061 payer: T::CrossAccountId,1062 data: CreateCollectionData<T::AccountId>,1063 flags: CollectionFlags,1064 ) -> Result<CollectionId, DispatchError> {1065 {1066 ensure!(1067 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1068 Error::<T>::CollectionTokenPrefixLimitExceeded1069 );1070 }10711072 let created_count = <CreatedCollectionCount<T>>::get()1073 .01074 .checked_add(1)1075 .ok_or(ArithmeticError::Overflow)?;1076 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1077 let id = CollectionId(created_count);10781079 // bound Total number of collections1080 ensure!(1081 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1082 <Error<T>>::TotalCollectionsLimitExceeded1083 );10841085 // =========10861087 let collection = Collection {1088 owner: owner.as_sub().clone(),1089 name: data.name,1090 mode: data.mode.clone(),1091 description: data.description,1092 token_prefix: data.token_prefix,1093 sponsorship: data1094 .pending_sponsor1095 .map(SponsorshipState::Unconfirmed)1096 .unwrap_or_default(),1097 limits: data1098 .limits1099 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1100 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1101 permissions: data1102 .permissions1103 .map(|permissions| {1104 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1105 })1106 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1107 flags,1108 };11091110 let mut collection_properties = up_data_structs::CollectionProperties::get();1111 collection_properties1112 .try_set_from_iter(data.properties.into_iter())1113 .map_err(<Error<T>>::from)?;11141115 CollectionProperties::<T>::insert(id, collection_properties);11161117 let mut token_props_permissions = PropertiesPermissionMap::new();1118 token_props_permissions1119 .try_set_from_iter(data.token_property_permissions.into_iter())1120 .map_err(<Error<T>>::from)?;11211122 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11231124 // Take a (non-refundable) deposit of collection creation1125 {1126 let mut imbalance =1127 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1128 imbalance.subsume(1129 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1130 &T::TreasuryAccountId::get(),1131 T::CollectionCreationPrice::get(),1132 ),1133 );1134 <T as Config>::Currency::settle(1135 payer.as_sub(),1136 imbalance,1137 WithdrawReasons::TRANSFER,1138 ExistenceRequirement::KeepAlive,1139 )1140 .map_err(|_| Error::<T>::NotSufficientFounds)?;1141 }11421143 <CreatedCollectionCount<T>>::put(created_count);1144 <Pallet<T>>::deposit_event(Event::CollectionCreated(1145 id,1146 data.mode.id(),1147 owner.as_sub().clone(),1148 ));1149 <PalletEvm<T>>::deposit_log(1150 erc::CollectionHelpersEvents::CollectionCreated {1151 owner: *owner.as_eth(),1152 collection_id: eth::collection_id_to_address(id),1153 }1154 .to_log(T::ContractAddress::get()),1155 );1156 <CollectionById<T>>::insert(id, collection);1157 Ok(id)1158 }11591160 /// Destroy collection.1161 ///1162 /// * `collection` - Collection handler.1163 /// * `sender` - The owner or administrator of the collection.1164 pub fn destroy_collection(1165 collection: CollectionHandle<T>,1166 sender: &T::CrossAccountId,1167 ) -> DispatchResult {1168 ensure!(1169 collection.limits.owner_can_destroy(),1170 <Error<T>>::NoPermission,1171 );1172 collection.check_is_owner(sender)?;11731174 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1175 .01176 .checked_add(1)1177 .ok_or(ArithmeticError::Overflow)?;11781179 // =========11801181 <DestroyedCollectionCount<T>>::put(destroyed_collections);1182 <CollectionById<T>>::remove(collection.id);1183 <AdminAmount<T>>::remove(collection.id);1184 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1185 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1186 <CollectionProperties<T>>::remove(collection.id);11871188 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11891190 <PalletEvm<T>>::deposit_log(1191 erc::CollectionHelpersEvents::CollectionDestroyed {1192 collection_id: eth::collection_id_to_address(collection.id),1193 }1194 .to_log(T::ContractAddress::get()),1195 );1196 Ok(())1197 }11981199 /// Set collection property.1200 ///1201 /// * `collection` - Collection handler.1202 /// * `sender` - The owner or administrator of the collection.1203 /// * `property` - The property to set.1204 pub fn set_collection_property(1205 collection: &CollectionHandle<T>,1206 sender: &T::CrossAccountId,1207 property: Property,1208 ) -> DispatchResult {1209 collection.check_is_owner_or_admin(sender)?;12101211 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1212 let property = property.clone();1213 properties.try_set(property.key, property.value)1214 })1215 .map_err(<Error<T>>::from)?;12161217 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1218 <PalletEvm<T>>::deposit_log(1219 erc::CollectionHelpersEvents::CollectionChanged {1220 collection_id: eth::collection_id_to_address(collection.id),1221 }1222 .to_log(T::ContractAddress::get()),1223 );12241225 Ok(())1226 }12271228 /// Set a scoped collection property, where the scope is a special prefix1229 /// prohibiting a user access to change the property directly.1230 ///1231 /// * `collection_id` - ID of the collection for which the property is being set.1232 /// * `scope` - Property scope.1233 /// * `property` - The property to set.1234 pub fn set_scoped_collection_property(1235 collection_id: CollectionId,1236 scope: PropertyScope,1237 property: Property,1238 ) -> DispatchResult {1239 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1240 properties.try_scoped_set(scope, property.key, property.value)1241 })1242 .map_err(<Error<T>>::from)?;12431244 Ok(())1245 }12461247 /// Set scoped collection properties, where the scope is a special prefix1248 /// prohibiting a user access to change the properties directly.1249 ///1250 /// * `collection_id` - ID of the collection for which the properties is being set.1251 /// * `scope` - Property scope.1252 /// * `properties` - The properties to set.1253 pub fn set_scoped_collection_properties(1254 collection_id: CollectionId,1255 scope: PropertyScope,1256 properties: impl Iterator<Item = Property>,1257 ) -> DispatchResult {1258 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1259 stored_properties.try_scoped_set_from_iter(scope, properties)1260 })1261 .map_err(<Error<T>>::from)?;12621263 Ok(())1264 }12651266 /// Set collection properties.1267 ///1268 /// * `collection` - Collection handler.1269 /// * `sender` - The owner or administrator of the collection.1270 /// * `properties` - The properties to set.1271 #[transactional]1272 pub fn set_collection_properties(1273 collection: &CollectionHandle<T>,1274 sender: &T::CrossAccountId,1275 properties: Vec<Property>,1276 ) -> DispatchResult {1277 for property in properties {1278 Self::set_collection_property(collection, sender, property)?;1279 }12801281 Ok(())1282 }12831284 /// Delete collection property.1285 ///1286 /// * `collection` - Collection handler.1287 /// * `sender` - The owner or administrator of the collection.1288 /// * `property` - The property to delete.1289 pub fn delete_collection_property(1290 collection: &CollectionHandle<T>,1291 sender: &T::CrossAccountId,1292 property_key: PropertyKey,1293 ) -> DispatchResult {1294 collection.check_is_owner_or_admin(sender)?;12951296 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1297 properties.remove(&property_key)1298 })1299 .map_err(<Error<T>>::from)?;13001301 Self::deposit_event(Event::CollectionPropertyDeleted(1302 collection.id,1303 property_key,1304 ));1305 <PalletEvm<T>>::deposit_log(1306 erc::CollectionHelpersEvents::CollectionChanged {1307 collection_id: eth::collection_id_to_address(collection.id),1308 }1309 .to_log(T::ContractAddress::get()),1310 );13111312 Ok(())1313 }13141315 /// Delete collection properties.1316 ///1317 /// * `collection` - Collection handler.1318 /// * `sender` - The owner or administrator of the collection.1319 /// * `properties` - The properties to delete.1320 #[transactional]1321 pub fn delete_collection_properties(1322 collection: &CollectionHandle<T>,1323 sender: &T::CrossAccountId,1324 property_keys: Vec<PropertyKey>,1325 ) -> DispatchResult {1326 for key in property_keys {1327 Self::delete_collection_property(collection, sender, key)?;1328 }13291330 Ok(())1331 }13321333 /// Set collection propetry permission without any checks.1334 ///1335 /// Used for migrations.1336 ///1337 /// * `collection` - Collection handler.1338 /// * `property_permissions` - Property permissions.1339 pub fn set_property_permission_unchecked(1340 collection: CollectionId,1341 property_permission: PropertyKeyPermission,1342 ) -> DispatchResult {1343 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1344 permissions.try_set(property_permission.key, property_permission.permission)1345 })1346 .map_err(<Error<T>>::from)?;1347 Ok(())1348 }13491350 /// Set collection property permission.1351 ///1352 /// * `collection` - Collection handler.1353 /// * `sender` - The owner or administrator of the collection.1354 /// * `property_permission` - Property permission.1355 pub fn set_property_permission(1356 collection: &CollectionHandle<T>,1357 sender: &T::CrossAccountId,1358 property_permission: PropertyKeyPermission,1359 ) -> DispatchResult {1360 Self::set_scoped_property_permission(1361 collection,1362 sender,1363 PropertyScope::None,1364 property_permission,1365 )1366 }13671368 /// Set collection property permission with scope.1369 ///1370 /// * `collection` - Collection handler.1371 /// * `sender` - The owner or administrator of the collection.1372 /// * `scope` - Property scope.1373 /// * `property_permission` - Property permission.1374 pub fn set_scoped_property_permission(1375 collection: &CollectionHandle<T>,1376 sender: &T::CrossAccountId,1377 scope: PropertyScope,1378 property_permission: PropertyKeyPermission,1379 ) -> DispatchResult {1380 collection.check_is_owner_or_admin(sender)?;13811382 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1383 let current_permission = all_permissions.get(&property_permission.key);1384 if matches![1385 current_permission,1386 Some(PropertyPermission { mutable: false, .. })1387 ] {1388 return Err(<Error<T>>::NoPermission.into());1389 }13901391 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1392 let property_permission = property_permission.clone();1393 permissions.try_scoped_set(1394 scope,1395 property_permission.key,1396 property_permission.permission,1397 )1398 })1399 .map_err(<Error<T>>::from)?;14001401 Self::deposit_event(Event::PropertyPermissionSet(1402 collection.id,1403 property_permission.key,1404 ));1405 <PalletEvm<T>>::deposit_log(1406 erc::CollectionHelpersEvents::CollectionChanged {1407 collection_id: eth::collection_id_to_address(collection.id),1408 }1409 .to_log(T::ContractAddress::get()),1410 );14111412 Ok(())1413 }14141415 /// Set token property permission.1416 ///1417 /// * `collection` - Collection handler.1418 /// * `sender` - The owner or administrator of the collection.1419 /// * `property_permissions` - Property permissions.1420 #[transactional]1421 pub fn set_token_property_permissions(1422 collection: &CollectionHandle<T>,1423 sender: &T::CrossAccountId,1424 property_permissions: Vec<PropertyKeyPermission>,1425 ) -> DispatchResult {1426 Self::set_scoped_token_property_permissions(1427 collection,1428 sender,1429 PropertyScope::None,1430 property_permissions,1431 )1432 }14331434 /// Set token property permission with scope.1435 ///1436 /// * `collection` - Collection handler.1437 /// * `sender` - The owner or administrator of the collection.1438 /// * `scope` - Property scope.1439 /// * `property_permissions` - Property permissions.1440 #[transactional]1441 pub fn set_scoped_token_property_permissions(1442 collection: &CollectionHandle<T>,1443 sender: &T::CrossAccountId,1444 scope: PropertyScope,1445 property_permissions: Vec<PropertyKeyPermission>,1446 ) -> DispatchResult {1447 for prop_pemission in property_permissions {1448 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1449 }14501451 Ok(())1452 }14531454 /// Get collection property.1455 pub fn get_collection_property(1456 collection_id: CollectionId,1457 key: &PropertyKey,1458 ) -> Option<PropertyValue> {1459 Self::collection_properties(collection_id).get(key).cloned()1460 }14611462 /// Convert byte vector to property key vector.1463 pub fn bytes_keys_to_property_keys(1464 keys: Vec<Vec<u8>>,1465 ) -> Result<Vec<PropertyKey>, DispatchError> {1466 keys.into_iter()1467 .map(|key| -> Result<PropertyKey, DispatchError> {1468 key.try_into()1469 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1470 })1471 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1472 }14731474 /// Get properties according to given keys.1475 pub fn filter_collection_properties(1476 collection_id: CollectionId,1477 keys: Option<Vec<PropertyKey>>,1478 ) -> Result<Vec<Property>, DispatchError> {1479 let properties = Self::collection_properties(collection_id);14801481 let properties = keys1482 .map(|keys| {1483 keys.into_iter()1484 .filter_map(|key| {1485 properties.get(&key).map(|value| Property {1486 key,1487 value: value.clone(),1488 })1489 })1490 .collect()1491 })1492 .unwrap_or_else(|| {1493 properties1494 .into_iter()1495 .map(|(key, value)| Property { key, value })1496 .collect()1497 });14981499 Ok(properties)1500 }15011502 /// Get property permissions according to given keys.1503 pub fn filter_property_permissions(1504 collection_id: CollectionId,1505 keys: Option<Vec<PropertyKey>>,1506 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1507 let permissions = Self::property_permissions(collection_id);15081509 let key_permissions = keys1510 .map(|keys| {1511 keys.into_iter()1512 .filter_map(|key| {1513 permissions1514 .get(&key)1515 .map(|permission| PropertyKeyPermission {1516 key,1517 permission: permission.clone(),1518 })1519 })1520 .collect()1521 })1522 .unwrap_or_else(|| {1523 permissions1524 .into_iter()1525 .map(|(key, permission)| PropertyKeyPermission { key, permission })1526 .collect()1527 });15281529 Ok(key_permissions)1530 }15311532 /// Toggle `user` participation in the `collection`'s allow list.1533 /// #### Store read/writes1534 /// 1 writes1535 pub fn toggle_allowlist(1536 collection: &CollectionHandle<T>,1537 sender: &T::CrossAccountId,1538 user: &T::CrossAccountId,1539 allowed: bool,1540 ) -> DispatchResult {1541 collection.check_is_owner_or_admin(sender)?;15421543 // =========15441545 if allowed {1546 <Allowlist<T>>::insert((collection.id, user), true);1547 Self::deposit_event(Event::<T>::AllowListAddressAdded(1548 collection.id,1549 user.clone(),1550 ));1551 } else {1552 <Allowlist<T>>::remove((collection.id, user));1553 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1554 collection.id,1555 user.clone(),1556 ));1557 }15581559 <PalletEvm<T>>::deposit_log(1560 erc::CollectionHelpersEvents::CollectionChanged {1561 collection_id: eth::collection_id_to_address(collection.id),1562 }1563 .to_log(T::ContractAddress::get()),1564 );15651566 Ok(())1567 }15681569 /// Toggle `user` participation in the `collection`'s admin list.1570 /// #### Store read/writes1571 /// 2 reads, 2 writes1572 pub fn toggle_admin(1573 collection: &CollectionHandle<T>,1574 sender: &T::CrossAccountId,1575 user: &T::CrossAccountId,1576 admin: bool,1577 ) -> DispatchResult {1578 collection.check_is_internal()?;1579 collection.check_is_owner(sender)?;15801581 let is_admin = <IsAdmin<T>>::get((collection.id, user));1582 if is_admin == admin {1583 if admin {1584 return Ok(());1585 } else {1586 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1587 }1588 }1589 let amount = <AdminAmount<T>>::get(collection.id);15901591 // =========15921593 if admin {1594 let amount = amount1595 .checked_add(1)1596 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1597 ensure!(1598 amount <= Self::collection_admins_limit(),1599 <Error<T>>::CollectionAdminCountExceeded,1600 );16011602 <AdminAmount<T>>::insert(collection.id, amount);1603 <IsAdmin<T>>::insert((collection.id, user), true);16041605 Self::deposit_event(Event::<T>::CollectionAdminAdded(1606 collection.id,1607 user.clone(),1608 ));1609 } else {1610 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1611 <IsAdmin<T>>::remove((collection.id, user));16121613 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1614 collection.id,1615 user.clone(),1616 ));1617 }16181619 <PalletEvm<T>>::deposit_log(1620 erc::CollectionHelpersEvents::CollectionChanged {1621 collection_id: eth::collection_id_to_address(collection.id),1622 }1623 .to_log(T::ContractAddress::get()),1624 );16251626 Ok(())1627 }16281629 /// Update collection limits.1630 pub fn update_limits(1631 user: &T::CrossAccountId,1632 collection: &mut CollectionHandle<T>,1633 new_limit: CollectionLimits,1634 ) -> DispatchResult {1635 collection.check_is_internal()?;1636 collection.check_is_owner_or_admin(user)?;16371638 collection.limits =1639 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16401641 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1642 <PalletEvm<T>>::deposit_log(1643 erc::CollectionHelpersEvents::CollectionChanged {1644 collection_id: eth::collection_id_to_address(collection.id),1645 }1646 .to_log(T::ContractAddress::get()),1647 );16481649 collection.save()1650 }16511652 /// Merge set fields from `new_limit` to `old_limit`.1653 fn clamp_limits(1654 mode: CollectionMode,1655 old_limit: &CollectionLimits,1656 mut new_limit: CollectionLimits,1657 ) -> Result<CollectionLimits, DispatchError> {1658 let limits = old_limit;1659 limit_default!(old_limit, new_limit,1660 account_token_ownership_limit => ensure!(1661 new_limit <= MAX_TOKEN_OWNERSHIP,1662 <Error<T>>::CollectionLimitBoundsExceeded,1663 ),1664 sponsored_data_size => ensure!(1665 new_limit <= CUSTOM_DATA_LIMIT,1666 <Error<T>>::CollectionLimitBoundsExceeded,1667 ),16681669 sponsored_data_rate_limit => {},1670 token_limit => ensure!(1671 old_limit >= new_limit && new_limit > 0,1672 <Error<T>>::CollectionTokenLimitExceeded1673 ),16741675 sponsor_transfer_timeout(match mode {1676 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1677 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1678 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1679 }) => ensure!(1680 new_limit <= MAX_SPONSOR_TIMEOUT,1681 <Error<T>>::CollectionLimitBoundsExceeded,1682 ),1683 sponsor_approve_timeout => {},1684 owner_can_transfer => ensure!(1685 !limits.owner_can_transfer_instaled() ||1686 old_limit || !new_limit,1687 <Error<T>>::OwnerPermissionsCantBeReverted,1688 ),1689 owner_can_destroy => ensure!(1690 old_limit || !new_limit,1691 <Error<T>>::OwnerPermissionsCantBeReverted,1692 ),1693 transfers_enabled => {},1694 );1695 Ok(new_limit)1696 }16971698 /// Update collection permissions.1699 pub fn update_permissions(1700 user: &T::CrossAccountId,1701 collection: &mut CollectionHandle<T>,1702 new_permission: CollectionPermissions,1703 ) -> DispatchResult {1704 collection.check_is_internal()?;1705 collection.check_is_owner_or_admin(user)?;1706 collection.permissions = Self::clamp_permissions(1707 collection.mode.clone(),1708 &collection.permissions,1709 new_permission,1710 )?;17111712 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1713 <PalletEvm<T>>::deposit_log(1714 erc::CollectionHelpersEvents::CollectionChanged {1715 collection_id: eth::collection_id_to_address(collection.id),1716 }1717 .to_log(T::ContractAddress::get()),1718 );17191720 collection.save()1721 }17221723 /// Merge set fields from `new_permission` to `old_permission`.1724 fn clamp_permissions(1725 _mode: CollectionMode,1726 old_permission: &CollectionPermissions,1727 mut new_permission: CollectionPermissions,1728 ) -> Result<CollectionPermissions, DispatchError> {1729 limit_default_clone!(old_permission, new_permission,1730 access => {},1731 mint_mode => {},1732 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1733 );1734 Ok(new_permission)1735 }17361737 /// Repair possibly broken properties of a collection.1738 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1739 CollectionProperties::<T>::mutate(collection_id, |properties| {1740 properties.recompute_consumed_space();1741 });17421743 Ok(())1744 }1745}17461747/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1748#[macro_export]1749macro_rules! unsupported {1750 ($runtime:path) => {1751 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1752 };1753}17541755/// Return weights for various worst-case operations.1756pub trait CommonWeightInfo<CrossAccountId> {1757 /// Weight of item creation.1758 fn create_item() -> Weight;17591760 /// Weight of items creation.1761 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17621763 /// Weight of items creation.1764 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17651766 /// The weight of the burning item.1767 fn burn_item() -> Weight;17681769 /// Property setting weight.1770 ///1771 /// * `amount`- The number of properties to set.1772 fn set_collection_properties(amount: u32) -> Weight;17731774 /// Collection property deletion weight.1775 ///1776 /// * `amount`- The number of properties to set.1777 fn delete_collection_properties(amount: u32) -> Weight;17781779 /// Token property setting weight.1780 ///1781 /// * `amount`- The number of properties to set.1782 fn set_token_properties(amount: u32) -> Weight;17831784 /// Token property deletion weight.1785 ///1786 /// * `amount`- The number of properties to delete.1787 fn delete_token_properties(amount: u32) -> Weight;17881789 /// Token property permissions set weight.1790 ///1791 /// * `amount`- The number of property permissions to set.1792 fn set_token_property_permissions(amount: u32) -> Weight;17931794 /// Transfer price of the token or its parts.1795 fn transfer() -> Weight;17961797 /// The price of setting the permission of the operation from another user.1798 fn approve() -> Weight;17991800 /// Transfer price from another user.1801 fn transfer_from() -> Weight;18021803 /// The price of burning a token from another user.1804 fn burn_from() -> Weight;18051806 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1807 /// whole users's balance.1808 ///1809 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1810 fn burn_recursively_self_raw() -> Weight;18111812 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1813 ///1814 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1815 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18161817 /// The price of recursive burning a token.1818 ///1819 /// `max_selfs` - The maximum burning weight of the token itself.1820 /// `max_breadth` - The maximum number of nested tokens to burn.1821 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1822 Self::burn_recursively_self_raw()1823 .saturating_mul(max_selfs.max(1) as u64)1824 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1825 }18261827 /// The price of retrieving token owner1828 fn token_owner() -> Weight;18291830 /// The price of setting approval for all1831 fn set_allowance_for_all() -> Weight;18321833 /// The price of repairing an item.1834 fn force_repair_item() -> Weight;1835}18361837/// Weight info extension trait for refungible pallet.1838pub trait RefungibleExtensionsWeightInfo {1839 /// Weight of token repartition.1840 fn repartition() -> Weight;1841}18421843/// Common collection operations.1844///1845/// It wraps methods in Fungible, Nonfungible and Refungible pallets1846/// and adds weight info.1847pub trait CommonCollectionOperations<T: Config> {1848 /// Create token.1849 ///1850 /// * `sender` - The user who mint the token and pays for the transaction.1851 /// * `to` - The user who will own the token.1852 /// * `data` - Token data.1853 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1854 fn create_item(1855 &self,1856 sender: T::CrossAccountId,1857 to: T::CrossAccountId,1858 data: CreateItemData,1859 nesting_budget: &dyn Budget,1860 ) -> DispatchResultWithPostInfo;18611862 /// Create multiple tokens.1863 ///1864 /// * `sender` - The user who mint the token and pays for the transaction.1865 /// * `to` - The user who will own the token.1866 /// * `data` - Token data.1867 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1868 fn create_multiple_items(1869 &self,1870 sender: T::CrossAccountId,1871 to: T::CrossAccountId,1872 data: Vec<CreateItemData>,1873 nesting_budget: &dyn Budget,1874 ) -> DispatchResultWithPostInfo;18751876 /// Create multiple tokens.1877 ///1878 /// * `sender` - The user who mint the token and pays for the transaction.1879 /// * `to` - The user who will own the token.1880 /// * `data` - Token data.1881 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1882 fn create_multiple_items_ex(1883 &self,1884 sender: T::CrossAccountId,1885 data: CreateItemExData<T::CrossAccountId>,1886 nesting_budget: &dyn Budget,1887 ) -> DispatchResultWithPostInfo;18881889 /// Burn token.1890 ///1891 /// * `sender` - The user who owns the token.1892 /// * `token` - Token id that will burned.1893 /// * `amount` - The number of parts of the token that will be burned.1894 fn burn_item(1895 &self,1896 sender: T::CrossAccountId,1897 token: TokenId,1898 amount: u128,1899 ) -> DispatchResultWithPostInfo;19001901 /// Burn token and all nested tokens recursievly.1902 ///1903 /// * `sender` - The user who owns the token.1904 /// * `token` - Token id that will burned.1905 /// * `self_budget` - The budget that can be spent on burning tokens.1906 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1907 fn burn_item_recursively(1908 &self,1909 sender: T::CrossAccountId,1910 token: TokenId,1911 self_budget: &dyn Budget,1912 breadth_budget: &dyn Budget,1913 ) -> DispatchResultWithPostInfo;19141915 /// Set collection properties.1916 ///1917 /// * `sender` - Must be either the owner of the collection or its admin.1918 /// * `properties` - Properties to be set.1919 fn set_collection_properties(1920 &self,1921 sender: T::CrossAccountId,1922 properties: Vec<Property>,1923 ) -> DispatchResultWithPostInfo;19241925 /// Delete collection properties.1926 ///1927 /// * `sender` - Must be either the owner of the collection or its admin.1928 /// * `properties` - The properties to be removed.1929 fn delete_collection_properties(1930 &self,1931 sender: &T::CrossAccountId,1932 property_keys: Vec<PropertyKey>,1933 ) -> DispatchResultWithPostInfo;19341935 /// Set token properties.1936 ///1937 /// The appropriate [`PropertyPermission`] for the token property1938 /// must be set with [`Self::set_token_property_permissions`].1939 ///1940 /// * `sender` - Must be either the owner of the token or its admin.1941 /// * `token_id` - The token for which the properties are being set.1942 /// * `properties` - Properties to be set.1943 /// * `budget` - Budget for setting properties.1944 fn set_token_properties(1945 &self,1946 sender: T::CrossAccountId,1947 token_id: TokenId,1948 properties: Vec<Property>,1949 budget: &dyn Budget,1950 ) -> DispatchResultWithPostInfo;19511952 /// Remove token properties.1953 ///1954 /// The appropriate [`PropertyPermission`] for the token property1955 /// must be set with [`Self::set_token_property_permissions`].1956 ///1957 /// * `sender` - Must be either the owner of the token or its admin.1958 /// * `token_id` - The token for which the properties are being remove.1959 /// * `property_keys` - Keys to remove corresponding properties.1960 /// * `budget` - Budget for removing properties.1961 fn delete_token_properties(1962 &self,1963 sender: T::CrossAccountId,1964 token_id: TokenId,1965 property_keys: Vec<PropertyKey>,1966 budget: &dyn Budget,1967 ) -> DispatchResultWithPostInfo;19681969 /// Set token property permissions.1970 ///1971 /// * `sender` - Must be either the owner of the token or its admin.1972 /// * `token_id` - The token for which the properties are being set.1973 /// * `property_permissions` - Property permissions to be set.1974 /// * `budget` - Budget for setting properties.1975 fn set_token_property_permissions(1976 &self,1977 sender: &T::CrossAccountId,1978 property_permissions: Vec<PropertyKeyPermission>,1979 ) -> DispatchResultWithPostInfo;19801981 /// Transfer amount of token pieces.1982 ///1983 /// * `sender` - Donor user.1984 /// * `to` - Recepient user.1985 /// * `token` - The token of which parts are being sent.1986 /// * `amount` - The number of parts of the token that will be transferred.1987 /// * `budget` - The maximum budget that can be spent on the transfer.1988 fn transfer(1989 &self,1990 sender: T::CrossAccountId,1991 to: T::CrossAccountId,1992 token: TokenId,1993 amount: u128,1994 budget: &dyn Budget,1995 ) -> DispatchResultWithPostInfo;19961997 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1998 ///1999 /// * `sender` - The user who grants access to the token.2000 /// * `spender` - The user to whom the rights are granted.2001 /// * `token` - The token to which access is granted.2002 /// * `amount` - The amount of pieces that another user can dispose of.2003 fn approve(2004 &self,2005 sender: T::CrossAccountId,2006 spender: T::CrossAccountId,2007 token: TokenId,2008 amount: u128,2009 ) -> DispatchResultWithPostInfo;20102011 /// Send parts of a token owned by another user.2012 ///2013 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2014 ///2015 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2016 /// * `from` - The user who owns the token.2017 /// * `to` - Recepient user.2018 /// * `token` - The token of which parts are being sent.2019 /// * `amount` - The number of parts of the token that will be transferred.2020 /// * `budget` - The maximum budget that can be spent on the transfer.2021 fn transfer_from(2022 &self,2023 sender: T::CrossAccountId,2024 from: T::CrossAccountId,2025 to: T::CrossAccountId,2026 token: TokenId,2027 amount: u128,2028 budget: &dyn Budget,2029 ) -> DispatchResultWithPostInfo;20302031 /// Burn parts of a token owned by another user.2032 ///2033 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2034 ///2035 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2036 /// * `from` - The user who owns the token.2037 /// * `token` - The token of which parts are being sent.2038 /// * `amount` - The number of parts of the token that will be transferred.2039 /// * `budget` - The maximum budget that can be spent on the burn.2040 fn burn_from(2041 &self,2042 sender: T::CrossAccountId,2043 from: T::CrossAccountId,2044 token: TokenId,2045 amount: u128,2046 budget: &dyn Budget,2047 ) -> DispatchResultWithPostInfo;20482049 /// Check permission to nest token.2050 ///2051 /// * `sender` - The user who initiated the check.2052 /// * `from` - The token that is checked for embedding.2053 /// * `under` - Token under which to check.2054 /// * `budget` - The maximum budget that can be spent on the check.2055 fn check_nesting(2056 &self,2057 sender: T::CrossAccountId,2058 from: (CollectionId, TokenId),2059 under: TokenId,2060 budget: &dyn Budget,2061 ) -> DispatchResult;20622063 /// Nest one token into another.2064 ///2065 /// * `under` - Token holder.2066 /// * `to_nest` - Nested token.2067 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20682069 /// Unnest token.2070 ///2071 /// * `under` - Token holder.2072 /// * `to_nest` - Token to unnest.2073 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20742075 /// Get all user tokens.2076 ///2077 /// * `account` - Account for which you need to get tokens.2078 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;20792080 /// Get all the tokens in the collection.2081 fn collection_tokens(&self) -> Vec<TokenId>;20822083 /// Check if the token exists.2084 ///2085 /// * `token` - Id token to check.2086 fn token_exists(&self, token: TokenId) -> bool;20872088 /// Get the id of the last minted token.2089 fn last_token_id(&self) -> TokenId;20902091 /// Get the owner of the token.2092 ///2093 /// * `token` - The token for which you need to find out the owner.2094 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;20952096 /// Returns 10 tokens owners in no particular order.2097 ///2098 /// * `token` - The token for which you need to find out the owners.2099 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21002101 /// Get the value of the token property by key.2102 ///2103 /// * `token` - Token with the property to get.2104 /// * `key` - Property name.2105 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21062107 /// Get a set of token properties by key vector.2108 ///2109 /// * `token` - Token with the property to get.2110 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2111 /// then all properties are returned.2112 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21132114 /// Amount of unique collection tokens2115 fn total_supply(&self) -> u32;21162117 /// Amount of different tokens account has.2118 ///2119 /// * `account` - The account for which need to get the balance.2120 fn account_balance(&self, account: T::CrossAccountId) -> u32;21212122 /// Amount of specific token account have.2123 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21242125 /// Amount of token pieces2126 fn total_pieces(&self, token: TokenId) -> Option<u128>;21272128 /// Get the number of parts of the token that a trusted user can manage.2129 ///2130 /// * `sender` - Trusted user.2131 /// * `spender` - Owner of the token.2132 /// * `token` - The token for which to get the value.2133 fn allowance(2134 &self,2135 sender: T::CrossAccountId,2136 spender: T::CrossAccountId,2137 token: TokenId,2138 ) -> u128;21392140 /// Get extension for RFT collection.2141 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21422143 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2144 /// * `owner` - Token owner2145 /// * `operator` - Operator2146 /// * `approve` - Should operator status be granted or revoked?2147 fn set_allowance_for_all(2148 &self,2149 owner: T::CrossAccountId,2150 operator: T::CrossAccountId,2151 approve: bool,2152 ) -> DispatchResultWithPostInfo;21532154 /// Tells whether the given `owner` approves the `operator`.2155 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21562157 /// Repairs a possibly broken item.2158 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2159}21602161/// Extension for RFT collection.2162pub trait RefungibleExtensions<T>2163where2164 T: Config,2165{2166 /// Change the number of parts of the token.2167 ///2168 /// When the value changes down, this function is equivalent to burning parts of the token.2169 ///2170 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2171 /// * `token` - The token for which you want to change the number of parts.2172 /// * `amount` - The new value of the parts of the token.2173 fn repartition(2174 &self,2175 sender: &T::CrossAccountId,2176 token: TokenId,2177 amount: u128,2178 ) -> DispatchResultWithPostInfo;2179}21802181/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2182///2183/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2184pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2185 let post_info = PostDispatchInfo {2186 actual_weight: Some(weight),2187 pays_fee: Pays::Yes,2188 };2189 match res {2190 Ok(()) => Ok(post_info),2191 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2192 }2193}21942195impl<T: Config> From<PropertiesError> for Error<T> {2196 fn from(error: PropertiesError) -> Self {2197 match error {2198 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2199 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2200 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2201 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2202 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2203 }2204 }2205}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 dispatch::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionFlags,74 RpcCollectionFlags,75 CollectionId,76 CreateItemData,77 MAX_TOKEN_PREFIX_LENGTH,78 COLLECTION_ADMINS_LIMIT,79 TokenId,80 TokenChild,81 CollectionStats,82 MAX_TOKEN_OWNERSHIP,83 CollectionMode,84 NFT_SPONSOR_TRANSFER_TIMEOUT,85 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,86 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,87 MAX_SPONSOR_TIMEOUT,88 CUSTOM_DATA_LIMIT,89 CollectionLimits,90 CreateCollectionData,91 SponsorshipState,92 CreateItemExData,93 SponsoringRateLimit,94 budget::Budget,95 PhantomType,96 Property,97 Properties,98 PropertiesPermissionMap,99 PropertyKey,100 PropertyValue,101 PropertyPermission,102 PropertiesError,103 PropertyKeyPermission,104 TokenData,105 TrySetProperty,106 PropertyScope,107 // RMRK108 RmrkCollectionInfo,109 RmrkInstanceInfo,110 RmrkResourceInfo,111 RmrkPropertyInfo,112 RmrkBaseInfo,113 RmrkPartType,114 RmrkBoundedTheme,115 RmrkNftChild,116 CollectionPermissions,117};118use up_pov_estimate_rpc::PovInfo;119120pub use pallet::*;121use sp_core::H160;122use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};123#[cfg(feature = "runtime-benchmarks")]124pub mod benchmarking;125pub mod dispatch;126pub mod erc;127pub mod eth;128pub mod weights;129130/// Weight info.131pub type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Collection handle contains information about collection data and id.134/// Also provides functionality to count consumed gas.135///136/// CollectionHandle is used as a generic wrapper for collections of all types.137/// It allows to perform common operations and queries on any collection type,138/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].139#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]140pub struct CollectionHandle<T: Config> {141 /// Collection id142 pub id: CollectionId,143 collection: Collection<T::AccountId>,144 /// Substrate recorder for counting consumed gas145 pub recorder: SubstrateRecorder<T>,146}147148impl<T: Config> WithRecorder<T> for CollectionHandle<T> {149 fn recorder(&self) -> &SubstrateRecorder<T> {150 &self.recorder151 }152 fn into_recorder(self) -> SubstrateRecorder<T> {153 self.recorder154 }155}156157impl<T: Config> CollectionHandle<T> {158 /// Same as [CollectionHandle::new] but with an explicit gas limit.159 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {160 <CollectionById<T>>::get(id).map(|collection| Self {161 id,162 collection,163 recorder: SubstrateRecorder::new(gas_limit),164 })165 }166167 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].168 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {169 <CollectionById<T>>::get(id).map(|collection| Self {170 id,171 collection,172 recorder,173 })174 }175176 /// Retrives collection data from storage and creates collection handle with default parameters.177 /// If collection not found return `None`178 pub fn new(id: CollectionId) -> Option<Self> {179 Self::new_with_gas_limit(id, u64::MAX)180 }181182 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.183 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {184 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)185 }186187 /// Consume gas for reading.188 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {189 self.recorder190 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(191 <T as frame_system::Config>::DbWeight::get()192 .read193 .saturating_mul(reads),194 )))195 }196197 /// Consume gas for writing.198 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {199 self.recorder200 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(201 <T as frame_system::Config>::DbWeight::get()202 .write203 .saturating_mul(writes),204 )))205 }206207 /// Consume gas for reading and writing.208 pub fn consume_store_reads_and_writes(209 &self,210 reads: u64,211 writes: u64,212 ) -> evm_coder::execution::Result<()> {213 let weight = <T as frame_system::Config>::DbWeight::get();214 let reads = weight.read.saturating_mul(reads);215 let writes = weight.read.saturating_mul(writes);216 self.recorder217 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(218 reads.saturating_add(writes),219 )))220 }221222 /// Save collection to storage.223 pub fn save(&self) -> DispatchResult {224 <CollectionById<T>>::insert(self.id, &self.collection);225 Ok(())226 }227228 /// Set collection sponsor.229 ///230 /// Unique collections allows sponsoring for certain actions.231 /// This method allows you to set the sponsor of the collection.232 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].233 pub fn set_sponsor(234 &mut self,235 sender: &T::CrossAccountId,236 sponsor: T::AccountId,237 ) -> DispatchResult {238 self.check_is_internal()?;239 self.check_is_owner_or_admin(sender)?;240241 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());242243 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));244 <PalletEvm<T>>::deposit_log(245 erc::CollectionHelpersEvents::CollectionChanged {246 collection_id: eth::collection_id_to_address(self.id),247 }248 .to_log(T::ContractAddress::get()),249 );250251 self.save()252 }253254 /// Force set `sponsor`.255 ///256 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation257 /// from the `sponsor` is not required.258 ///259 /// # Arguments260 ///261 /// * `sender`: Caller's account.262 /// * `sponsor`: ID of the account of the sponsor-to-be.263 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {264 self.check_is_internal()?;265266 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());267268 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));269 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));270 <PalletEvm<T>>::deposit_log(271 erc::CollectionHelpersEvents::CollectionChanged {272 collection_id: eth::collection_id_to_address(self.id),273 }274 .to_log(T::ContractAddress::get()),275 );276277 self.save()278 }279280 /// Confirm sponsorship281 ///282 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.283 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].284 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {285 self.check_is_internal()?;286 ensure!(287 self.collection.sponsorship.pending_sponsor() == Some(sender),288 Error::<T>::ConfirmSponsorshipFail289 );290291 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());292293 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));294 <PalletEvm<T>>::deposit_log(295 erc::CollectionHelpersEvents::CollectionChanged {296 collection_id: eth::collection_id_to_address(self.id),297 }298 .to_log(T::ContractAddress::get()),299 );300301 self.save()302 }303304 /// Remove collection sponsor.305 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {306 self.check_is_internal()?;307 self.check_is_owner_or_admin(sender)?;308309 self.collection.sponsorship = SponsorshipState::Disabled;310311 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));312 <PalletEvm<T>>::deposit_log(313 erc::CollectionHelpersEvents::CollectionChanged {314 collection_id: eth::collection_id_to_address(self.id),315 }316 .to_log(T::ContractAddress::get()),317 );318 self.save()319 }320321 /// Force remove `sponsor`.322 ///323 /// Differs from `remove_sponsor` in that324 /// it doesn't require consent from the `owner` of the collection.325 pub fn force_remove_sponsor(&mut self) -> DispatchResult {326 self.check_is_internal()?;327328 self.collection.sponsorship = SponsorshipState::Disabled;329330 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));331 <PalletEvm<T>>::deposit_log(332 erc::CollectionHelpersEvents::CollectionChanged {333 collection_id: eth::collection_id_to_address(self.id),334 }335 .to_log(T::ContractAddress::get()),336 );337 self.save()338 }339340 /// Checks that the collection was created with, and must be operated upon through **Unique API**.341 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.342 pub fn check_is_internal(&self) -> DispatchResult {343 if self.flags.external {344 return Err(<Error<T>>::CollectionIsExternal)?;345 }346347 Ok(())348 }349350 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.351 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.352 pub fn check_is_external(&self) -> DispatchResult {353 if !self.flags.external {354 return Err(<Error<T>>::CollectionIsInternal)?;355 }356357 Ok(())358 }359}360361impl<T: Config> Deref for CollectionHandle<T> {362 type Target = Collection<T::AccountId>;363364 fn deref(&self) -> &Self::Target {365 &self.collection366 }367}368369impl<T: Config> DerefMut for CollectionHandle<T> {370 fn deref_mut(&mut self) -> &mut Self::Target {371 &mut self.collection372 }373}374375impl<T: Config> CollectionHandle<T> {376 /// Checks if the `user` is the owner of the collection.377 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {378 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);379 Ok(())380 }381382 /// Returns **true** if the `user` is the owner or administrator of the collection.383 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {384 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))385 }386387 /// Checks if the `user` is the owner or administrator of the collection.388 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {389 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);390 Ok(())391 }392393 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.394 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {395 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)396 }397398 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.399 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {400 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)401 }402403 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.404 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {405 ensure!(406 <Allowlist<T>>::get((self.id, user)),407 <Error<T>>::AddressNotInAllowlist408 );409 Ok(())410 }411412 /// Changes collection owner to another account413 /// #### Store read/writes414 /// 1 writes415 pub fn change_owner(416 &mut self,417 caller: T::CrossAccountId,418 new_owner: T::CrossAccountId,419 ) -> DispatchResult {420 self.check_is_internal()?;421 self.check_is_owner(&caller)?;422 self.collection.owner = new_owner.as_sub().clone();423424 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(425 self.id,426 new_owner.as_sub().clone(),427 ));428 <PalletEvm<T>>::deposit_log(429 erc::CollectionHelpersEvents::CollectionChanged {430 collection_id: eth::collection_id_to_address(self.id),431 }432 .to_log(T::ContractAddress::get()),433 );434435 self.save()436 }437}438439#[frame_support::pallet]440pub mod pallet {441 use super::*;442 use dispatch::CollectionDispatch;443 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};444 use frame_system::pallet_prelude::*;445 use frame_support::traits::Currency;446 use up_data_structs::{TokenId, mapping::TokenAddressMapping};447 use scale_info::TypeInfo;448 use weights::WeightInfo;449450 #[pallet::config]451 pub trait Config:452 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo453 {454 /// Weight information for functions of this pallet.455 type WeightInfo: WeightInfo;456457 /// Events compatible with [`frame_system::Config::Event`].458 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;459460 /// Handler of accounts and payment.461 type Currency: Currency<Self::AccountId>;462463 /// Set price to create a collection.464 #[pallet::constant]465 type CollectionCreationPrice: Get<466 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,467 >;468469 /// Dispatcher of operations on collections.470 type CollectionDispatch: CollectionDispatch<Self>;471472 /// Account which holds the chain's treasury.473 type TreasuryAccountId: Get<Self::AccountId>;474475 /// Address under which the CollectionHelper contract would be available.476 #[pallet::constant]477 type ContractAddress: Get<H160>;478479 /// Mapper for token addresses to Ethereum addresses.480 type EvmTokenAddressMapping: TokenAddressMapping<H160>;481482 /// Mapper for token addresses to [`CrossAccountId`].483 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;484 }485486 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);487488 #[pallet::pallet]489 #[pallet::storage_version(STORAGE_VERSION)]490 #[pallet::generate_store(pub(super) trait Store)]491 pub struct Pallet<T>(_);492493 #[pallet::extra_constants]494 impl<T: Config> Pallet<T> {495 /// Maximum admins per collection.496 pub fn collection_admins_limit() -> u32 {497 COLLECTION_ADMINS_LIMIT498 }499 }500501 #[pallet::event]502 #[pallet::generate_deposit(pub fn deposit_event)]503 pub enum Event<T: Config> {504 /// New collection was created505 CollectionCreated(506 /// Globally unique identifier of newly created collection.507 CollectionId,508 /// [`CollectionMode`] converted into _u8_.509 u8,510 /// Collection owner.511 T::AccountId,512 ),513514 /// New collection was destroyed515 CollectionDestroyed(516 /// Globally unique identifier of collection.517 CollectionId,518 ),519520 /// New item was created.521 ItemCreated(522 /// Id of the collection where item was created.523 CollectionId,524 /// Id of an item. Unique within the collection.525 TokenId,526 /// Owner of newly created item527 T::CrossAccountId,528 /// Always 1 for NFT529 u128,530 ),531532 /// Collection item was burned.533 ItemDestroyed(534 /// Id of the collection where item was destroyed.535 CollectionId,536 /// Identifier of burned NFT.537 TokenId,538 /// Which user has destroyed its tokens.539 T::CrossAccountId,540 /// Amount of token pieces destroed. Always 1 for NFT.541 u128,542 ),543544 /// Item was transferred545 Transfer(546 /// Id of collection to which item is belong.547 CollectionId,548 /// Id of an item.549 TokenId,550 /// Original owner of item.551 T::CrossAccountId,552 /// New owner of item.553 T::CrossAccountId,554 /// Amount of token pieces transfered. Always 1 for NFT.555 u128,556 ),557558 /// Amount pieces of token owned by `sender` was approved for `spender`.559 Approved(560 /// Id of collection to which item is belong.561 CollectionId,562 /// Id of an item.563 TokenId,564 /// Original owner of item.565 T::CrossAccountId,566 /// Id for which the approval was granted.567 T::CrossAccountId,568 /// Amount of token pieces transfered. Always 1 for NFT.569 u128,570 ),571572 /// A `sender` approves operations on all owned tokens for `spender`.573 ApprovedForAll(574 /// Id of collection to which item is belong.575 CollectionId,576 /// Owner of a wallet.577 T::CrossAccountId,578 /// Id for which operator status was granted or rewoked.579 T::CrossAccountId,580 /// Is operator status granted or revoked?581 bool,582 ),583584 /// The colletion property has been added or edited.585 CollectionPropertySet(586 /// Id of collection to which property has been set.587 CollectionId,588 /// The property that was set.589 PropertyKey,590 ),591592 /// The property has been deleted.593 CollectionPropertyDeleted(594 /// Id of collection to which property has been deleted.595 CollectionId,596 /// The property that was deleted.597 PropertyKey,598 ),599600 /// The token property has been added or edited.601 TokenPropertySet(602 /// Identifier of the collection whose token has the property set.603 CollectionId,604 /// The token for which the property was set.605 TokenId,606 /// The property that was set.607 PropertyKey,608 ),609610 /// The token property has been deleted.611 TokenPropertyDeleted(612 /// Identifier of the collection whose token has the property deleted.613 CollectionId,614 /// The token for which the property was deleted.615 TokenId,616 /// The property that was deleted.617 PropertyKey,618 ),619620 /// The token property permission of a collection has been set.621 PropertyPermissionSet(622 /// ID of collection to which property permission has been set.623 CollectionId,624 /// The property permission that was set.625 PropertyKey,626 ),627628 /// Address was added to the allow list.629 AllowListAddressAdded(630 /// ID of the affected collection.631 CollectionId,632 /// Address of the added account.633 T::CrossAccountId,634 ),635636 /// Address was removed from the allow list.637 AllowListAddressRemoved(638 /// ID of the affected collection.639 CollectionId,640 /// Address of the removed account.641 T::CrossAccountId,642 ),643644 /// Collection admin was added.645 CollectionAdminAdded(646 /// ID of the affected collection.647 CollectionId,648 /// Admin address.649 T::CrossAccountId,650 ),651652 /// Collection admin was removed.653 CollectionAdminRemoved(654 /// ID of the affected collection.655 CollectionId,656 /// Removed admin address.657 T::CrossAccountId,658 ),659660 /// Collection limits were set.661 CollectionLimitSet(662 /// ID of the affected collection.663 CollectionId,664 ),665666 /// Collection owned was changed.667 CollectionOwnerChanged(668 /// ID of the affected collection.669 CollectionId,670 /// New owner address.671 T::AccountId,672 ),673674 /// Collection permissions were set.675 CollectionPermissionSet(676 /// ID of the affected collection.677 CollectionId,678 ),679680 /// Collection sponsor was set.681 CollectionSponsorSet(682 /// ID of the affected collection.683 CollectionId,684 /// New sponsor address.685 T::AccountId,686 ),687688 /// New sponsor was confirm.689 SponsorshipConfirmed(690 /// ID of the affected collection.691 CollectionId,692 /// New sponsor address.693 T::AccountId,694 ),695696 /// Collection sponsor was removed.697 CollectionSponsorRemoved(698 /// ID of the affected collection.699 CollectionId,700 ),701 }702703 #[pallet::error]704 pub enum Error<T> {705 /// This collection does not exist.706 CollectionNotFound,707 /// Sender parameter and item owner must be equal.708 MustBeTokenOwner,709 /// No permission to perform action710 NoPermission,711 /// Destroying only empty collections is allowed712 CantDestroyNotEmptyCollection,713 /// Collection is not in mint mode.714 PublicMintingNotAllowed,715 /// Address is not in allow list.716 AddressNotInAllowlist,717718 /// Collection name can not be longer than 63 char.719 CollectionNameLimitExceeded,720 /// Collection description can not be longer than 255 char.721 CollectionDescriptionLimitExceeded,722 /// Token prefix can not be longer than 15 char.723 CollectionTokenPrefixLimitExceeded,724 /// Total collections bound exceeded.725 TotalCollectionsLimitExceeded,726 /// Exceeded max admin count727 CollectionAdminCountExceeded,728 /// Collection limit bounds per collection exceeded729 CollectionLimitBoundsExceeded,730 /// Tried to enable permissions which are only permitted to be disabled731 OwnerPermissionsCantBeReverted,732 /// Collection settings not allowing items transferring733 TransferNotAllowed,734 /// Account token limit exceeded per collection735 AccountTokenLimitExceeded,736 /// Collection token limit exceeded737 CollectionTokenLimitExceeded,738 /// Metadata flag frozen739 MetadataFlagFrozen,740741 /// Item does not exist742 TokenNotFound,743 /// Item is balance not enough744 TokenValueTooLow,745 /// Requested value is more than the approved746 ApprovedValueTooLow,747 /// Tried to approve more than owned748 CantApproveMoreThanOwned,749 /// Only spending from eth mirror could be approved750 AddressIsNotEthMirror,751752 /// Can't transfer tokens to ethereum zero address753 AddressIsZero,754755 /// The operation is not supported756 UnsupportedOperation,757758 /// Insufficient funds to perform an action759 NotSufficientFounds,760761 /// User does not satisfy the nesting rule762 UserIsNotAllowedToNest,763 /// Only tokens from specific collections may nest tokens under this one764 SourceCollectionIsNotAllowedToNest,765766 /// Tried to store more data than allowed in collection field767 CollectionFieldSizeExceeded,768769 /// Tried to store more property data than allowed770 NoSpaceForProperty,771772 /// Tried to store more property keys than allowed773 PropertyLimitReached,774775 /// Property key is too long776 PropertyKeyIsTooLong,777778 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed779 InvalidCharacterInPropertyKey,780781 /// Empty property keys are forbidden782 EmptyPropertyKey,783784 /// Tried to access an external collection with an internal API785 CollectionIsExternal,786787 /// Tried to access an internal collection with an external API788 CollectionIsInternal,789790 /// This address is not set as sponsor, use setCollectionSponsor first.791 ConfirmSponsorshipFail,792793 /// The user is not an administrator.794 UserIsNotCollectionAdmin,795 }796797 /// Storage of the count of created collections. Essentially contains the last collection ID.798 #[pallet::storage]799 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;800801 /// Storage of the count of deleted collections.802 #[pallet::storage]803 pub type DestroyedCollectionCount<T> =804 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;805806 /// Storage of collection info.807 #[pallet::storage]808 pub type CollectionById<T> = StorageMap<809 Hasher = Blake2_128Concat,810 Key = CollectionId,811 Value = Collection<<T as frame_system::Config>::AccountId>,812 QueryKind = OptionQuery,813 >;814815 /// Storage of collection properties.816 #[pallet::storage]817 #[pallet::getter(fn collection_properties)]818 pub type CollectionProperties<T> = StorageMap<819 Hasher = Blake2_128Concat,820 Key = CollectionId,821 Value = Properties,822 QueryKind = ValueQuery,823 OnEmpty = up_data_structs::CollectionProperties,824 >;825826 /// Storage of token property permissions of a collection.827 #[pallet::storage]828 #[pallet::getter(fn property_permissions)]829 pub type CollectionPropertyPermissions<T> = StorageMap<830 Hasher = Blake2_128Concat,831 Key = CollectionId,832 Value = PropertiesPermissionMap,833 QueryKind = ValueQuery,834 >;835836 /// Storage of the amount of collection admins.837 #[pallet::storage]838 pub type AdminAmount<T> = StorageMap<839 Hasher = Blake2_128Concat,840 Key = CollectionId,841 Value = u32,842 QueryKind = ValueQuery,843 >;844845 /// List of collection admins.846 #[pallet::storage]847 pub type IsAdmin<T: Config> = StorageNMap<848 Key = (849 Key<Blake2_128Concat, CollectionId>,850 Key<Blake2_128Concat, T::CrossAccountId>,851 ),852 Value = bool,853 QueryKind = ValueQuery,854 >;855856 /// Allowlisted collection users.857 #[pallet::storage]858 pub type Allowlist<T: Config> = StorageNMap<859 Key = (860 Key<Blake2_128Concat, CollectionId>,861 Key<Blake2_128Concat, T::CrossAccountId>,862 ),863 Value = bool,864 QueryKind = ValueQuery,865 >;866867 /// Not used by code, exists only to provide some types to metadata.868 #[pallet::storage]869 pub type DummyStorageValue<T: Config> = StorageValue<870 Value = (871 CollectionStats,872 CollectionId,873 TokenId,874 TokenChild,875 PhantomType<(876 TokenData<T::CrossAccountId>,877 RpcCollection<T::AccountId>,878 // RMRK879 RmrkCollectionInfo<T::AccountId>,880 RmrkInstanceInfo<T::AccountId>,881 RmrkResourceInfo,882 RmrkPropertyInfo,883 RmrkBaseInfo<T::AccountId>,884 RmrkPartType,885 RmrkBoundedTheme,886 RmrkNftChild,887 // PoV Estimate Info888 PovInfo,889 )>,890 ),891 QueryKind = OptionQuery,892 >;893894 #[pallet::hooks]895 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {896 fn on_runtime_upgrade() -> Weight {897 StorageVersion::new(1).put::<Pallet<T>>();898899 Weight::zero()900 }901 }902}903904impl<T: Config> Pallet<T> {905 /// Enshure that receiver address is correct.906 ///907 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.908 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {909 ensure!(910 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,911 <Error<T>>::AddressIsZero912 );913 Ok(())914 }915916 /// Get a vector of collection admins.917 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {918 <IsAdmin<T>>::iter_prefix((collection,))919 .map(|(a, _)| a)920 .collect()921 }922923 /// Get a vector of users allowed to mint tokens.924 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {925 <Allowlist<T>>::iter_prefix((collection,))926 .map(|(a, _)| a)927 .collect()928 }929930 /// Is `user` allowed to mint token in `collection`.931 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {932 <Allowlist<T>>::get((collection, user))933 }934935 /// Get statistics of collections.936 pub fn collection_stats() -> CollectionStats {937 let created = <CreatedCollectionCount<T>>::get();938 let destroyed = <DestroyedCollectionCount<T>>::get();939 CollectionStats {940 created: created.0,941 destroyed: destroyed.0,942 alive: created.0 - destroyed.0,943 }944 }945946 /// Get the effective limits for the collection.947 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {948 let collection = <CollectionById<T>>::get(collection)?;949 let limits = collection.limits;950 let effective_limits = CollectionLimits {951 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),952 sponsored_data_size: Some(limits.sponsored_data_size()),953 sponsored_data_rate_limit: Some(954 limits955 .sponsored_data_rate_limit956 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),957 ),958 token_limit: Some(limits.token_limit()),959 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(960 match collection.mode {961 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,962 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,963 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,964 },965 )),966 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),967 owner_can_transfer: Some(limits.owner_can_transfer()),968 owner_can_destroy: Some(limits.owner_can_destroy()),969 transfers_enabled: Some(limits.transfers_enabled()),970 };971972 Some(effective_limits)973 }974975 /// Returns information about the `collection` adapted for rpc.976 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {977 let Collection {978 name,979 description,980 owner,981 mode,982 token_prefix,983 sponsorship,984 limits,985 permissions,986 flags,987 } = <CollectionById<T>>::get(collection)?;988989 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)990 .into_iter()991 .map(|(key, permission)| PropertyKeyPermission { key, permission })992 .collect();993994 let properties = <CollectionProperties<T>>::get(collection)995 .into_iter()996 .map(|(key, value)| Property { key, value })997 .collect();998999 let permissions = CollectionPermissions {1000 access: Some(permissions.access()),1001 mint_mode: Some(permissions.mint_mode()),1002 nesting: Some(permissions.nesting().clone()),1003 };10041005 Some(RpcCollection {1006 name: name.into_inner(),1007 description: description.into_inner(),1008 owner,1009 mode,1010 token_prefix: token_prefix.into_inner(),1011 sponsorship,1012 limits,1013 permissions,1014 token_property_permissions,1015 properties,1016 read_only: flags.external,10171018 flags: RpcCollectionFlags {1019 foreign: flags.foreign,1020 erc721metadata: flags.erc721metadata,1021 },1022 })1023 }1024}10251026macro_rules! limit_default {1027 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1028 $(1029 if let Some($new) = $new.$field {1030 let $old = $old.$field($($arg)?);1031 let _ = $new;1032 let _ = $old;1033 $check1034 } else {1035 $new.$field = $old.$field1036 }1037 )*1038 }};1039}1040macro_rules! limit_default_clone {1041 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1042 $(1043 if let Some($new) = $new.$field.clone() {1044 let $old = $old.$field($($arg)?);1045 let _ = $new;1046 let _ = $old;1047 $check1048 } else {1049 $new.$field = $old.$field.clone()1050 }1051 )*1052 }};1053}10541055impl<T: Config> Pallet<T> {1056 /// Create new collection.1057 ///1058 /// * `owner` - The owner of the collection.1059 /// * `data` - Description of the created collection.1060 /// * `flags` - Extra flags to store.1061 pub fn init_collection(1062 owner: T::CrossAccountId,1063 payer: T::CrossAccountId,1064 data: CreateCollectionData<T::AccountId>,1065 flags: CollectionFlags,1066 ) -> Result<CollectionId, DispatchError> {1067 {1068 ensure!(1069 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1070 Error::<T>::CollectionTokenPrefixLimitExceeded1071 );1072 }10731074 let created_count = <CreatedCollectionCount<T>>::get()1075 .01076 .checked_add(1)1077 .ok_or(ArithmeticError::Overflow)?;1078 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1079 let id = CollectionId(created_count);10801081 // bound Total number of collections1082 ensure!(1083 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1084 <Error<T>>::TotalCollectionsLimitExceeded1085 );10861087 // =========10881089 let collection = Collection {1090 owner: owner.as_sub().clone(),1091 name: data.name,1092 mode: data.mode.clone(),1093 description: data.description,1094 token_prefix: data.token_prefix,1095 sponsorship: data1096 .pending_sponsor1097 .map(SponsorshipState::Unconfirmed)1098 .unwrap_or_default(),1099 limits: data1100 .limits1101 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1102 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1103 permissions: data1104 .permissions1105 .map(|permissions| {1106 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1107 })1108 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1109 flags,1110 };11111112 let mut collection_properties = up_data_structs::CollectionProperties::get();1113 collection_properties1114 .try_set_from_iter(data.properties.into_iter())1115 .map_err(<Error<T>>::from)?;11161117 CollectionProperties::<T>::insert(id, collection_properties);11181119 let mut token_props_permissions = PropertiesPermissionMap::new();1120 token_props_permissions1121 .try_set_from_iter(data.token_property_permissions.into_iter())1122 .map_err(<Error<T>>::from)?;11231124 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11251126 // Take a (non-refundable) deposit of collection creation1127 {1128 let mut imbalance =1129 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1130 imbalance.subsume(1131 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1132 &T::TreasuryAccountId::get(),1133 T::CollectionCreationPrice::get(),1134 ),1135 );1136 <T as Config>::Currency::settle(1137 payer.as_sub(),1138 imbalance,1139 WithdrawReasons::TRANSFER,1140 ExistenceRequirement::KeepAlive,1141 )1142 .map_err(|_| Error::<T>::NotSufficientFounds)?;1143 }11441145 <CreatedCollectionCount<T>>::put(created_count);1146 <Pallet<T>>::deposit_event(Event::CollectionCreated(1147 id,1148 data.mode.id(),1149 owner.as_sub().clone(),1150 ));1151 <PalletEvm<T>>::deposit_log(1152 erc::CollectionHelpersEvents::CollectionCreated {1153 owner: *owner.as_eth(),1154 collection_id: eth::collection_id_to_address(id),1155 }1156 .to_log(T::ContractAddress::get()),1157 );1158 <CollectionById<T>>::insert(id, collection);1159 Ok(id)1160 }11611162 /// Destroy collection.1163 ///1164 /// * `collection` - Collection handler.1165 /// * `sender` - The owner or administrator of the collection.1166 pub fn destroy_collection(1167 collection: CollectionHandle<T>,1168 sender: &T::CrossAccountId,1169 ) -> DispatchResult {1170 ensure!(1171 collection.limits.owner_can_destroy(),1172 <Error<T>>::NoPermission,1173 );1174 collection.check_is_owner(sender)?;11751176 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1177 .01178 .checked_add(1)1179 .ok_or(ArithmeticError::Overflow)?;11801181 // =========11821183 <DestroyedCollectionCount<T>>::put(destroyed_collections);1184 <CollectionById<T>>::remove(collection.id);1185 <AdminAmount<T>>::remove(collection.id);1186 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1187 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1188 <CollectionProperties<T>>::remove(collection.id);11891190 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));11911192 <PalletEvm<T>>::deposit_log(1193 erc::CollectionHelpersEvents::CollectionDestroyed {1194 collection_id: eth::collection_id_to_address(collection.id),1195 }1196 .to_log(T::ContractAddress::get()),1197 );1198 Ok(())1199 }12001201 /// Set collection property.1202 ///1203 /// * `collection` - Collection handler.1204 /// * `sender` - The owner or administrator of the collection.1205 /// * `property` - The property to set.1206 pub fn set_collection_property(1207 collection: &CollectionHandle<T>,1208 sender: &T::CrossAccountId,1209 property: Property,1210 ) -> DispatchResult {1211 collection.check_is_owner_or_admin(sender)?;12121213 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1214 let property = property.clone();1215 properties.try_set(property.key, property.value)1216 })1217 .map_err(<Error<T>>::from)?;12181219 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));1220 <PalletEvm<T>>::deposit_log(1221 erc::CollectionHelpersEvents::CollectionChanged {1222 collection_id: eth::collection_id_to_address(collection.id),1223 }1224 .to_log(T::ContractAddress::get()),1225 );12261227 Ok(())1228 }12291230 /// Set a scoped collection property, where the scope is a special prefix1231 /// prohibiting a user access to change the property directly.1232 ///1233 /// * `collection_id` - ID of the collection for which the property is being set.1234 /// * `scope` - Property scope.1235 /// * `property` - The property to set.1236 pub fn set_scoped_collection_property(1237 collection_id: CollectionId,1238 scope: PropertyScope,1239 property: Property,1240 ) -> DispatchResult {1241 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1242 properties.try_scoped_set(scope, property.key, property.value)1243 })1244 .map_err(<Error<T>>::from)?;12451246 Ok(())1247 }12481249 /// Set scoped collection properties, where the scope is a special prefix1250 /// prohibiting a user access to change the properties directly.1251 ///1252 /// * `collection_id` - ID of the collection for which the properties is being set.1253 /// * `scope` - Property scope.1254 /// * `properties` - The properties to set.1255 pub fn set_scoped_collection_properties(1256 collection_id: CollectionId,1257 scope: PropertyScope,1258 properties: impl Iterator<Item = Property>,1259 ) -> DispatchResult {1260 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1261 stored_properties.try_scoped_set_from_iter(scope, properties)1262 })1263 .map_err(<Error<T>>::from)?;12641265 Ok(())1266 }12671268 /// Set collection properties.1269 ///1270 /// * `collection` - Collection handler.1271 /// * `sender` - The owner or administrator of the collection.1272 /// * `properties` - The properties to set.1273 #[transactional]1274 pub fn set_collection_properties(1275 collection: &CollectionHandle<T>,1276 sender: &T::CrossAccountId,1277 properties: Vec<Property>,1278 ) -> DispatchResult {1279 for property in properties {1280 Self::set_collection_property(collection, sender, property)?;1281 }12821283 Ok(())1284 }12851286 /// Delete collection property.1287 ///1288 /// * `collection` - Collection handler.1289 /// * `sender` - The owner or administrator of the collection.1290 /// * `property` - The property to delete.1291 pub fn delete_collection_property(1292 collection: &CollectionHandle<T>,1293 sender: &T::CrossAccountId,1294 property_key: PropertyKey,1295 ) -> DispatchResult {1296 collection.check_is_owner_or_admin(sender)?;12971298 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1299 properties.remove(&property_key)1300 })1301 .map_err(<Error<T>>::from)?;13021303 Self::deposit_event(Event::CollectionPropertyDeleted(1304 collection.id,1305 property_key,1306 ));1307 <PalletEvm<T>>::deposit_log(1308 erc::CollectionHelpersEvents::CollectionChanged {1309 collection_id: eth::collection_id_to_address(collection.id),1310 }1311 .to_log(T::ContractAddress::get()),1312 );13131314 Ok(())1315 }13161317 /// Delete collection properties.1318 ///1319 /// * `collection` - Collection handler.1320 /// * `sender` - The owner or administrator of the collection.1321 /// * `properties` - The properties to delete.1322 #[transactional]1323 pub fn delete_collection_properties(1324 collection: &CollectionHandle<T>,1325 sender: &T::CrossAccountId,1326 property_keys: Vec<PropertyKey>,1327 ) -> DispatchResult {1328 for key in property_keys {1329 Self::delete_collection_property(collection, sender, key)?;1330 }13311332 Ok(())1333 }13341335 /// Set collection propetry permission without any checks.1336 ///1337 /// Used for migrations.1338 ///1339 /// * `collection` - Collection handler.1340 /// * `property_permissions` - Property permissions.1341 pub fn set_property_permission_unchecked(1342 collection: CollectionId,1343 property_permission: PropertyKeyPermission,1344 ) -> DispatchResult {1345 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1346 permissions.try_set(property_permission.key, property_permission.permission)1347 })1348 .map_err(<Error<T>>::from)?;1349 Ok(())1350 }13511352 /// Set collection property permission.1353 ///1354 /// * `collection` - Collection handler.1355 /// * `sender` - The owner or administrator of the collection.1356 /// * `property_permission` - Property permission.1357 pub fn set_property_permission(1358 collection: &CollectionHandle<T>,1359 sender: &T::CrossAccountId,1360 property_permission: PropertyKeyPermission,1361 ) -> DispatchResult {1362 Self::set_scoped_property_permission(1363 collection,1364 sender,1365 PropertyScope::None,1366 property_permission,1367 )1368 }13691370 /// Set collection property permission with scope.1371 ///1372 /// * `collection` - Collection handler.1373 /// * `sender` - The owner or administrator of the collection.1374 /// * `scope` - Property scope.1375 /// * `property_permission` - Property permission.1376 pub fn set_scoped_property_permission(1377 collection: &CollectionHandle<T>,1378 sender: &T::CrossAccountId,1379 scope: PropertyScope,1380 property_permission: PropertyKeyPermission,1381 ) -> DispatchResult {1382 collection.check_is_owner_or_admin(sender)?;13831384 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1385 let current_permission = all_permissions.get(&property_permission.key);1386 if matches![1387 current_permission,1388 Some(PropertyPermission { mutable: false, .. })1389 ] {1390 return Err(<Error<T>>::NoPermission.into());1391 }13921393 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1394 let property_permission = property_permission.clone();1395 permissions.try_scoped_set(1396 scope,1397 property_permission.key,1398 property_permission.permission,1399 )1400 })1401 .map_err(<Error<T>>::from)?;14021403 Self::deposit_event(Event::PropertyPermissionSet(1404 collection.id,1405 property_permission.key,1406 ));1407 <PalletEvm<T>>::deposit_log(1408 erc::CollectionHelpersEvents::CollectionChanged {1409 collection_id: eth::collection_id_to_address(collection.id),1410 }1411 .to_log(T::ContractAddress::get()),1412 );14131414 Ok(())1415 }14161417 /// Set token property permission.1418 ///1419 /// * `collection` - Collection handler.1420 /// * `sender` - The owner or administrator of the collection.1421 /// * `property_permissions` - Property permissions.1422 #[transactional]1423 pub fn set_token_property_permissions(1424 collection: &CollectionHandle<T>,1425 sender: &T::CrossAccountId,1426 property_permissions: Vec<PropertyKeyPermission>,1427 ) -> DispatchResult {1428 Self::set_scoped_token_property_permissions(1429 collection,1430 sender,1431 PropertyScope::None,1432 property_permissions,1433 )1434 }14351436 /// Set token property permission with scope.1437 ///1438 /// * `collection` - Collection handler.1439 /// * `sender` - The owner or administrator of the collection.1440 /// * `scope` - Property scope.1441 /// * `property_permissions` - Property permissions.1442 #[transactional]1443 pub fn set_scoped_token_property_permissions(1444 collection: &CollectionHandle<T>,1445 sender: &T::CrossAccountId,1446 scope: PropertyScope,1447 property_permissions: Vec<PropertyKeyPermission>,1448 ) -> DispatchResult {1449 for prop_pemission in property_permissions {1450 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1451 }14521453 Ok(())1454 }14551456 /// Get collection property.1457 pub fn get_collection_property(1458 collection_id: CollectionId,1459 key: &PropertyKey,1460 ) -> Option<PropertyValue> {1461 Self::collection_properties(collection_id).get(key).cloned()1462 }14631464 /// Convert byte vector to property key vector.1465 pub fn bytes_keys_to_property_keys(1466 keys: Vec<Vec<u8>>,1467 ) -> Result<Vec<PropertyKey>, DispatchError> {1468 keys.into_iter()1469 .map(|key| -> Result<PropertyKey, DispatchError> {1470 key.try_into()1471 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1472 })1473 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1474 }14751476 /// Get properties according to given keys.1477 pub fn filter_collection_properties(1478 collection_id: CollectionId,1479 keys: Option<Vec<PropertyKey>>,1480 ) -> Result<Vec<Property>, DispatchError> {1481 let properties = Self::collection_properties(collection_id);14821483 let properties = keys1484 .map(|keys| {1485 keys.into_iter()1486 .filter_map(|key| {1487 properties.get(&key).map(|value| Property {1488 key,1489 value: value.clone(),1490 })1491 })1492 .collect()1493 })1494 .unwrap_or_else(|| {1495 properties1496 .into_iter()1497 .map(|(key, value)| Property { key, value })1498 .collect()1499 });15001501 Ok(properties)1502 }15031504 /// Get property permissions according to given keys.1505 pub fn filter_property_permissions(1506 collection_id: CollectionId,1507 keys: Option<Vec<PropertyKey>>,1508 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1509 let permissions = Self::property_permissions(collection_id);15101511 let key_permissions = keys1512 .map(|keys| {1513 keys.into_iter()1514 .filter_map(|key| {1515 permissions1516 .get(&key)1517 .map(|permission| PropertyKeyPermission {1518 key,1519 permission: permission.clone(),1520 })1521 })1522 .collect()1523 })1524 .unwrap_or_else(|| {1525 permissions1526 .into_iter()1527 .map(|(key, permission)| PropertyKeyPermission { key, permission })1528 .collect()1529 });15301531 Ok(key_permissions)1532 }15331534 /// Toggle `user` participation in the `collection`'s allow list.1535 /// #### Store read/writes1536 /// 1 writes1537 pub fn toggle_allowlist(1538 collection: &CollectionHandle<T>,1539 sender: &T::CrossAccountId,1540 user: &T::CrossAccountId,1541 allowed: bool,1542 ) -> DispatchResult {1543 collection.check_is_owner_or_admin(sender)?;15441545 // =========15461547 if allowed {1548 <Allowlist<T>>::insert((collection.id, user), true);1549 Self::deposit_event(Event::<T>::AllowListAddressAdded(1550 collection.id,1551 user.clone(),1552 ));1553 } else {1554 <Allowlist<T>>::remove((collection.id, user));1555 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1556 collection.id,1557 user.clone(),1558 ));1559 }15601561 <PalletEvm<T>>::deposit_log(1562 erc::CollectionHelpersEvents::CollectionChanged {1563 collection_id: eth::collection_id_to_address(collection.id),1564 }1565 .to_log(T::ContractAddress::get()),1566 );15671568 Ok(())1569 }15701571 /// Toggle `user` participation in the `collection`'s admin list.1572 /// #### Store read/writes1573 /// 2 reads, 2 writes1574 pub fn toggle_admin(1575 collection: &CollectionHandle<T>,1576 sender: &T::CrossAccountId,1577 user: &T::CrossAccountId,1578 admin: bool,1579 ) -> DispatchResult {1580 collection.check_is_internal()?;1581 collection.check_is_owner(sender)?;15821583 let is_admin = <IsAdmin<T>>::get((collection.id, user));1584 if is_admin == admin {1585 if admin {1586 return Ok(());1587 } else {1588 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1589 }1590 }1591 let amount = <AdminAmount<T>>::get(collection.id);15921593 // =========15941595 if admin {1596 let amount = amount1597 .checked_add(1)1598 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1599 ensure!(1600 amount <= Self::collection_admins_limit(),1601 <Error<T>>::CollectionAdminCountExceeded,1602 );16031604 <AdminAmount<T>>::insert(collection.id, amount);1605 <IsAdmin<T>>::insert((collection.id, user), true);16061607 Self::deposit_event(Event::<T>::CollectionAdminAdded(1608 collection.id,1609 user.clone(),1610 ));1611 } else {1612 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1613 <IsAdmin<T>>::remove((collection.id, user));16141615 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1616 collection.id,1617 user.clone(),1618 ));1619 }16201621 <PalletEvm<T>>::deposit_log(1622 erc::CollectionHelpersEvents::CollectionChanged {1623 collection_id: eth::collection_id_to_address(collection.id),1624 }1625 .to_log(T::ContractAddress::get()),1626 );16271628 Ok(())1629 }16301631 /// Update collection limits.1632 pub fn update_limits(1633 user: &T::CrossAccountId,1634 collection: &mut CollectionHandle<T>,1635 new_limit: CollectionLimits,1636 ) -> DispatchResult {1637 collection.check_is_internal()?;1638 collection.check_is_owner_or_admin(user)?;16391640 collection.limits =1641 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16421643 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1644 <PalletEvm<T>>::deposit_log(1645 erc::CollectionHelpersEvents::CollectionChanged {1646 collection_id: eth::collection_id_to_address(collection.id),1647 }1648 .to_log(T::ContractAddress::get()),1649 );16501651 collection.save()1652 }16531654 /// Merge set fields from `new_limit` to `old_limit`.1655 fn clamp_limits(1656 mode: CollectionMode,1657 old_limit: &CollectionLimits,1658 mut new_limit: CollectionLimits,1659 ) -> Result<CollectionLimits, DispatchError> {1660 let limits = old_limit;1661 limit_default!(old_limit, new_limit,1662 account_token_ownership_limit => ensure!(1663 new_limit <= MAX_TOKEN_OWNERSHIP,1664 <Error<T>>::CollectionLimitBoundsExceeded,1665 ),1666 sponsored_data_size => ensure!(1667 new_limit <= CUSTOM_DATA_LIMIT,1668 <Error<T>>::CollectionLimitBoundsExceeded,1669 ),16701671 sponsored_data_rate_limit => {},1672 token_limit => ensure!(1673 old_limit >= new_limit && new_limit > 0,1674 <Error<T>>::CollectionTokenLimitExceeded1675 ),16761677 sponsor_transfer_timeout(match mode {1678 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1679 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1680 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1681 }) => ensure!(1682 new_limit <= MAX_SPONSOR_TIMEOUT,1683 <Error<T>>::CollectionLimitBoundsExceeded,1684 ),1685 sponsor_approve_timeout => {},1686 owner_can_transfer => ensure!(1687 !limits.owner_can_transfer_instaled() ||1688 old_limit || !new_limit,1689 <Error<T>>::OwnerPermissionsCantBeReverted,1690 ),1691 owner_can_destroy => ensure!(1692 old_limit || !new_limit,1693 <Error<T>>::OwnerPermissionsCantBeReverted,1694 ),1695 transfers_enabled => {},1696 );1697 Ok(new_limit)1698 }16991700 /// Update collection permissions.1701 pub fn update_permissions(1702 user: &T::CrossAccountId,1703 collection: &mut CollectionHandle<T>,1704 new_permission: CollectionPermissions,1705 ) -> DispatchResult {1706 collection.check_is_internal()?;1707 collection.check_is_owner_or_admin(user)?;1708 collection.permissions = Self::clamp_permissions(1709 collection.mode.clone(),1710 &collection.permissions,1711 new_permission,1712 )?;17131714 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1715 <PalletEvm<T>>::deposit_log(1716 erc::CollectionHelpersEvents::CollectionChanged {1717 collection_id: eth::collection_id_to_address(collection.id),1718 }1719 .to_log(T::ContractAddress::get()),1720 );17211722 collection.save()1723 }17241725 /// Merge set fields from `new_permission` to `old_permission`.1726 fn clamp_permissions(1727 _mode: CollectionMode,1728 old_permission: &CollectionPermissions,1729 mut new_permission: CollectionPermissions,1730 ) -> Result<CollectionPermissions, DispatchError> {1731 limit_default_clone!(old_permission, new_permission,1732 access => {},1733 mint_mode => {},1734 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1735 );1736 Ok(new_permission)1737 }17381739 /// Repair possibly broken properties of a collection.1740 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1741 CollectionProperties::<T>::mutate(collection_id, |properties| {1742 properties.recompute_consumed_space();1743 });17441745 Ok(())1746 }1747}17481749/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1750#[macro_export]1751macro_rules! unsupported {1752 ($runtime:path) => {1753 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1754 };1755}17561757/// Return weights for various worst-case operations.1758pub trait CommonWeightInfo<CrossAccountId> {1759 /// Weight of item creation.1760 fn create_item() -> Weight;17611762 /// Weight of items creation.1763 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17641765 /// Weight of items creation.1766 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17671768 /// The weight of the burning item.1769 fn burn_item() -> Weight;17701771 /// Property setting weight.1772 ///1773 /// * `amount`- The number of properties to set.1774 fn set_collection_properties(amount: u32) -> Weight;17751776 /// Collection property deletion weight.1777 ///1778 /// * `amount`- The number of properties to set.1779 fn delete_collection_properties(amount: u32) -> Weight;17801781 /// Token property setting weight.1782 ///1783 /// * `amount`- The number of properties to set.1784 fn set_token_properties(amount: u32) -> Weight;17851786 /// Token property deletion weight.1787 ///1788 /// * `amount`- The number of properties to delete.1789 fn delete_token_properties(amount: u32) -> Weight;17901791 /// Token property permissions set weight.1792 ///1793 /// * `amount`- The number of property permissions to set.1794 fn set_token_property_permissions(amount: u32) -> Weight;17951796 /// Transfer price of the token or its parts.1797 fn transfer() -> Weight;17981799 /// The price of setting the permission of the operation from another user.1800 fn approve() -> Weight;18011802 /// The price of setting the permission of the operation from another user for eth mirror.1803 fn approve_from() -> Weight;18041805 /// Transfer price from another user.1806 fn transfer_from() -> Weight;18071808 /// The price of burning a token from another user.1809 fn burn_from() -> Weight;18101811 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1812 /// whole users's balance.1813 ///1814 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1815 fn burn_recursively_self_raw() -> Weight;18161817 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1818 ///1819 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1820 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18211822 /// The price of recursive burning a token.1823 ///1824 /// `max_selfs` - The maximum burning weight of the token itself.1825 /// `max_breadth` - The maximum number of nested tokens to burn.1826 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1827 Self::burn_recursively_self_raw()1828 .saturating_mul(max_selfs.max(1) as u64)1829 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1830 }18311832 /// The price of retrieving token owner1833 fn token_owner() -> Weight;18341835 /// The price of setting approval for all1836 fn set_allowance_for_all() -> Weight;18371838 /// The price of repairing an item.1839 fn force_repair_item() -> Weight;1840}18411842/// Weight info extension trait for refungible pallet.1843pub trait RefungibleExtensionsWeightInfo {1844 /// Weight of token repartition.1845 fn repartition() -> Weight;1846}18471848/// Common collection operations.1849///1850/// It wraps methods in Fungible, Nonfungible and Refungible pallets1851/// and adds weight info.1852pub trait CommonCollectionOperations<T: Config> {1853 /// Create token.1854 ///1855 /// * `sender` - The user who mint the token and pays for the transaction.1856 /// * `to` - The user who will own the token.1857 /// * `data` - Token data.1858 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1859 fn create_item(1860 &self,1861 sender: T::CrossAccountId,1862 to: T::CrossAccountId,1863 data: CreateItemData,1864 nesting_budget: &dyn Budget,1865 ) -> DispatchResultWithPostInfo;18661867 /// Create multiple tokens.1868 ///1869 /// * `sender` - The user who mint the token and pays for the transaction.1870 /// * `to` - The user who will own the token.1871 /// * `data` - Token data.1872 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1873 fn create_multiple_items(1874 &self,1875 sender: T::CrossAccountId,1876 to: T::CrossAccountId,1877 data: Vec<CreateItemData>,1878 nesting_budget: &dyn Budget,1879 ) -> DispatchResultWithPostInfo;18801881 /// Create multiple tokens.1882 ///1883 /// * `sender` - The user who mint the token and pays for the transaction.1884 /// * `to` - The user who will own the token.1885 /// * `data` - Token data.1886 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1887 fn create_multiple_items_ex(1888 &self,1889 sender: T::CrossAccountId,1890 data: CreateItemExData<T::CrossAccountId>,1891 nesting_budget: &dyn Budget,1892 ) -> DispatchResultWithPostInfo;18931894 /// Burn token.1895 ///1896 /// * `sender` - The user who owns the token.1897 /// * `token` - Token id that will burned.1898 /// * `amount` - The number of parts of the token that will be burned.1899 fn burn_item(1900 &self,1901 sender: T::CrossAccountId,1902 token: TokenId,1903 amount: u128,1904 ) -> DispatchResultWithPostInfo;19051906 /// Burn token and all nested tokens recursievly.1907 ///1908 /// * `sender` - The user who owns the token.1909 /// * `token` - Token id that will burned.1910 /// * `self_budget` - The budget that can be spent on burning tokens.1911 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1912 fn burn_item_recursively(1913 &self,1914 sender: T::CrossAccountId,1915 token: TokenId,1916 self_budget: &dyn Budget,1917 breadth_budget: &dyn Budget,1918 ) -> DispatchResultWithPostInfo;19191920 /// Set collection properties.1921 ///1922 /// * `sender` - Must be either the owner of the collection or its admin.1923 /// * `properties` - Properties to be set.1924 fn set_collection_properties(1925 &self,1926 sender: T::CrossAccountId,1927 properties: Vec<Property>,1928 ) -> DispatchResultWithPostInfo;19291930 /// Delete collection properties.1931 ///1932 /// * `sender` - Must be either the owner of the collection or its admin.1933 /// * `properties` - The properties to be removed.1934 fn delete_collection_properties(1935 &self,1936 sender: &T::CrossAccountId,1937 property_keys: Vec<PropertyKey>,1938 ) -> DispatchResultWithPostInfo;19391940 /// Set token properties.1941 ///1942 /// The appropriate [`PropertyPermission`] for the token property1943 /// must be set with [`Self::set_token_property_permissions`].1944 ///1945 /// * `sender` - Must be either the owner of the token or its admin.1946 /// * `token_id` - The token for which the properties are being set.1947 /// * `properties` - Properties to be set.1948 /// * `budget` - Budget for setting properties.1949 fn set_token_properties(1950 &self,1951 sender: T::CrossAccountId,1952 token_id: TokenId,1953 properties: Vec<Property>,1954 budget: &dyn Budget,1955 ) -> DispatchResultWithPostInfo;19561957 /// Remove token properties.1958 ///1959 /// The appropriate [`PropertyPermission`] for the token property1960 /// must be set with [`Self::set_token_property_permissions`].1961 ///1962 /// * `sender` - Must be either the owner of the token or its admin.1963 /// * `token_id` - The token for which the properties are being remove.1964 /// * `property_keys` - Keys to remove corresponding properties.1965 /// * `budget` - Budget for removing properties.1966 fn delete_token_properties(1967 &self,1968 sender: T::CrossAccountId,1969 token_id: TokenId,1970 property_keys: Vec<PropertyKey>,1971 budget: &dyn Budget,1972 ) -> DispatchResultWithPostInfo;19731974 /// Set token property permissions.1975 ///1976 /// * `sender` - Must be either the owner of the token or its admin.1977 /// * `token_id` - The token for which the properties are being set.1978 /// * `property_permissions` - Property permissions to be set.1979 /// * `budget` - Budget for setting properties.1980 fn set_token_property_permissions(1981 &self,1982 sender: &T::CrossAccountId,1983 property_permissions: Vec<PropertyKeyPermission>,1984 ) -> DispatchResultWithPostInfo;19851986 /// Transfer amount of token pieces.1987 ///1988 /// * `sender` - Donor user.1989 /// * `to` - Recepient user.1990 /// * `token` - The token of which parts are being sent.1991 /// * `amount` - The number of parts of the token that will be transferred.1992 /// * `budget` - The maximum budget that can be spent on the transfer.1993 fn transfer(1994 &self,1995 sender: T::CrossAccountId,1996 to: T::CrossAccountId,1997 token: TokenId,1998 amount: u128,1999 budget: &dyn Budget,2000 ) -> DispatchResultWithPostInfo;20012002 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2003 ///2004 /// * `sender` - The user who grants access to the token.2005 /// * `spender` - The user to whom the rights are granted.2006 /// * `token` - The token to which access is granted.2007 /// * `amount` - The amount of pieces that another user can dispose of.2008 fn approve(2009 &self,2010 sender: T::CrossAccountId,2011 spender: T::CrossAccountId,2012 token: TokenId,2013 amount: u128,2014 ) -> DispatchResultWithPostInfo;20152016 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2017 ///2018 /// * `sender` - The user who grants access to the token.2019 /// * `from` - Spender's eth mirror.2020 /// * `to` - The user to whom the rights are granted.2021 /// * `token` - The token to which access is granted.2022 /// * `amount` - The amount of pieces that another user can dispose of.2023 fn approve_from(2024 &self,2025 sender: T::CrossAccountId,2026 from: T::CrossAccountId,2027 to: T::CrossAccountId,2028 token: TokenId,2029 amount: u128,2030 ) -> DispatchResultWithPostInfo;20312032 /// Send parts of a token owned by another user.2033 ///2034 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2035 ///2036 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2037 /// * `from` - The user who owns the token.2038 /// * `to` - Recepient user.2039 /// * `token` - The token of which parts are being sent.2040 /// * `amount` - The number of parts of the token that will be transferred.2041 /// * `budget` - The maximum budget that can be spent on the transfer.2042 fn transfer_from(2043 &self,2044 sender: T::CrossAccountId,2045 from: T::CrossAccountId,2046 to: T::CrossAccountId,2047 token: TokenId,2048 amount: u128,2049 budget: &dyn Budget,2050 ) -> DispatchResultWithPostInfo;20512052 /// Burn parts of a token owned by another user.2053 ///2054 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2055 ///2056 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2057 /// * `from` - The user who owns the token.2058 /// * `token` - The token of which parts are being sent.2059 /// * `amount` - The number of parts of the token that will be transferred.2060 /// * `budget` - The maximum budget that can be spent on the burn.2061 fn burn_from(2062 &self,2063 sender: T::CrossAccountId,2064 from: T::CrossAccountId,2065 token: TokenId,2066 amount: u128,2067 budget: &dyn Budget,2068 ) -> DispatchResultWithPostInfo;20692070 /// Check permission to nest token.2071 ///2072 /// * `sender` - The user who initiated the check.2073 /// * `from` - The token that is checked for embedding.2074 /// * `under` - Token under which to check.2075 /// * `budget` - The maximum budget that can be spent on the check.2076 fn check_nesting(2077 &self,2078 sender: T::CrossAccountId,2079 from: (CollectionId, TokenId),2080 under: TokenId,2081 budget: &dyn Budget,2082 ) -> DispatchResult;20832084 /// Nest one token into another.2085 ///2086 /// * `under` - Token holder.2087 /// * `to_nest` - Nested token.2088 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20892090 /// Unnest token.2091 ///2092 /// * `under` - Token holder.2093 /// * `to_nest` - Token to unnest.2094 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));20952096 /// Get all user tokens.2097 ///2098 /// * `account` - Account for which you need to get tokens.2099 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;21002101 /// Get all the tokens in the collection.2102 fn collection_tokens(&self) -> Vec<TokenId>;21032104 /// Check if the token exists.2105 ///2106 /// * `token` - Id token to check.2107 fn token_exists(&self, token: TokenId) -> bool;21082109 /// Get the id of the last minted token.2110 fn last_token_id(&self) -> TokenId;21112112 /// Get the owner of the token.2113 ///2114 /// * `token` - The token for which you need to find out the owner.2115 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;21162117 /// Returns 10 tokens owners in no particular order.2118 ///2119 /// * `token` - The token for which you need to find out the owners.2120 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21212122 /// Get the value of the token property by key.2123 ///2124 /// * `token` - Token with the property to get.2125 /// * `key` - Property name.2126 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21272128 /// Get a set of token properties by key vector.2129 ///2130 /// * `token` - Token with the property to get.2131 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2132 /// then all properties are returned.2133 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21342135 /// Amount of unique collection tokens2136 fn total_supply(&self) -> u32;21372138 /// Amount of different tokens account has.2139 ///2140 /// * `account` - The account for which need to get the balance.2141 fn account_balance(&self, account: T::CrossAccountId) -> u32;21422143 /// Amount of specific token account have.2144 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21452146 /// Amount of token pieces2147 fn total_pieces(&self, token: TokenId) -> Option<u128>;21482149 /// Get the number of parts of the token that a trusted user can manage.2150 ///2151 /// * `sender` - Trusted user.2152 /// * `spender` - Owner of the token.2153 /// * `token` - The token for which to get the value.2154 fn allowance(2155 &self,2156 sender: T::CrossAccountId,2157 spender: T::CrossAccountId,2158 token: TokenId,2159 ) -> u128;21602161 /// Get extension for RFT collection.2162 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21632164 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2165 /// * `owner` - Token owner2166 /// * `operator` - Operator2167 /// * `approve` - Should operator status be granted or revoked?2168 fn set_allowance_for_all(2169 &self,2170 owner: T::CrossAccountId,2171 operator: T::CrossAccountId,2172 approve: bool,2173 ) -> DispatchResultWithPostInfo;21742175 /// Tells whether the given `owner` approves the `operator`.2176 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;21772178 /// Repairs a possibly broken item.2179 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2180}21812182/// Extension for RFT collection.2183pub trait RefungibleExtensions<T>2184where2185 T: Config,2186{2187 /// Change the number of parts of the token.2188 ///2189 /// When the value changes down, this function is equivalent to burning parts of the token.2190 ///2191 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2192 /// * `token` - The token for which you want to change the number of parts.2193 /// * `amount` - The new value of the parts of the token.2194 fn repartition(2195 &self,2196 sender: &T::CrossAccountId,2197 token: TokenId,2198 amount: u128,2199 ) -> DispatchResultWithPostInfo;2200}22012202/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2203///2204/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2205pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2206 let post_info = PostDispatchInfo {2207 actual_weight: Some(weight),2208 pays_fee: Pays::Yes,2209 };2210 match res {2211 Ok(()) => Ok(post_info),2212 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2213 }2214}22152216impl<T: Config> From<PropertiesError> for Error<T> {2217 fn from(error: PropertiesError) -> Self {2218 match error {2219 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2220 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2221 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2222 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2223 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2224 }2225 }2226}pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -283,8 +283,8 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -82,6 +82,16 @@
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ <Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, 100)?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -87,6 +87,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -254,6 +258,25 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -613,6 +613,45 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.
+ ///
+ /// - `collection`: Collection that contains the token
+ /// - `sender`: Owner of tokens that sets the allowance.
+ /// - `from`: Owner's eth mirror.
+ /// - `to`: Recipient of the allowance rights.
+ /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, amount);
+ Ok(())
+ }
+
/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
///
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -39,6 +39,7 @@
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
}
@@ -84,6 +85,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
@@ -141,6 +149,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -134,6 +134,15 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, owner_eth.clone())?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, item, Some(&spender))?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -102,6 +102,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -353,6 +357,26 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ with_weight(
+ if amount == 1 {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, Some(&to))
+ } else {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, None)
+ },
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1171,6 +1171,51 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `token`: Token the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ token: TokenId,
+ to: Option<&T::CrossAccountId>,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ if let Some(to) = to {
+ collection.check_allowlist(to)?;
+ }
+ }
+
+ if let Some(to) = to {
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ if token_data.owner != *from {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, token, to, false);
+ Ok(())
+ }
+
/// Checks allowance for the spender to use the token.
fn check_allowed(
collection: &NonfungibleHandle<T>,
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -42,6 +42,7 @@
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
fn set_token_property_permissions(b: u32, ) -> Weight;
@@ -147,6 +148,13 @@
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
@@ -310,6 +318,13 @@
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -163,6 +163,15 @@
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, [(owner_eth.clone(), 200)])?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, item, 100)?}
+
transfer_from_normal {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -127,6 +127,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
max_weight_of!(
transfer_from_normal(),
@@ -314,6 +318,20 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, token_id, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1102,6 +1102,47 @@
Ok(())
}
+ /// Set allowance to spend from sender's eth mirror
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.
+ pub fn set_allowance_for(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, token_id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))
+ && Self::token_exists(collection, token_id),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, token_id, amount);
+ Ok(())
+ }
+
/// Returns allowance, which should be set after transaction
fn check_allowed(
collection: &RefungibleHandle<T>,
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -45,6 +45,7 @@
fn transfer_removing() -> Weight;
fn transfer_creating_removing() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from_normal() -> Weight;
fn transfer_from_creating() -> Weight;
fn transfer_from_removing() -> Weight;
@@ -175,6 +176,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
@@ -400,6 +408,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -851,6 +851,29 @@
dispatch_tx::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))
}
+ /// Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+ ///
+ /// # Permissions
+ ///
+ /// * Collection owner
+ /// * Collection admin
+ /// * Current item owner
+ ///
+ /// # Arguments
+ ///
+ /// * `from`: Owner's account eth mirror
+ /// * `to`: Account to be approved to make specific transactions on non-owned tokens.
+ /// * `collection_id`: ID of the collection the item belongs to.
+ /// * `item_id`: ID of the item transactions on which are now approved.
+ /// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+ /// Set to 0 to revoke the approval.
+ #[weight = T::CommonWeightInfo::approve_from()]
+ pub fn approve_from(origin, from:T::CrossAccountId, to: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {
+ let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+
+ dispatch_tx::<T, _>(collection_id, |d| d.approve_from(sender, from, to, item_id, amount))
+ }
+
/// Change ownership of an item on behalf of the owner as a non-owner account.
///
/// See the [`approve`][`Pallet::approve`] method for additional information.
runtime/common/identity.rsdiffbeforeafterboth--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -21,9 +21,7 @@
use sp_runtime::{
traits::{DispatchInfoOf, SignedExtension},
- transaction_validity::{
- TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
- },
+ transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
};
#[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -101,6 +101,10 @@
dispatch_weight::<T>() + max_weight_of!(approve())
}
+ fn approve_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(approve_from())
+ }
+
fn transfer_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(transfer_from())
}
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -16,336 +16,521 @@
import {IKeyringPair} from '@polkadot/types/types';
import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {CrossAccountId} from './util/playgrounds/unique';
+
-describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+[
+ {method: 'approveToken', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account)},
+ {method: 'approveTokenFromEth', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account).toEthereum()},
+].map(testCase => {
+ describe(`Integration Test ${testCase.method}(spender, collection_id, item_id, amount):`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
});
- });
- itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- });
+ itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ });
+
+ itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amount).to.be.equal(BigInt(1));
+ });
+
+ itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amount).to.be.equal(BigInt(1));
+ });
+
+ itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const collectionId = collection.collectionId;
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+ });
- itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
- itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+ });
- itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const collectionId = collection.collectionId;
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
- });
+ itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
- itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+ });
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ const result = (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(result).to.be.rejected;
+ });
});
- itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] Normal user can approve other users to transfer:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
- });
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTokenTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTokenTx()).to.be.rejected;
- });
-});
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
+ });
-describe('Normal user can approve other users to transfer:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+ expect(amount).to.be.equal(BigInt(1));
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+ const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+ expect(amount).to.be.equal(BigInt(100n));
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
- });
+ describe(`[${testCase.method}] Approved users can transferFrom up to approved amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
- const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
- expect(amount).to.be.equal(BigInt(100n));
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+ expect(owner.Substrate).to.be.equal(alice.address);
+ });
+
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+ });
+
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+ });
});
-});
-describe('Approved users can transferFrom up to approved amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ describe(`[${testCase.method}] Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+ expect(owner.Substrate).to.be.equal(alice.address);
+ const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+
+ const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+ const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+ const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(100));
+ const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+ await expect(transferTokenFromTx()).to.be.rejected;
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
- expect(owner.Substrate).to.be.equal(alice.address);
+ describe(`[${testCase.method}] Approved amount decreases by the transferred amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+ let dave: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+
+ const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+ await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: charlie.address}, 2n);
+ const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+ expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+
+ const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+ await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: dave.address}, 8n);
+ const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+ expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
+ });
});
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] User may clear the approvals to approving for 0 amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+ const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub('Fungible', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
+
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+
+ const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
+
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+
+ const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
});
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] User cannot approve for the amount greater than they own:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('1 for NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 2n);
+ await expect(result).to.be.rejected;
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
+ });
+
+ itSub('Fungible', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ const result = (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
+ await expect(result).to.be.rejected;
+ });
+
+ itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ const result = (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
+ await expect(result).to.be.rejected;
+ });
});
-});
-describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ describe(`[${testCase.method}] Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub('can be called by collection admin on non-owned item', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
+ const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(result).to.be.rejected;
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
- expect(owner.Substrate).to.be.equal(alice.address);
- const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ describe(`[${testCase.method}] Negative Integration Test approve(spender, collection_id, item_id, amount):`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ await expect((helper.nft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address})).to.be.rejected;
+ });
+
+ itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
- const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
- const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(100));
- const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
-});
+ itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
-describe('Approved amount decreases by the transferred amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
- let dave: IKeyringPair;
+ itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.nft.burn(alice, collectionId);
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+ itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.burn(alice, collectionId);
+ const approveTx = () => (helper.ft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
});
- });
- itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+ itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.rft.burn(alice, collectionId);
+ const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
- await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: charlie.address}, 2n);
- const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
- expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+ itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
- await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: dave.address}, 8n);
- const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
- expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
- });
-});
+ itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
-describe('User may clear the approvals to approving for 0 amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ const approveTx = () => (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
});
- });
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
- const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- itSub('Fungible', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
+ await helper.rft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 100n);
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
+ await expect(approveTx()).to.be.rejected;
+ });
- const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
- itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ await helper.ft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 10n);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
+ await expect(approveTx()).to.be.rejected;
+ });
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
- const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
- await expect(transferTokenFromTx()).to.be.rejected;
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
});
});
-describe('User cannot approve for the amount greater than they own:', () => {
+describe('Normal user can approve other users to be wallet operator:', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
- let charlie: IKeyringPair;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
});
});
- itSub('1 for NFT', async ({helper}) => {
+ itSub('[nft] Enable and disable approval', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTx = () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
- await expect(approveTx()).to.be.rejected;
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
- });
- itSub('Fungible', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- const approveTx = () => helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
- await expect(approveTx()).to.be.rejected;
+ const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkBeforeApproval).to.be.false;
+
+ await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+ const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterApproval).to.be.true;
+
+ await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+ const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterDisapproval).to.be.false;
});
- itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- const approveTx = () => helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
- await expect(approveTx()).to.be.rejected;
+
+ const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkBeforeApproval).to.be.false;
+
+ await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+ const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterApproval).to.be.true;
+
+ await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+ const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterDisapproval).to.be.false;
});
});
@@ -464,184 +649,5 @@
await token.approve(dave, {Substrate: bob.address}, 50n);
await expect(token.approve(dave, {Substrate: charlie.address}, 51n))
.to.be.rejectedWith('this test would fail (since it is skipped), replace this expecting message with what would have been received');
- });
-});
-
-describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
- });
- });
-
- itSub('can be called by collection admin on non-owned item', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
- const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-});
-
-describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
- });
- });
-
- itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.nft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.ft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.rft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.nft.burn(alice, collectionId);
- const approveTx = () => helper.nft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.burn(alice, collectionId);
- const approveTx = () => helper.ft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.rft.burn(alice, collectionId);
- const approveTx = () => helper.rft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const approveTx = () => helper.nft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const approveTx = () => helper.rft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 100n);
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
-
- const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
-
- await helper.ft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
- const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
-
- const approveTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-});
-
-describe('Normal user can approve other users to be wallet operator:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
- });
- });
-
- itSub('[nft] Enable and disable approval', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
- const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkBeforeApproval).to.be.false;
-
- await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
- const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterApproval).to.be.true;
-
- await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
- const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterDisapproval).to.be.false;
- });
-
- itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
- const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkBeforeApproval).to.be.false;
-
- await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
- const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterApproval).to.be.true;
-
- await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
- const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterDisapproval).to.be.false;
});
});
tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -183,9 +183,9 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -85,6 +85,10 @@
**/
AccountTokenLimitExceeded: AugmentedError<ApiType>;
/**
+ * Only spending from eth mirror could be approved
+ **/
+ AddressIsNotEthMirror: AugmentedError<ApiType>;
+ /**
* Can't transfer tokens to ethereum zero address
**/
AddressIsZero: AugmentedError<ApiType>;
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1214,6 +1214,25 @@
**/
approve: AugmentedSubmittable<(spender: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
/**
+ * Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+ *
+ * # Permissions
+ *
+ * * Collection owner
+ * * Collection admin
+ * * Current item owner
+ *
+ * # Arguments
+ *
+ * * `from`: Owner's account eth mirror
+ * * `to`: Account to be approved to make specific transactions on non-owned tokens.
+ * * `collection_id`: ID of the collection the item belongs to.
+ * * `item_id`: ID of the item transactions on which are now approved.
+ * * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+ * Set to 0 to revoke the approval.
+ **/
+ approveFrom: AugmentedSubmittable<(from: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, to: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
+ /**
* Destroy a token on behalf of the owner as a non-owner account.
*
* See also: [`approve`][`Pallet::approve`].
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1216,6 +1216,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -1231,7 +1232,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletCommonEvent */
@@ -2306,6 +2307,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2345,7 +2354,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name PalletUniqueError */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2264,6 +2264,13 @@
itemId: 'u32',
amount: 'u128',
},
+ approve_from: {
+ from: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ to: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ collectionId: 'u32',
+ itemId: 'u32',
+ amount: 'u128',
+ },
transfer_from: {
from: 'PalletEvmAccountBasicCrossAccountIdRepr',
recipient: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3280,7 +3287,7 @@
* Lookup423: pallet_common::pallet::Error<T>
**/
PalletCommonError: {
- _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
+ _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
},
/**
* Lookup425: pallet_fungible::pallet::Error<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2493,6 +2493,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2532,7 +2540,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name UpDataStructsCollectionMode (236) */
@@ -3564,6 +3572,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -3579,7 +3588,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletFungibleError (425) */
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -633,6 +633,10 @@
let call = this.getApi() as any;
for(const part of apiCall.slice(4).split('.')) {
call = call[part];
+ if (!call) {
+ const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';
+ throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);
+ }
}
return call(...params);
}
@@ -1259,6 +1263,42 @@
}
/**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param fromAddressObj Signer's Ethereum address containing her tokens
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
+ const approveResult = await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],
+ true, // `Unable to approve token for ${label}`,
+ );
+
+ return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');
+ }
+
+ /**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();
+ return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);
+ }
+
+ /**
* Get the amount of token pieces approved to transfer or burn. Normally 0.
*
* @param collectionId ID of collection
@@ -1756,8 +1796,8 @@
* @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
- approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {
- return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);
+ approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);
}
}