difftreelog
Merge pull request #869 from UniqueNetwork/feature/generalize_2_methods
in: master
Feature/generalize_2_methods
34 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6361,7 +6361,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
dependencies = [
"evm-coder",
"frame-benchmarking",
@@ -6774,7 +6774,7 @@
[[package]]
name = "pallet-refungible"
-version = "0.2.12"
+version = "0.2.13"
dependencies = [
"evm-coder",
"frame-benchmarking",
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -18,7 +18,10 @@
use alloc::format;
use sp_std::{vec, vec::Vec};
-use evm_coder::{AbiCoder, types::Address};
+use evm_coder::{
+ AbiCoder,
+ types::{Address, String},
+};
pub use pallet_evm::{Config, account::CrossAccountId};
use sp_core::{H160, U256};
use up_data_structs::CollectionId;
@@ -390,6 +393,16 @@
}
}
+/// Data for creation token with uri.
+#[derive(Debug, AbiCoder)]
+pub struct TokenUri {
+ /// Id of new token.
+ pub id: U256,
+
+ /// Uri of new token.
+ pub uri: String,
+}
+
/// Nested collections.
#[derive(Debug, Default, AbiCoder)]
pub struct CollectionNesting {
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68 dispatch::Pays,69 transactional,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73 COLLECTION_NUMBER_LIMIT,74 Collection,75 RpcCollection,76 CollectionFlags,77 RpcCollectionFlags,78 CollectionId,79 CreateItemData,80 MAX_TOKEN_PREFIX_LENGTH,81 COLLECTION_ADMINS_LIMIT,82 TokenId,83 TokenChild,84 CollectionStats,85 MAX_TOKEN_OWNERSHIP,86 CollectionMode,87 NFT_SPONSOR_TRANSFER_TIMEOUT,88 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,89 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,90 MAX_SPONSOR_TIMEOUT,91 CUSTOM_DATA_LIMIT,92 CollectionLimits,93 CreateCollectionData,94 SponsorshipState,95 CreateItemExData,96 SponsoringRateLimit,97 budget::Budget,98 PhantomType,99 Property,100 Properties,101 PropertiesPermissionMap,102 PropertyKey,103 PropertyValue,104 PropertyPermission,105 PropertiesError,106 TokenOwnerError,107 PropertyKeyPermission,108 TokenData,109 TrySetProperty,110 PropertyScope,111 // RMRK112 RmrkCollectionInfo,113 RmrkInstanceInfo,114 RmrkResourceInfo,115 RmrkPropertyInfo,116 RmrkBaseInfo,117 RmrkPartType,118 RmrkBoundedTheme,119 RmrkNftChild,120 CollectionPermissions,121};122use up_pov_estimate_rpc::PovInfo;123124pub use pallet::*;125use sp_core::H160;126use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};127#[cfg(feature = "runtime-benchmarks")]128pub mod benchmarking;129pub mod dispatch;130pub mod erc;131pub mod eth;132pub mod weights;133134/// Weight info.135pub type SelfWeightOf<T> = <T as Config>::WeightInfo;136137/// Collection handle contains information about collection data and id.138/// Also provides functionality to count consumed gas.139///140/// CollectionHandle is used as a generic wrapper for collections of all types.141/// It allows to perform common operations and queries on any collection type,142/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].143#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]144pub struct CollectionHandle<T: Config> {145 /// Collection id146 pub id: CollectionId,147 collection: Collection<T::AccountId>,148 /// Substrate recorder for counting consumed gas149 pub recorder: SubstrateRecorder<T>,150}151152impl<T: Config> WithRecorder<T> for CollectionHandle<T> {153 fn recorder(&self) -> &SubstrateRecorder<T> {154 &self.recorder155 }156 fn into_recorder(self) -> SubstrateRecorder<T> {157 self.recorder158 }159}160161impl<T: Config> CollectionHandle<T> {162 /// Same as [CollectionHandle::new] but with an explicit gas limit.163 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {164 <CollectionById<T>>::get(id).map(|collection| Self {165 id,166 collection,167 recorder: SubstrateRecorder::new(gas_limit),168 })169 }170171 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].172 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {173 <CollectionById<T>>::get(id).map(|collection| Self {174 id,175 collection,176 recorder,177 })178 }179180 /// Retrives collection data from storage and creates collection handle with default parameters.181 /// If collection not found return `None`182 pub fn new(id: CollectionId) -> Option<Self> {183 Self::new_with_gas_limit(id, u64::MAX)184 }185186 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.187 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {188 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)189 }190191 /// Consume gas for reading.192 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {193 self.recorder194 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(195 <T as frame_system::Config>::DbWeight::get()196 .read197 .saturating_mul(reads),198 )))199 }200201 /// Consume gas for writing.202 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {203 self.recorder204 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(205 <T as frame_system::Config>::DbWeight::get()206 .write207 .saturating_mul(writes),208 )))209 }210211 /// Consume gas for reading and writing.212 pub fn consume_store_reads_and_writes(213 &self,214 reads: u64,215 writes: u64,216 ) -> evm_coder::execution::Result<()> {217 let weight = <T as frame_system::Config>::DbWeight::get();218 let reads = weight.read.saturating_mul(reads);219 let writes = weight.read.saturating_mul(writes);220 self.recorder221 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(222 reads.saturating_add(writes),223 )))224 }225226 /// Save collection to storage.227 pub fn save(&self) -> DispatchResult {228 <CollectionById<T>>::insert(self.id, &self.collection);229 Ok(())230 }231232 /// Set collection sponsor.233 ///234 /// Unique collections allows sponsoring for certain actions.235 /// This method allows you to set the sponsor of the collection.236 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].237 pub fn set_sponsor(238 &mut self,239 sender: &T::CrossAccountId,240 sponsor: T::AccountId,241 ) -> DispatchResult {242 self.check_is_internal()?;243 self.check_is_owner_or_admin(sender)?;244245 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());246247 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));248 <PalletEvm<T>>::deposit_log(249 erc::CollectionHelpersEvents::CollectionChanged {250 collection_id: eth::collection_id_to_address(self.id),251 }252 .to_log(T::ContractAddress::get()),253 );254255 self.save()256 }257258 /// Force set `sponsor`.259 ///260 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation261 /// from the `sponsor` is not required.262 ///263 /// # Arguments264 ///265 /// * `sender`: Caller's account.266 /// * `sponsor`: ID of the account of the sponsor-to-be.267 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {268 self.check_is_internal()?;269270 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());271272 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));273 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));274 <PalletEvm<T>>::deposit_log(275 erc::CollectionHelpersEvents::CollectionChanged {276 collection_id: eth::collection_id_to_address(self.id),277 }278 .to_log(T::ContractAddress::get()),279 );280281 self.save()282 }283284 /// Confirm sponsorship285 ///286 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.287 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].288 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {289 self.check_is_internal()?;290 ensure!(291 self.collection.sponsorship.pending_sponsor() == Some(sender),292 Error::<T>::ConfirmSponsorshipFail293 );294295 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());296297 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));298 <PalletEvm<T>>::deposit_log(299 erc::CollectionHelpersEvents::CollectionChanged {300 collection_id: eth::collection_id_to_address(self.id),301 }302 .to_log(T::ContractAddress::get()),303 );304305 self.save()306 }307308 /// Remove collection sponsor.309 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {310 self.check_is_internal()?;311 self.check_is_owner_or_admin(sender)?;312313 self.collection.sponsorship = SponsorshipState::Disabled;314315 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));316 <PalletEvm<T>>::deposit_log(317 erc::CollectionHelpersEvents::CollectionChanged {318 collection_id: eth::collection_id_to_address(self.id),319 }320 .to_log(T::ContractAddress::get()),321 );322 self.save()323 }324325 /// Force remove `sponsor`.326 ///327 /// Differs from `remove_sponsor` in that328 /// it doesn't require consent from the `owner` of the collection.329 pub fn force_remove_sponsor(&mut self) -> DispatchResult {330 self.check_is_internal()?;331332 self.collection.sponsorship = SponsorshipState::Disabled;333334 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));335 <PalletEvm<T>>::deposit_log(336 erc::CollectionHelpersEvents::CollectionChanged {337 collection_id: eth::collection_id_to_address(self.id),338 }339 .to_log(T::ContractAddress::get()),340 );341 self.save()342 }343344 /// Checks that the collection was created with, and must be operated upon through **Unique API**.345 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.346 pub fn check_is_internal(&self) -> DispatchResult {347 if self.flags.external {348 return Err(<Error<T>>::CollectionIsExternal)?;349 }350351 Ok(())352 }353354 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.355 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.356 pub fn check_is_external(&self) -> DispatchResult {357 if !self.flags.external {358 return Err(<Error<T>>::CollectionIsInternal)?;359 }360361 Ok(())362 }363}364365impl<T: Config> Deref for CollectionHandle<T> {366 type Target = Collection<T::AccountId>;367368 fn deref(&self) -> &Self::Target {369 &self.collection370 }371}372373impl<T: Config> DerefMut for CollectionHandle<T> {374 fn deref_mut(&mut self) -> &mut Self::Target {375 &mut self.collection376 }377}378379impl<T: Config> CollectionHandle<T> {380 /// Checks if the `user` is the owner of the collection.381 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {382 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);383 Ok(())384 }385386 /// Returns **true** if the `user` is the owner or administrator of the collection.387 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {388 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))389 }390391 /// Checks if the `user` is the owner or administrator of the collection.392 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {393 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);394 Ok(())395 }396397 /// Returns **true** if398 /// * the `user`is a collection owner or admin399 /// * the collection limits allow the owner/admins to transfer/burn any collection token400 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {401 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)402 }403404 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.405 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {406 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)407 }408409 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.410 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {411 ensure!(412 <Allowlist<T>>::get((self.id, user)),413 <Error<T>>::AddressNotInAllowlist414 );415 Ok(())416 }417418 /// Changes collection owner to another account419 /// #### Store read/writes420 /// 1 writes421 pub fn change_owner(422 &mut self,423 caller: T::CrossAccountId,424 new_owner: T::CrossAccountId,425 ) -> DispatchResult {426 self.check_is_internal()?;427 self.check_is_owner(&caller)?;428 self.collection.owner = new_owner.as_sub().clone();429430 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(431 self.id,432 new_owner.as_sub().clone(),433 ));434 <PalletEvm<T>>::deposit_log(435 erc::CollectionHelpersEvents::CollectionChanged {436 collection_id: eth::collection_id_to_address(self.id),437 }438 .to_log(T::ContractAddress::get()),439 );440441 self.save()442 }443}444445#[frame_support::pallet]446pub mod pallet {447 use super::*;448 use dispatch::CollectionDispatch;449 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};450 use frame_system::pallet_prelude::*;451 use frame_support::traits::Currency;452 use up_data_structs::{TokenId, mapping::TokenAddressMapping};453 use scale_info::TypeInfo;454 use weights::WeightInfo;455456 #[pallet::config]457 pub trait Config:458 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo459 {460 /// Weight information for functions of this pallet.461 type WeightInfo: WeightInfo;462463 /// Events compatible with [`frame_system::Config::Event`].464 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;465466 /// Handler of accounts and payment.467 type Currency: Currency<Self::AccountId>;468469 /// Set price to create a collection.470 #[pallet::constant]471 type CollectionCreationPrice: Get<472 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,473 >;474475 /// Dispatcher of operations on collections.476 type CollectionDispatch: CollectionDispatch<Self>;477478 /// Account which holds the chain's treasury.479 type TreasuryAccountId: Get<Self::AccountId>;480481 /// Address under which the CollectionHelper contract would be available.482 #[pallet::constant]483 type ContractAddress: Get<H160>;484485 /// Mapper for token addresses to Ethereum addresses.486 type EvmTokenAddressMapping: TokenAddressMapping<H160>;487488 /// Mapper for token addresses to [`CrossAccountId`].489 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;490 }491492 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);493494 #[pallet::pallet]495 #[pallet::storage_version(STORAGE_VERSION)]496 #[pallet::generate_store(pub(super) trait Store)]497 pub struct Pallet<T>(_);498499 #[pallet::extra_constants]500 impl<T: Config> Pallet<T> {501 /// Maximum admins per collection.502 pub fn collection_admins_limit() -> u32 {503 COLLECTION_ADMINS_LIMIT504 }505 }506507 impl<T: Config> Pallet<T> {508 /// Helper function that handles deposit events509 pub fn deposit_event(event: Event<T>) {510 let event = <T as Config>::RuntimeEvent::from(event);511 let event = event.into();512 <frame_system::Pallet<T>>::deposit_event(event)513 }514 }515516 #[pallet::event]517 pub enum Event<T: Config> {518 /// New collection was created519 CollectionCreated(520 /// Globally unique identifier of newly created collection.521 CollectionId,522 /// [`CollectionMode`] converted into _u8_.523 u8,524 /// Collection owner.525 T::AccountId,526 ),527528 /// New collection was destroyed529 CollectionDestroyed(530 /// Globally unique identifier of collection.531 CollectionId,532 ),533534 /// New item was created.535 ItemCreated(536 /// Id of the collection where item was created.537 CollectionId,538 /// Id of an item. Unique within the collection.539 TokenId,540 /// Owner of newly created item541 T::CrossAccountId,542 /// Always 1 for NFT543 u128,544 ),545546 /// Collection item was burned.547 ItemDestroyed(548 /// Id of the collection where item was destroyed.549 CollectionId,550 /// Identifier of burned NFT.551 TokenId,552 /// Which user has destroyed its tokens.553 T::CrossAccountId,554 /// Amount of token pieces destroed. Always 1 for NFT.555 u128,556 ),557558 /// Item was transferred559 Transfer(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 /// New owner of item.567 T::CrossAccountId,568 /// Amount of token pieces transfered. Always 1 for NFT.569 u128,570 ),571572 /// Amount pieces of token owned by `sender` was approved for `spender`.573 Approved(574 /// Id of collection to which item is belong.575 CollectionId,576 /// Id of an item.577 TokenId,578 /// Original owner of item.579 T::CrossAccountId,580 /// Id for which the approval was granted.581 T::CrossAccountId,582 /// Amount of token pieces transfered. Always 1 for NFT.583 u128,584 ),585586 /// A `sender` approves operations on all owned tokens for `spender`.587 ApprovedForAll(588 /// Id of collection to which item is belong.589 CollectionId,590 /// Owner of a wallet.591 T::CrossAccountId,592 /// Id for which operator status was granted or rewoked.593 T::CrossAccountId,594 /// Is operator status granted or revoked?595 bool,596 ),597598 /// The colletion property has been added or edited.599 CollectionPropertySet(600 /// Id of collection to which property has been set.601 CollectionId,602 /// The property that was set.603 PropertyKey,604 ),605606 /// The property has been deleted.607 CollectionPropertyDeleted(608 /// Id of collection to which property has been deleted.609 CollectionId,610 /// The property that was deleted.611 PropertyKey,612 ),613614 /// The token property has been added or edited.615 TokenPropertySet(616 /// Identifier of the collection whose token has the property set.617 CollectionId,618 /// The token for which the property was set.619 TokenId,620 /// The property that was set.621 PropertyKey,622 ),623624 /// The token property has been deleted.625 TokenPropertyDeleted(626 /// Identifier of the collection whose token has the property deleted.627 CollectionId,628 /// The token for which the property was deleted.629 TokenId,630 /// The property that was deleted.631 PropertyKey,632 ),633634 /// The token property permission of a collection has been set.635 PropertyPermissionSet(636 /// ID of collection to which property permission has been set.637 CollectionId,638 /// The property permission that was set.639 PropertyKey,640 ),641642 /// Address was added to the allow list.643 AllowListAddressAdded(644 /// ID of the affected collection.645 CollectionId,646 /// Address of the added account.647 T::CrossAccountId,648 ),649650 /// Address was removed from the allow list.651 AllowListAddressRemoved(652 /// ID of the affected collection.653 CollectionId,654 /// Address of the removed account.655 T::CrossAccountId,656 ),657658 /// Collection admin was added.659 CollectionAdminAdded(660 /// ID of the affected collection.661 CollectionId,662 /// Admin address.663 T::CrossAccountId,664 ),665666 /// Collection admin was removed.667 CollectionAdminRemoved(668 /// ID of the affected collection.669 CollectionId,670 /// Removed admin address.671 T::CrossAccountId,672 ),673674 /// Collection limits were set.675 CollectionLimitSet(676 /// ID of the affected collection.677 CollectionId,678 ),679680 /// Collection owned was changed.681 CollectionOwnerChanged(682 /// ID of the affected collection.683 CollectionId,684 /// New owner address.685 T::AccountId,686 ),687688 /// Collection permissions were set.689 CollectionPermissionSet(690 /// ID of the affected collection.691 CollectionId,692 ),693694 /// Collection sponsor was set.695 CollectionSponsorSet(696 /// ID of the affected collection.697 CollectionId,698 /// New sponsor address.699 T::AccountId,700 ),701702 /// New sponsor was confirm.703 SponsorshipConfirmed(704 /// ID of the affected collection.705 CollectionId,706 /// New sponsor address.707 T::AccountId,708 ),709710 /// Collection sponsor was removed.711 CollectionSponsorRemoved(712 /// ID of the affected collection.713 CollectionId,714 ),715 }716717 #[pallet::error]718 pub enum Error<T> {719 /// This collection does not exist.720 CollectionNotFound,721 /// Sender parameter and item owner must be equal.722 MustBeTokenOwner,723 /// No permission to perform action724 NoPermission,725 /// Destroying only empty collections is allowed726 CantDestroyNotEmptyCollection,727 /// Collection is not in mint mode.728 PublicMintingNotAllowed,729 /// Address is not in allow list.730 AddressNotInAllowlist,731732 /// Collection name can not be longer than 63 char.733 CollectionNameLimitExceeded,734 /// Collection description can not be longer than 255 char.735 CollectionDescriptionLimitExceeded,736 /// Token prefix can not be longer than 15 char.737 CollectionTokenPrefixLimitExceeded,738 /// Total collections bound exceeded.739 TotalCollectionsLimitExceeded,740 /// Exceeded max admin count741 CollectionAdminCountExceeded,742 /// Collection limit bounds per collection exceeded743 CollectionLimitBoundsExceeded,744 /// Tried to enable permissions which are only permitted to be disabled745 OwnerPermissionsCantBeReverted,746 /// Collection settings not allowing items transferring747 TransferNotAllowed,748 /// Account token limit exceeded per collection749 AccountTokenLimitExceeded,750 /// Collection token limit exceeded751 CollectionTokenLimitExceeded,752 /// Metadata flag frozen753 MetadataFlagFrozen,754755 /// Item does not exist756 TokenNotFound,757 /// Item is balance not enough758 TokenValueTooLow,759 /// Requested value is more than the approved760 ApprovedValueTooLow,761 /// Tried to approve more than owned762 CantApproveMoreThanOwned,763 /// Only spending from eth mirror could be approved764 AddressIsNotEthMirror,765766 /// Can't transfer tokens to ethereum zero address767 AddressIsZero,768769 /// The operation is not supported770 UnsupportedOperation,771772 /// Insufficient funds to perform an action773 NotSufficientFounds,774775 /// User does not satisfy the nesting rule776 UserIsNotAllowedToNest,777 /// Only tokens from specific collections may nest tokens under this one778 SourceCollectionIsNotAllowedToNest,779780 /// Tried to store more data than allowed in collection field781 CollectionFieldSizeExceeded,782783 /// Tried to store more property data than allowed784 NoSpaceForProperty,785786 /// Tried to store more property keys than allowed787 PropertyLimitReached,788789 /// Property key is too long790 PropertyKeyIsTooLong,791792 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed793 InvalidCharacterInPropertyKey,794795 /// Empty property keys are forbidden796 EmptyPropertyKey,797798 /// Tried to access an external collection with an internal API799 CollectionIsExternal,800801 /// Tried to access an internal collection with an external API802 CollectionIsInternal,803804 /// This address is not set as sponsor, use setCollectionSponsor first.805 ConfirmSponsorshipFail,806807 /// The user is not an administrator.808 UserIsNotCollectionAdmin,809 }810811 /// Storage of the count of created collections. Essentially contains the last collection ID.812 #[pallet::storage]813 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;814815 /// Storage of the count of deleted collections.816 #[pallet::storage]817 pub type DestroyedCollectionCount<T> =818 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;819820 /// Storage of collection info.821 #[pallet::storage]822 pub type CollectionById<T> = StorageMap<823 Hasher = Blake2_128Concat,824 Key = CollectionId,825 Value = Collection<<T as frame_system::Config>::AccountId>,826 QueryKind = OptionQuery,827 >;828829 /// Storage of collection properties.830 #[pallet::storage]831 #[pallet::getter(fn collection_properties)]832 pub type CollectionProperties<T> = StorageMap<833 Hasher = Blake2_128Concat,834 Key = CollectionId,835 Value = Properties,836 QueryKind = ValueQuery,837 OnEmpty = up_data_structs::CollectionProperties,838 >;839840 /// Storage of token property permissions of a collection.841 #[pallet::storage]842 #[pallet::getter(fn property_permissions)]843 pub type CollectionPropertyPermissions<T> = StorageMap<844 Hasher = Blake2_128Concat,845 Key = CollectionId,846 Value = PropertiesPermissionMap,847 QueryKind = ValueQuery,848 >;849850 /// Storage of the amount of collection admins.851 #[pallet::storage]852 pub type AdminAmount<T> = StorageMap<853 Hasher = Blake2_128Concat,854 Key = CollectionId,855 Value = u32,856 QueryKind = ValueQuery,857 >;858859 /// List of collection admins.860 #[pallet::storage]861 pub type IsAdmin<T: Config> = StorageNMap<862 Key = (863 Key<Blake2_128Concat, CollectionId>,864 Key<Blake2_128Concat, T::CrossAccountId>,865 ),866 Value = bool,867 QueryKind = ValueQuery,868 >;869870 /// Allowlisted collection users.871 #[pallet::storage]872 pub type Allowlist<T: Config> = StorageNMap<873 Key = (874 Key<Blake2_128Concat, CollectionId>,875 Key<Blake2_128Concat, T::CrossAccountId>,876 ),877 Value = bool,878 QueryKind = ValueQuery,879 >;880881 /// Not used by code, exists only to provide some types to metadata.882 #[pallet::storage]883 pub type DummyStorageValue<T: Config> = StorageValue<884 Value = (885 CollectionStats,886 CollectionId,887 TokenId,888 TokenChild,889 PhantomType<(890 TokenData<T::CrossAccountId>,891 RpcCollection<T::AccountId>,892 // RMRK893 RmrkCollectionInfo<T::AccountId>,894 RmrkInstanceInfo<T::AccountId>,895 RmrkResourceInfo,896 RmrkPropertyInfo,897 RmrkBaseInfo<T::AccountId>,898 RmrkPartType,899 RmrkBoundedTheme,900 RmrkNftChild,901 // PoV Estimate Info902 PovInfo,903 )>,904 ),905 QueryKind = OptionQuery,906 >;907908 #[pallet::hooks]909 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {910 fn on_runtime_upgrade() -> Weight {911 StorageVersion::new(1).put::<Pallet<T>>();912913 Weight::zero()914 }915 }916}917918impl<T: Config> Pallet<T> {919 /// Enshure that receiver address is correct.920 ///921 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.922 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {923 ensure!(924 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,925 <Error<T>>::AddressIsZero926 );927 Ok(())928 }929930 /// Get a vector of collection admins.931 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {932 <IsAdmin<T>>::iter_prefix((collection,))933 .map(|(a, _)| a)934 .collect()935 }936937 /// Get a vector of users allowed to mint tokens.938 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {939 <Allowlist<T>>::iter_prefix((collection,))940 .map(|(a, _)| a)941 .collect()942 }943944 /// Is `user` allowed to mint token in `collection`.945 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {946 <Allowlist<T>>::get((collection, user))947 }948949 /// Get statistics of collections.950 pub fn collection_stats() -> CollectionStats {951 let created = <CreatedCollectionCount<T>>::get();952 let destroyed = <DestroyedCollectionCount<T>>::get();953 CollectionStats {954 created: created.0,955 destroyed: destroyed.0,956 alive: created.0 - destroyed.0,957 }958 }959960 /// Get the effective limits for the collection.961 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {962 let collection = <CollectionById<T>>::get(collection)?;963 let limits = collection.limits;964 let effective_limits = CollectionLimits {965 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),966 sponsored_data_size: Some(limits.sponsored_data_size()),967 sponsored_data_rate_limit: Some(968 limits969 .sponsored_data_rate_limit970 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),971 ),972 token_limit: Some(limits.token_limit()),973 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(974 match collection.mode {975 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,976 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,977 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,978 },979 )),980 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),981 owner_can_transfer: Some(limits.owner_can_transfer()),982 owner_can_destroy: Some(limits.owner_can_destroy()),983 transfers_enabled: Some(limits.transfers_enabled()),984 };985986 Some(effective_limits)987 }988989 /// Returns information about the `collection` adapted for rpc.990 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {991 let Collection {992 name,993 description,994 owner,995 mode,996 token_prefix,997 sponsorship,998 limits,999 permissions,1000 flags,1001 } = <CollectionById<T>>::get(collection)?;10021003 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1004 .into_iter()1005 .map(|(key, permission)| PropertyKeyPermission { key, permission })1006 .collect();10071008 let properties = <CollectionProperties<T>>::get(collection)1009 .into_iter()1010 .map(|(key, value)| Property { key, value })1011 .collect();10121013 let permissions = CollectionPermissions {1014 access: Some(permissions.access()),1015 mint_mode: Some(permissions.mint_mode()),1016 nesting: Some(permissions.nesting().clone()),1017 };10181019 Some(RpcCollection {1020 name: name.into_inner(),1021 description: description.into_inner(),1022 owner,1023 mode,1024 token_prefix: token_prefix.into_inner(),1025 sponsorship,1026 limits,1027 permissions,1028 token_property_permissions,1029 properties,1030 read_only: flags.external,10311032 flags: RpcCollectionFlags {1033 foreign: flags.foreign,1034 erc721metadata: flags.erc721metadata,1035 },1036 })1037 }1038}10391040macro_rules! limit_default {1041 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1042 $(1043 if let Some($new) = $new.$field {1044 let $old = $old.$field($($arg)?);1045 let _ = $new;1046 let _ = $old;1047 $check1048 } else {1049 $new.$field = $old.$field1050 }1051 )*1052 }};1053}1054macro_rules! limit_default_clone {1055 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1056 $(1057 if let Some($new) = $new.$field.clone() {1058 let $old = $old.$field($($arg)?);1059 let _ = $new;1060 let _ = $old;1061 $check1062 } else {1063 $new.$field = $old.$field.clone()1064 }1065 )*1066 }};1067}10681069impl<T: Config> Pallet<T> {1070 /// Create new collection.1071 ///1072 /// * `owner` - The owner of the collection.1073 /// * `data` - Description of the created collection.1074 /// * `flags` - Extra flags to store.1075 pub fn init_collection(1076 owner: T::CrossAccountId,1077 payer: T::CrossAccountId,1078 data: CreateCollectionData<T::AccountId>,1079 flags: CollectionFlags,1080 ) -> Result<CollectionId, DispatchError> {1081 {1082 ensure!(1083 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1084 Error::<T>::CollectionTokenPrefixLimitExceeded1085 );1086 }10871088 let created_count = <CreatedCollectionCount<T>>::get()1089 .01090 .checked_add(1)1091 .ok_or(ArithmeticError::Overflow)?;1092 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1093 let id = CollectionId(created_count);10941095 // bound Total number of collections1096 ensure!(1097 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1098 <Error<T>>::TotalCollectionsLimitExceeded1099 );11001101 // =========11021103 let collection = Collection {1104 owner: owner.as_sub().clone(),1105 name: data.name,1106 mode: data.mode.clone(),1107 description: data.description,1108 token_prefix: data.token_prefix,1109 sponsorship: data1110 .pending_sponsor1111 .map(SponsorshipState::Unconfirmed)1112 .unwrap_or_default(),1113 limits: data1114 .limits1115 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1116 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1117 permissions: data1118 .permissions1119 .map(|permissions| {1120 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1121 })1122 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1123 flags,1124 };11251126 let mut collection_properties = up_data_structs::CollectionProperties::get();1127 collection_properties1128 .try_set_from_iter(data.properties.into_iter())1129 .map_err(<Error<T>>::from)?;11301131 CollectionProperties::<T>::insert(id, collection_properties);11321133 let mut token_props_permissions = PropertiesPermissionMap::new();1134 token_props_permissions1135 .try_set_from_iter(data.token_property_permissions.into_iter())1136 .map_err(<Error<T>>::from)?;11371138 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11391140 // Take a (non-refundable) deposit of collection creation1141 {1142 let mut imbalance =1143 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1144 imbalance.subsume(1145 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1146 &T::TreasuryAccountId::get(),1147 T::CollectionCreationPrice::get(),1148 ),1149 );1150 <T as Config>::Currency::settle(1151 payer.as_sub(),1152 imbalance,1153 WithdrawReasons::TRANSFER,1154 ExistenceRequirement::KeepAlive,1155 )1156 .map_err(|_| Error::<T>::NotSufficientFounds)?;1157 }11581159 <CreatedCollectionCount<T>>::put(created_count);1160 <Pallet<T>>::deposit_event(Event::CollectionCreated(1161 id,1162 data.mode.id(),1163 owner.as_sub().clone(),1164 ));1165 <PalletEvm<T>>::deposit_log(1166 erc::CollectionHelpersEvents::CollectionCreated {1167 owner: *owner.as_eth(),1168 collection_id: eth::collection_id_to_address(id),1169 }1170 .to_log(T::ContractAddress::get()),1171 );1172 <CollectionById<T>>::insert(id, collection);1173 Ok(id)1174 }11751176 /// Destroy collection.1177 ///1178 /// * `collection` - Collection handler.1179 /// * `sender` - The owner or administrator of the collection.1180 pub fn destroy_collection(1181 collection: CollectionHandle<T>,1182 sender: &T::CrossAccountId,1183 ) -> DispatchResult {1184 ensure!(1185 collection.limits.owner_can_destroy(),1186 <Error<T>>::NoPermission,1187 );1188 collection.check_is_owner(sender)?;11891190 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1191 .01192 .checked_add(1)1193 .ok_or(ArithmeticError::Overflow)?;11941195 // =========11961197 <DestroyedCollectionCount<T>>::put(destroyed_collections);1198 <CollectionById<T>>::remove(collection.id);1199 <AdminAmount<T>>::remove(collection.id);1200 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1201 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1202 <CollectionProperties<T>>::remove(collection.id);12031204 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12051206 <PalletEvm<T>>::deposit_log(1207 erc::CollectionHelpersEvents::CollectionDestroyed {1208 collection_id: eth::collection_id_to_address(collection.id),1209 }1210 .to_log(T::ContractAddress::get()),1211 );1212 Ok(())1213 }12141215 /// This function sets or removes a collection properties according to1216 /// `properties_updates` contents:1217 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1218 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1219 ///1220 /// This function fires an event for each property change.1221 /// In case of an error, all the changes (including the events) will be reverted1222 /// since the function is transactional.1223 #[transactional]1224 fn modify_collection_properties(1225 collection: &CollectionHandle<T>,1226 sender: &T::CrossAccountId,1227 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1228 ) -> DispatchResult {1229 collection.check_is_owner_or_admin(sender)?;12301231 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12321233 for (key, value) in properties_updates {1234 match value {1235 Some(value) => {1236 stored_properties1237 .try_set(key.clone(), value)1238 .map_err(<Error<T>>::from)?;12391240 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1241 <PalletEvm<T>>::deposit_log(1242 erc::CollectionHelpersEvents::CollectionChanged {1243 collection_id: eth::collection_id_to_address(collection.id),1244 }1245 .to_log(T::ContractAddress::get()),1246 );1247 }1248 None => {1249 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12501251 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1252 <PalletEvm<T>>::deposit_log(1253 erc::CollectionHelpersEvents::CollectionChanged {1254 collection_id: eth::collection_id_to_address(collection.id),1255 }1256 .to_log(T::ContractAddress::get()),1257 );1258 }1259 }1260 }12611262 <CollectionProperties<T>>::set(collection.id, stored_properties);12631264 Ok(())1265 }12661267 /// Set collection property.1268 ///1269 /// * `collection` - Collection handler.1270 /// * `sender` - The owner or administrator of the collection.1271 /// * `property` - The property to set.1272 pub fn set_collection_property(1273 collection: &CollectionHandle<T>,1274 sender: &T::CrossAccountId,1275 property: Property,1276 ) -> DispatchResult {1277 Self::set_collection_properties(collection, sender, [property].into_iter())1278 }12791280 /// Set a scoped collection property, where the scope is a special prefix1281 /// prohibiting a user access to change the property directly.1282 ///1283 /// * `collection_id` - ID of the collection for which the property is being set.1284 /// * `scope` - Property scope.1285 /// * `property` - The property to set.1286 pub fn set_scoped_collection_property(1287 collection_id: CollectionId,1288 scope: PropertyScope,1289 property: Property,1290 ) -> DispatchResult {1291 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1292 properties.try_scoped_set(scope, property.key, property.value)1293 })1294 .map_err(<Error<T>>::from)?;12951296 Ok(())1297 }12981299 /// Set scoped collection properties, where the scope is a special prefix1300 /// prohibiting a user access to change the properties directly.1301 ///1302 /// * `collection_id` - ID of the collection for which the properties is being set.1303 /// * `scope` - Property scope.1304 /// * `properties` - The properties to set.1305 pub fn set_scoped_collection_properties(1306 collection_id: CollectionId,1307 scope: PropertyScope,1308 properties: impl Iterator<Item = Property>,1309 ) -> DispatchResult {1310 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1311 stored_properties.try_scoped_set_from_iter(scope, properties)1312 })1313 .map_err(<Error<T>>::from)?;13141315 Ok(())1316 }13171318 /// Set collection properties.1319 ///1320 /// * `collection` - Collection handler.1321 /// * `sender` - The owner or administrator of the collection.1322 /// * `properties` - The properties to set.1323 pub fn set_collection_properties(1324 collection: &CollectionHandle<T>,1325 sender: &T::CrossAccountId,1326 properties: impl Iterator<Item = Property>,1327 ) -> DispatchResult {1328 Self::modify_collection_properties(1329 collection,1330 sender,1331 properties.map(|property| (property.key, Some(property.value))),1332 )1333 }13341335 /// Delete collection property.1336 ///1337 /// * `collection` - Collection handler.1338 /// * `sender` - The owner or administrator of the collection.1339 /// * `property` - The property to delete.1340 pub fn delete_collection_property(1341 collection: &CollectionHandle<T>,1342 sender: &T::CrossAccountId,1343 property_key: PropertyKey,1344 ) -> DispatchResult {1345 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1346 }13471348 /// Delete collection properties.1349 ///1350 /// * `collection` - Collection handler.1351 /// * `sender` - The owner or administrator of the collection.1352 /// * `properties` - The properties to delete.1353 pub fn delete_collection_properties(1354 collection: &CollectionHandle<T>,1355 sender: &T::CrossAccountId,1356 property_keys: impl Iterator<Item = PropertyKey>,1357 ) -> DispatchResult {1358 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1359 }13601361 /// Set collection propetry permission without any checks.1362 ///1363 /// Used for migrations.1364 ///1365 /// * `collection` - Collection handler.1366 /// * `property_permissions` - Property permissions.1367 pub fn set_property_permission_unchecked(1368 collection: CollectionId,1369 property_permission: PropertyKeyPermission,1370 ) -> DispatchResult {1371 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1372 permissions.try_set(property_permission.key, property_permission.permission)1373 })1374 .map_err(<Error<T>>::from)?;1375 Ok(())1376 }13771378 /// Set collection property permission.1379 ///1380 /// * `collection` - Collection handler.1381 /// * `sender` - The owner or administrator of the collection.1382 /// * `property_permission` - Property permission.1383 pub fn set_property_permission(1384 collection: &CollectionHandle<T>,1385 sender: &T::CrossAccountId,1386 property_permission: PropertyKeyPermission,1387 ) -> DispatchResult {1388 Self::set_scoped_property_permission(1389 collection,1390 sender,1391 PropertyScope::None,1392 property_permission,1393 )1394 }13951396 /// Set collection property permission with scope.1397 ///1398 /// * `collection` - Collection handler.1399 /// * `sender` - The owner or administrator of the collection.1400 /// * `scope` - Property scope.1401 /// * `property_permission` - Property permission.1402 pub fn set_scoped_property_permission(1403 collection: &CollectionHandle<T>,1404 sender: &T::CrossAccountId,1405 scope: PropertyScope,1406 property_permission: PropertyKeyPermission,1407 ) -> DispatchResult {1408 collection.check_is_owner_or_admin(sender)?;14091410 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1411 let current_permission = all_permissions.get(&property_permission.key);1412 if matches![1413 current_permission,1414 Some(PropertyPermission { mutable: false, .. })1415 ] {1416 return Err(<Error<T>>::NoPermission.into());1417 }14181419 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1420 let property_permission = property_permission.clone();1421 permissions.try_scoped_set(1422 scope,1423 property_permission.key,1424 property_permission.permission,1425 )1426 })1427 .map_err(<Error<T>>::from)?;14281429 Self::deposit_event(Event::PropertyPermissionSet(1430 collection.id,1431 property_permission.key,1432 ));1433 <PalletEvm<T>>::deposit_log(1434 erc::CollectionHelpersEvents::CollectionChanged {1435 collection_id: eth::collection_id_to_address(collection.id),1436 }1437 .to_log(T::ContractAddress::get()),1438 );14391440 Ok(())1441 }14421443 /// Set token property permission.1444 ///1445 /// * `collection` - Collection handler.1446 /// * `sender` - The owner or administrator of the collection.1447 /// * `property_permissions` - Property permissions.1448 #[transactional]1449 pub fn set_token_property_permissions(1450 collection: &CollectionHandle<T>,1451 sender: &T::CrossAccountId,1452 property_permissions: Vec<PropertyKeyPermission>,1453 ) -> DispatchResult {1454 Self::set_scoped_token_property_permissions(1455 collection,1456 sender,1457 PropertyScope::None,1458 property_permissions,1459 )1460 }14611462 /// Set token property permission with scope.1463 ///1464 /// * `collection` - Collection handler.1465 /// * `sender` - The owner or administrator of the collection.1466 /// * `scope` - Property scope.1467 /// * `property_permissions` - Property permissions.1468 #[transactional]1469 pub fn set_scoped_token_property_permissions(1470 collection: &CollectionHandle<T>,1471 sender: &T::CrossAccountId,1472 scope: PropertyScope,1473 property_permissions: Vec<PropertyKeyPermission>,1474 ) -> DispatchResult {1475 for prop_pemission in property_permissions {1476 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1477 }14781479 Ok(())1480 }14811482 /// Get collection property.1483 pub fn get_collection_property(1484 collection_id: CollectionId,1485 key: &PropertyKey,1486 ) -> Option<PropertyValue> {1487 Self::collection_properties(collection_id).get(key).cloned()1488 }14891490 /// Convert byte vector to property key vector.1491 pub fn bytes_keys_to_property_keys(1492 keys: Vec<Vec<u8>>,1493 ) -> Result<Vec<PropertyKey>, DispatchError> {1494 keys.into_iter()1495 .map(|key| -> Result<PropertyKey, DispatchError> {1496 key.try_into()1497 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1498 })1499 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1500 }15011502 /// Get properties according to given keys.1503 pub fn filter_collection_properties(1504 collection_id: CollectionId,1505 keys: Option<Vec<PropertyKey>>,1506 ) -> Result<Vec<Property>, DispatchError> {1507 let properties = Self::collection_properties(collection_id);15081509 let properties = keys1510 .map(|keys| {1511 keys.into_iter()1512 .filter_map(|key| {1513 properties.get(&key).map(|value| Property {1514 key,1515 value: value.clone(),1516 })1517 })1518 .collect()1519 })1520 .unwrap_or_else(|| {1521 properties1522 .into_iter()1523 .map(|(key, value)| Property { key, value })1524 .collect()1525 });15261527 Ok(properties)1528 }15291530 /// Get property permissions according to given keys.1531 pub fn filter_property_permissions(1532 collection_id: CollectionId,1533 keys: Option<Vec<PropertyKey>>,1534 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1535 let permissions = Self::property_permissions(collection_id);15361537 let key_permissions = keys1538 .map(|keys| {1539 keys.into_iter()1540 .filter_map(|key| {1541 permissions1542 .get(&key)1543 .map(|permission| PropertyKeyPermission {1544 key,1545 permission: permission.clone(),1546 })1547 })1548 .collect()1549 })1550 .unwrap_or_else(|| {1551 permissions1552 .into_iter()1553 .map(|(key, permission)| PropertyKeyPermission { key, permission })1554 .collect()1555 });15561557 Ok(key_permissions)1558 }15591560 /// Toggle `user` participation in the `collection`'s allow list.1561 /// #### Store read/writes1562 /// 1 writes1563 pub fn toggle_allowlist(1564 collection: &CollectionHandle<T>,1565 sender: &T::CrossAccountId,1566 user: &T::CrossAccountId,1567 allowed: bool,1568 ) -> DispatchResult {1569 collection.check_is_owner_or_admin(sender)?;15701571 // =========15721573 if allowed {1574 <Allowlist<T>>::insert((collection.id, user), true);1575 Self::deposit_event(Event::<T>::AllowListAddressAdded(1576 collection.id,1577 user.clone(),1578 ));1579 } else {1580 <Allowlist<T>>::remove((collection.id, user));1581 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1582 collection.id,1583 user.clone(),1584 ));1585 }15861587 <PalletEvm<T>>::deposit_log(1588 erc::CollectionHelpersEvents::CollectionChanged {1589 collection_id: eth::collection_id_to_address(collection.id),1590 }1591 .to_log(T::ContractAddress::get()),1592 );15931594 Ok(())1595 }15961597 /// Toggle `user` participation in the `collection`'s admin list.1598 /// #### Store read/writes1599 /// 2 reads, 2 writes1600 pub fn toggle_admin(1601 collection: &CollectionHandle<T>,1602 sender: &T::CrossAccountId,1603 user: &T::CrossAccountId,1604 admin: bool,1605 ) -> DispatchResult {1606 collection.check_is_internal()?;1607 collection.check_is_owner(sender)?;16081609 let is_admin = <IsAdmin<T>>::get((collection.id, user));1610 if is_admin == admin {1611 if admin {1612 return Ok(());1613 } else {1614 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1615 }1616 }1617 let amount = <AdminAmount<T>>::get(collection.id);16181619 // =========16201621 if admin {1622 let amount = amount1623 .checked_add(1)1624 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1625 ensure!(1626 amount <= Self::collection_admins_limit(),1627 <Error<T>>::CollectionAdminCountExceeded,1628 );16291630 <AdminAmount<T>>::insert(collection.id, amount);1631 <IsAdmin<T>>::insert((collection.id, user), true);16321633 Self::deposit_event(Event::<T>::CollectionAdminAdded(1634 collection.id,1635 user.clone(),1636 ));1637 } else {1638 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1639 <IsAdmin<T>>::remove((collection.id, user));16401641 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1642 collection.id,1643 user.clone(),1644 ));1645 }16461647 <PalletEvm<T>>::deposit_log(1648 erc::CollectionHelpersEvents::CollectionChanged {1649 collection_id: eth::collection_id_to_address(collection.id),1650 }1651 .to_log(T::ContractAddress::get()),1652 );16531654 Ok(())1655 }16561657 /// Update collection limits.1658 pub fn update_limits(1659 user: &T::CrossAccountId,1660 collection: &mut CollectionHandle<T>,1661 new_limit: CollectionLimits,1662 ) -> DispatchResult {1663 collection.check_is_internal()?;1664 collection.check_is_owner_or_admin(user)?;16651666 collection.limits =1667 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;16681669 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1670 <PalletEvm<T>>::deposit_log(1671 erc::CollectionHelpersEvents::CollectionChanged {1672 collection_id: eth::collection_id_to_address(collection.id),1673 }1674 .to_log(T::ContractAddress::get()),1675 );16761677 collection.save()1678 }16791680 /// Merge set fields from `new_limit` to `old_limit`.1681 fn clamp_limits(1682 mode: CollectionMode,1683 old_limit: &CollectionLimits,1684 mut new_limit: CollectionLimits,1685 ) -> Result<CollectionLimits, DispatchError> {1686 let limits = old_limit;1687 limit_default!(old_limit, new_limit,1688 account_token_ownership_limit => ensure!(1689 new_limit <= MAX_TOKEN_OWNERSHIP,1690 <Error<T>>::CollectionLimitBoundsExceeded,1691 ),1692 sponsored_data_size => ensure!(1693 new_limit <= CUSTOM_DATA_LIMIT,1694 <Error<T>>::CollectionLimitBoundsExceeded,1695 ),16961697 sponsored_data_rate_limit => {},1698 token_limit => ensure!(1699 old_limit >= new_limit && new_limit > 0,1700 <Error<T>>::CollectionTokenLimitExceeded1701 ),17021703 sponsor_transfer_timeout(match mode {1704 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1705 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1706 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1707 }) => ensure!(1708 new_limit <= MAX_SPONSOR_TIMEOUT,1709 <Error<T>>::CollectionLimitBoundsExceeded,1710 ),1711 sponsor_approve_timeout => {},1712 owner_can_transfer => ensure!(1713 !limits.owner_can_transfer_instaled() ||1714 old_limit || !new_limit,1715 <Error<T>>::OwnerPermissionsCantBeReverted,1716 ),1717 owner_can_destroy => ensure!(1718 old_limit || !new_limit,1719 <Error<T>>::OwnerPermissionsCantBeReverted,1720 ),1721 transfers_enabled => {},1722 );1723 Ok(new_limit)1724 }17251726 /// Update collection permissions.1727 pub fn update_permissions(1728 user: &T::CrossAccountId,1729 collection: &mut CollectionHandle<T>,1730 new_permission: CollectionPermissions,1731 ) -> DispatchResult {1732 collection.check_is_internal()?;1733 collection.check_is_owner_or_admin(user)?;1734 collection.permissions = Self::clamp_permissions(1735 collection.mode.clone(),1736 &collection.permissions,1737 new_permission,1738 )?;17391740 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1741 <PalletEvm<T>>::deposit_log(1742 erc::CollectionHelpersEvents::CollectionChanged {1743 collection_id: eth::collection_id_to_address(collection.id),1744 }1745 .to_log(T::ContractAddress::get()),1746 );17471748 collection.save()1749 }17501751 /// Merge set fields from `new_permission` to `old_permission`.1752 fn clamp_permissions(1753 _mode: CollectionMode,1754 old_permission: &CollectionPermissions,1755 mut new_permission: CollectionPermissions,1756 ) -> Result<CollectionPermissions, DispatchError> {1757 limit_default_clone!(old_permission, new_permission,1758 access => {},1759 mint_mode => {},1760 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1761 );1762 Ok(new_permission)1763 }17641765 /// Repair possibly broken properties of a collection.1766 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1767 CollectionProperties::<T>::mutate(collection_id, |properties| {1768 properties.recompute_consumed_space();1769 });17701771 Ok(())1772 }1773}17741775/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1776#[macro_export]1777macro_rules! unsupported {1778 ($runtime:path) => {1779 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1780 };1781}17821783/// Return weights for various worst-case operations.1784pub trait CommonWeightInfo<CrossAccountId> {1785 /// Weight of item creation.1786 fn create_item(data: &CreateItemData) -> Weight {1787 Self::create_multiple_items(from_ref(data))1788 }17891790 /// Weight of items creation.1791 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;17921793 /// Weight of items creation.1794 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;17951796 /// The weight of the burning item.1797 fn burn_item() -> Weight;17981799 /// Property setting weight.1800 ///1801 /// * `amount`- The number of properties to set.1802 fn set_collection_properties(amount: u32) -> Weight;18031804 /// Collection property deletion weight.1805 ///1806 /// * `amount`- The number of properties to set.1807 fn delete_collection_properties(amount: u32) -> Weight;18081809 /// Token property setting weight.1810 ///1811 /// * `amount`- The number of properties to set.1812 fn set_token_properties(amount: u32) -> Weight;18131814 /// Token property deletion weight.1815 ///1816 /// * `amount`- The number of properties to delete.1817 fn delete_token_properties(amount: u32) -> Weight;18181819 /// Token property permissions set weight.1820 ///1821 /// * `amount`- The number of property permissions to set.1822 fn set_token_property_permissions(amount: u32) -> Weight;18231824 /// Transfer price of the token or its parts.1825 fn transfer() -> Weight;18261827 /// The price of setting the permission of the operation from another user.1828 fn approve() -> Weight;18291830 /// The price of setting the permission of the operation from another user for eth mirror.1831 fn approve_from() -> Weight;18321833 /// Transfer price from another user.1834 fn transfer_from() -> Weight;18351836 /// The price of burning a token from another user.1837 fn burn_from() -> Weight;18381839 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1840 /// whole users's balance.1841 ///1842 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1843 fn burn_recursively_self_raw() -> Weight;18441845 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1846 ///1847 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1848 fn burn_recursively_breadth_raw(amount: u32) -> Weight;18491850 /// The price of recursive burning a token.1851 ///1852 /// `max_selfs` - The maximum burning weight of the token itself.1853 /// `max_breadth` - The maximum number of nested tokens to burn.1854 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1855 Self::burn_recursively_self_raw()1856 .saturating_mul(max_selfs.max(1) as u64)1857 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1858 }18591860 /// The price of retrieving token owner1861 fn token_owner() -> Weight;18621863 /// The price of setting approval for all1864 fn set_allowance_for_all() -> Weight;18651866 /// The price of repairing an item.1867 fn force_repair_item() -> Weight;1868}18691870/// Weight info extension trait for refungible pallet.1871pub trait RefungibleExtensionsWeightInfo {1872 /// Weight of token repartition.1873 fn repartition() -> Weight;1874}18751876/// Common collection operations.1877///1878/// It wraps methods in Fungible, Nonfungible and Refungible pallets1879/// and adds weight info.1880pub trait CommonCollectionOperations<T: Config> {1881 /// Create token.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_item(1888 &self,1889 sender: T::CrossAccountId,1890 to: T::CrossAccountId,1891 data: CreateItemData,1892 nesting_budget: &dyn Budget,1893 ) -> DispatchResultWithPostInfo;18941895 /// Create multiple tokens.1896 ///1897 /// * `sender` - The user who mint the token and pays for the transaction.1898 /// * `to` - The user who will own the token.1899 /// * `data` - Token data.1900 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1901 fn create_multiple_items(1902 &self,1903 sender: T::CrossAccountId,1904 to: T::CrossAccountId,1905 data: Vec<CreateItemData>,1906 nesting_budget: &dyn Budget,1907 ) -> DispatchResultWithPostInfo;19081909 /// Create multiple tokens.1910 ///1911 /// * `sender` - The user who mint the token and pays for the transaction.1912 /// * `to` - The user who will own the token.1913 /// * `data` - Token data.1914 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1915 fn create_multiple_items_ex(1916 &self,1917 sender: T::CrossAccountId,1918 data: CreateItemExData<T::CrossAccountId>,1919 nesting_budget: &dyn Budget,1920 ) -> DispatchResultWithPostInfo;19211922 /// Burn token.1923 ///1924 /// * `sender` - The user who owns the token.1925 /// * `token` - Token id that will burned.1926 /// * `amount` - The number of parts of the token that will be burned.1927 fn burn_item(1928 &self,1929 sender: T::CrossAccountId,1930 token: TokenId,1931 amount: u128,1932 ) -> DispatchResultWithPostInfo;19331934 /// Burn token and all nested tokens recursievly.1935 ///1936 /// * `sender` - The user who owns the token.1937 /// * `token` - Token id that will burned.1938 /// * `self_budget` - The budget that can be spent on burning tokens.1939 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1940 fn burn_item_recursively(1941 &self,1942 sender: T::CrossAccountId,1943 token: TokenId,1944 self_budget: &dyn Budget,1945 breadth_budget: &dyn Budget,1946 ) -> DispatchResultWithPostInfo;19471948 /// Set collection properties.1949 ///1950 /// * `sender` - Must be either the owner of the collection or its admin.1951 /// * `properties` - Properties to be set.1952 fn set_collection_properties(1953 &self,1954 sender: T::CrossAccountId,1955 properties: Vec<Property>,1956 ) -> DispatchResultWithPostInfo;19571958 /// Delete collection properties.1959 ///1960 /// * `sender` - Must be either the owner of the collection or its admin.1961 /// * `properties` - The properties to be removed.1962 fn delete_collection_properties(1963 &self,1964 sender: &T::CrossAccountId,1965 property_keys: Vec<PropertyKey>,1966 ) -> DispatchResultWithPostInfo;19671968 /// Set token properties.1969 ///1970 /// The appropriate [`PropertyPermission`] for the token property1971 /// must be set with [`Self::set_token_property_permissions`].1972 ///1973 /// * `sender` - Must be either the owner of the token or its admin.1974 /// * `token_id` - The token for which the properties are being set.1975 /// * `properties` - Properties to be set.1976 /// * `budget` - Budget for setting properties.1977 fn set_token_properties(1978 &self,1979 sender: T::CrossAccountId,1980 token_id: TokenId,1981 properties: Vec<Property>,1982 budget: &dyn Budget,1983 ) -> DispatchResultWithPostInfo;19841985 /// Remove token properties.1986 ///1987 /// The appropriate [`PropertyPermission`] for the token property1988 /// must be set with [`Self::set_token_property_permissions`].1989 ///1990 /// * `sender` - Must be either the owner of the token or its admin.1991 /// * `token_id` - The token for which the properties are being remove.1992 /// * `property_keys` - Keys to remove corresponding properties.1993 /// * `budget` - Budget for removing properties.1994 fn delete_token_properties(1995 &self,1996 sender: T::CrossAccountId,1997 token_id: TokenId,1998 property_keys: Vec<PropertyKey>,1999 budget: &dyn Budget,2000 ) -> DispatchResultWithPostInfo;20012002 /// Set token property permissions.2003 ///2004 /// * `sender` - Must be either the owner of the token or its admin.2005 /// * `token_id` - The token for which the properties are being set.2006 /// * `property_permissions` - Property permissions to be set.2007 /// * `budget` - Budget for setting properties.2008 fn set_token_property_permissions(2009 &self,2010 sender: &T::CrossAccountId,2011 property_permissions: Vec<PropertyKeyPermission>,2012 ) -> DispatchResultWithPostInfo;20132014 /// Transfer amount of token pieces.2015 ///2016 /// * `sender` - Donor user.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(2022 &self,2023 sender: T::CrossAccountId,2024 to: T::CrossAccountId,2025 token: TokenId,2026 amount: u128,2027 budget: &dyn Budget,2028 ) -> DispatchResultWithPostInfo;20292030 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2031 ///2032 /// * `sender` - The user who grants access to the token.2033 /// * `spender` - The user to whom the rights are granted.2034 /// * `token` - The token to which access is granted.2035 /// * `amount` - The amount of pieces that another user can dispose of.2036 fn approve(2037 &self,2038 sender: T::CrossAccountId,2039 spender: T::CrossAccountId,2040 token: TokenId,2041 amount: u128,2042 ) -> DispatchResultWithPostInfo;20432044 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2045 ///2046 /// * `sender` - The user who grants access to the token.2047 /// * `from` - Spender's eth mirror.2048 /// * `to` - The user to whom the rights are granted.2049 /// * `token` - The token to which access is granted.2050 /// * `amount` - The amount of pieces that another user can dispose of.2051 fn approve_from(2052 &self,2053 sender: T::CrossAccountId,2054 from: T::CrossAccountId,2055 to: T::CrossAccountId,2056 token: TokenId,2057 amount: u128,2058 ) -> DispatchResultWithPostInfo;20592060 /// Send parts of a token owned by another user.2061 ///2062 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2063 ///2064 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2065 /// * `from` - The user who owns the token.2066 /// * `to` - Recepient user.2067 /// * `token` - The token of which parts are being sent.2068 /// * `amount` - The number of parts of the token that will be transferred.2069 /// * `budget` - The maximum budget that can be spent on the transfer.2070 fn transfer_from(2071 &self,2072 sender: T::CrossAccountId,2073 from: T::CrossAccountId,2074 to: T::CrossAccountId,2075 token: TokenId,2076 amount: u128,2077 budget: &dyn Budget,2078 ) -> DispatchResultWithPostInfo;20792080 /// Burn parts of a token owned by another user.2081 ///2082 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2083 ///2084 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2085 /// * `from` - The user who owns the token.2086 /// * `token` - The token of which parts are being sent.2087 /// * `amount` - The number of parts of the token that will be transferred.2088 /// * `budget` - The maximum budget that can be spent on the burn.2089 fn burn_from(2090 &self,2091 sender: T::CrossAccountId,2092 from: T::CrossAccountId,2093 token: TokenId,2094 amount: u128,2095 budget: &dyn Budget,2096 ) -> DispatchResultWithPostInfo;20972098 /// Check permission to nest token.2099 ///2100 /// * `sender` - The user who initiated the check.2101 /// * `from` - The token that is checked for embedding.2102 /// * `under` - Token under which to check.2103 /// * `budget` - The maximum budget that can be spent on the check.2104 fn check_nesting(2105 &self,2106 sender: T::CrossAccountId,2107 from: (CollectionId, TokenId),2108 under: TokenId,2109 budget: &dyn Budget,2110 ) -> DispatchResult;21112112 /// Nest one token into another.2113 ///2114 /// * `under` - Token holder.2115 /// * `to_nest` - Nested token.2116 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21172118 /// Unnest token.2119 ///2120 /// * `under` - Token holder.2121 /// * `to_nest` - Token to unnest.2122 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));21232124 /// Get all user tokens.2125 ///2126 /// * `account` - Account for which you need to get tokens.2127 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;21282129 /// Get all the tokens in the collection.2130 fn collection_tokens(&self) -> Vec<TokenId>;21312132 /// Check if the token exists.2133 ///2134 /// * `token` - Id token to check.2135 fn token_exists(&self, token: TokenId) -> bool;21362137 /// Get the id of the last minted token.2138 fn last_token_id(&self) -> TokenId;21392140 /// Get the owner of the token.2141 ///2142 /// * `token` - The token for which you need to find out the owner.2143 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;21442145 /// Returns 10 tokens owners in no particular order.2146 ///2147 /// * `token` - The token for which you need to find out the owners.2148 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;21492150 /// Get the value of the token property by key.2151 ///2152 /// * `token` - Token with the property to get.2153 /// * `key` - Property name.2154 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;21552156 /// Get a set of token properties by key vector.2157 ///2158 /// * `token` - Token with the property to get.2159 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2160 /// then all properties are returned.2161 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;21622163 /// Amount of unique collection tokens2164 fn total_supply(&self) -> u32;21652166 /// Amount of different tokens account has.2167 ///2168 /// * `account` - The account for which need to get the balance.2169 fn account_balance(&self, account: T::CrossAccountId) -> u32;21702171 /// Amount of specific token account have.2172 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;21732174 /// Amount of token pieces2175 fn total_pieces(&self, token: TokenId) -> Option<u128>;21762177 /// Get the number of parts of the token that a trusted user can manage.2178 ///2179 /// * `sender` - Trusted user.2180 /// * `spender` - Owner of the token.2181 /// * `token` - The token for which to get the value.2182 fn allowance(2183 &self,2184 sender: T::CrossAccountId,2185 spender: T::CrossAccountId,2186 token: TokenId,2187 ) -> u128;21882189 /// Get extension for RFT collection.2190 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;21912192 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2193 /// * `owner` - Token owner2194 /// * `operator` - Operator2195 /// * `approve` - Should operator status be granted or revoked?2196 fn set_allowance_for_all(2197 &self,2198 owner: T::CrossAccountId,2199 operator: T::CrossAccountId,2200 approve: bool,2201 ) -> DispatchResultWithPostInfo;22022203 /// Tells whether the given `owner` approves the `operator`.2204 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;22052206 /// Repairs a possibly broken item.2207 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2208}22092210/// Extension for RFT collection.2211pub trait RefungibleExtensions<T>2212where2213 T: Config,2214{2215 /// Change the number of parts of the token.2216 ///2217 /// When the value changes down, this function is equivalent to burning parts of the token.2218 ///2219 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2220 /// * `token` - The token for which you want to change the number of parts.2221 /// * `amount` - The new value of the parts of the token.2222 fn repartition(2223 &self,2224 sender: &T::CrossAccountId,2225 token: TokenId,2226 amount: u128,2227 ) -> DispatchResultWithPostInfo;2228}22292230/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2231///2232/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2233pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2234 let post_info = PostDispatchInfo {2235 actual_weight: Some(weight),2236 pays_fee: Pays::Yes,2237 };2238 match res {2239 Ok(()) => Ok(post_info),2240 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2241 }2242}22432244impl<T: Config> From<PropertiesError> for Error<T> {2245 fn from(error: PropertiesError) -> Self {2246 match error {2247 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2248 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2249 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2250 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2251 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2252 }2253 }2254}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::{57 ops::{Deref, DerefMut},58 slice::from_ref,59};60use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};61use sp_std::vec::Vec;62use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};63use evm_coder::ToLog;64use frame_support::{65 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},66 ensure,67 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},68 dispatch::Pays,69 transactional, fail,70};71use pallet_evm::GasWeightMapping;72use up_data_structs::{73 AccessMode,74 COLLECTION_NUMBER_LIMIT,75 Collection,76 RpcCollection,77 CollectionFlags,78 RpcCollectionFlags,79 CollectionId,80 CreateItemData,81 MAX_TOKEN_PREFIX_LENGTH,82 COLLECTION_ADMINS_LIMIT,83 TokenId,84 TokenChild,85 CollectionStats,86 MAX_TOKEN_OWNERSHIP,87 CollectionMode,88 NFT_SPONSOR_TRANSFER_TIMEOUT,89 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,90 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,91 MAX_SPONSOR_TIMEOUT,92 CUSTOM_DATA_LIMIT,93 CollectionLimits,94 CreateCollectionData,95 SponsorshipState,96 CreateItemExData,97 SponsoringRateLimit,98 budget::Budget,99 PhantomType,100 Property,101 Properties,102 PropertiesPermissionMap,103 PropertyKey,104 PropertyValue,105 PropertyPermission,106 PropertiesError,107 TokenOwnerError,108 PropertyKeyPermission,109 TokenData,110 TrySetProperty,111 PropertyScope,112 // RMRK113 RmrkCollectionInfo,114 RmrkInstanceInfo,115 RmrkResourceInfo,116 RmrkPropertyInfo,117 RmrkBaseInfo,118 RmrkPartType,119 RmrkBoundedTheme,120 RmrkNftChild,121 CollectionPermissions,122};123use up_pov_estimate_rpc::PovInfo;124125pub use pallet::*;126use sp_core::H160;127use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};128129use crate::erc::CollectionHelpersEvents;130#[cfg(feature = "runtime-benchmarks")]131pub mod benchmarking;132pub mod dispatch;133pub mod erc;134pub mod eth;135pub mod weights;136137/// Weight info.138pub type SelfWeightOf<T> = <T as Config>::WeightInfo;139140/// Collection handle contains information about collection data and id.141/// Also provides functionality to count consumed gas.142///143/// CollectionHandle is used as a generic wrapper for collections of all types.144/// It allows to perform common operations and queries on any collection type,145/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].146#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]147pub struct CollectionHandle<T: Config> {148 /// Collection id149 pub id: CollectionId,150 collection: Collection<T::AccountId>,151 /// Substrate recorder for counting consumed gas152 pub recorder: SubstrateRecorder<T>,153}154155impl<T: Config> WithRecorder<T> for CollectionHandle<T> {156 fn recorder(&self) -> &SubstrateRecorder<T> {157 &self.recorder158 }159 fn into_recorder(self) -> SubstrateRecorder<T> {160 self.recorder161 }162}163164impl<T: Config> CollectionHandle<T> {165 /// Same as [CollectionHandle::new] but with an explicit gas limit.166 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder: SubstrateRecorder::new(gas_limit),171 })172 }173174 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].175 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {176 <CollectionById<T>>::get(id).map(|collection| Self {177 id,178 collection,179 recorder,180 })181 }182183 /// Retrives collection data from storage and creates collection handle with default parameters.184 /// If collection not found return `None`185 pub fn new(id: CollectionId) -> Option<Self> {186 Self::new_with_gas_limit(id, u64::MAX)187 }188189 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.190 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {191 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)192 }193194 /// Consume gas for reading.195 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {196 self.recorder197 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(198 <T as frame_system::Config>::DbWeight::get()199 .read200 .saturating_mul(reads),201 )))202 }203204 /// Consume gas for writing.205 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {206 self.recorder207 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(208 <T as frame_system::Config>::DbWeight::get()209 .write210 .saturating_mul(writes),211 )))212 }213214 /// Consume gas for reading and writing.215 pub fn consume_store_reads_and_writes(216 &self,217 reads: u64,218 writes: u64,219 ) -> evm_coder::execution::Result<()> {220 let weight = <T as frame_system::Config>::DbWeight::get();221 let reads = weight.read.saturating_mul(reads);222 let writes = weight.read.saturating_mul(writes);223 self.recorder224 .consume_gas(T::GasWeightMapping::weight_to_gas(Weight::from_ref_time(225 reads.saturating_add(writes),226 )))227 }228229 /// Save collection to storage.230 pub fn save(&self) -> DispatchResult {231 <CollectionById<T>>::insert(self.id, &self.collection);232 Ok(())233 }234235 /// Set collection sponsor.236 ///237 /// Unique collections allows sponsoring for certain actions.238 /// This method allows you to set the sponsor of the collection.239 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].240 pub fn set_sponsor(241 &mut self,242 sender: &T::CrossAccountId,243 sponsor: T::AccountId,244 ) -> DispatchResult {245 self.check_is_internal()?;246 self.check_is_owner_or_admin(sender)?;247248 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor.clone());249250 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor));251 <PalletEvm<T>>::deposit_log(252 erc::CollectionHelpersEvents::CollectionChanged {253 collection_id: eth::collection_id_to_address(self.id),254 }255 .to_log(T::ContractAddress::get()),256 );257258 self.save()259 }260261 /// Force set `sponsor`.262 ///263 /// Differs from [`set_sponsor`][`Self::set_sponsor`] in that confirmation264 /// from the `sponsor` is not required.265 ///266 /// # Arguments267 ///268 /// * `sender`: Caller's account.269 /// * `sponsor`: ID of the account of the sponsor-to-be.270 pub fn force_set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {271 self.check_is_internal()?;272273 self.collection.sponsorship = SponsorshipState::Confirmed(sponsor.clone());274275 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorSet(self.id, sponsor.clone()));276 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sponsor));277 <PalletEvm<T>>::deposit_log(278 erc::CollectionHelpersEvents::CollectionChanged {279 collection_id: eth::collection_id_to_address(self.id),280 }281 .to_log(T::ContractAddress::get()),282 );283284 self.save()285 }286287 /// Confirm sponsorship288 ///289 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.290 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].291 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> DispatchResult {292 self.check_is_internal()?;293 ensure!(294 self.collection.sponsorship.pending_sponsor() == Some(sender),295 Error::<T>::ConfirmSponsorshipFail296 );297298 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());299300 <Pallet<T>>::deposit_event(Event::<T>::SponsorshipConfirmed(self.id, sender.clone()));301 <PalletEvm<T>>::deposit_log(302 erc::CollectionHelpersEvents::CollectionChanged {303 collection_id: eth::collection_id_to_address(self.id),304 }305 .to_log(T::ContractAddress::get()),306 );307308 self.save()309 }310311 /// Remove collection sponsor.312 pub fn remove_sponsor(&mut self, sender: &T::CrossAccountId) -> DispatchResult {313 self.check_is_internal()?;314 self.check_is_owner_or_admin(sender)?;315316 self.collection.sponsorship = SponsorshipState::Disabled;317318 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));319 <PalletEvm<T>>::deposit_log(320 erc::CollectionHelpersEvents::CollectionChanged {321 collection_id: eth::collection_id_to_address(self.id),322 }323 .to_log(T::ContractAddress::get()),324 );325 self.save()326 }327328 /// Force remove `sponsor`.329 ///330 /// Differs from `remove_sponsor` in that331 /// it doesn't require consent from the `owner` of the collection.332 pub fn force_remove_sponsor(&mut self) -> DispatchResult {333 self.check_is_internal()?;334335 self.collection.sponsorship = SponsorshipState::Disabled;336337 <Pallet<T>>::deposit_event(Event::<T>::CollectionSponsorRemoved(self.id));338 <PalletEvm<T>>::deposit_log(339 erc::CollectionHelpersEvents::CollectionChanged {340 collection_id: eth::collection_id_to_address(self.id),341 }342 .to_log(T::ContractAddress::get()),343 );344 self.save()345 }346347 /// Checks that the collection was created with, and must be operated upon through **Unique API**.348 /// Now check only the `external` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.349 pub fn check_is_internal(&self) -> DispatchResult {350 if self.flags.external {351 return Err(<Error<T>>::CollectionIsExternal)?;352 }353354 Ok(())355 }356357 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.358 /// Now check only the `external` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.359 pub fn check_is_external(&self) -> DispatchResult {360 if !self.flags.external {361 return Err(<Error<T>>::CollectionIsInternal)?;362 }363364 Ok(())365 }366}367368impl<T: Config> Deref for CollectionHandle<T> {369 type Target = Collection<T::AccountId>;370371 fn deref(&self) -> &Self::Target {372 &self.collection373 }374}375376impl<T: Config> DerefMut for CollectionHandle<T> {377 fn deref_mut(&mut self) -> &mut Self::Target {378 &mut self.collection379 }380}381382impl<T: Config> CollectionHandle<T> {383 /// Checks if the `user` is the owner of the collection.384 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {385 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);386 Ok(())387 }388389 /// Returns **true** if the `user` is the owner or administrator of the collection.390 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {391 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))392 }393394 /// Checks if the `user` is the owner or administrator of the collection.395 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {396 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);397 Ok(())398 }399400 /// Returns **true** if401 /// * the `user`is a collection owner or admin402 /// * the collection limits allow the owner/admins to transfer/burn any collection token403 pub fn ignores_token_restrictions(&self, user: &T::CrossAccountId) -> bool {404 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)405 }406407 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.408 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {409 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)410 }411412 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.413 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {414 ensure!(415 <Allowlist<T>>::get((self.id, user)),416 <Error<T>>::AddressNotInAllowlist417 );418 Ok(())419 }420421 /// Changes collection owner to another account422 /// #### Store read/writes423 /// 1 writes424 pub fn change_owner(425 &mut self,426 caller: T::CrossAccountId,427 new_owner: T::CrossAccountId,428 ) -> DispatchResult {429 self.check_is_internal()?;430 self.check_is_owner(&caller)?;431 self.collection.owner = new_owner.as_sub().clone();432433 <Pallet<T>>::deposit_event(Event::<T>::CollectionOwnerChanged(434 self.id,435 new_owner.as_sub().clone(),436 ));437 <PalletEvm<T>>::deposit_log(438 erc::CollectionHelpersEvents::CollectionChanged {439 collection_id: eth::collection_id_to_address(self.id),440 }441 .to_log(T::ContractAddress::get()),442 );443444 self.save()445 }446}447448#[frame_support::pallet]449pub mod pallet {450 use super::*;451 use dispatch::CollectionDispatch;452 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};453 use frame_system::pallet_prelude::*;454 use frame_support::traits::Currency;455 use up_data_structs::{TokenId, mapping::TokenAddressMapping};456 use scale_info::TypeInfo;457 use weights::WeightInfo;458459 #[pallet::config]460 pub trait Config:461 frame_system::Config + pallet_evm_coder_substrate::Config + pallet_evm::Config + TypeInfo462 {463 /// Weight information for functions of this pallet.464 type WeightInfo: WeightInfo;465466 /// Events compatible with [`frame_system::Config::Event`].467 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;468469 /// Handler of accounts and payment.470 type Currency: Currency<Self::AccountId>;471472 /// Set price to create a collection.473 #[pallet::constant]474 type CollectionCreationPrice: Get<475 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,476 >;477478 /// Dispatcher of operations on collections.479 type CollectionDispatch: CollectionDispatch<Self>;480481 /// Account which holds the chain's treasury.482 type TreasuryAccountId: Get<Self::AccountId>;483484 /// Address under which the CollectionHelper contract would be available.485 #[pallet::constant]486 type ContractAddress: Get<H160>;487488 /// Mapper for token addresses to Ethereum addresses.489 type EvmTokenAddressMapping: TokenAddressMapping<H160>;490491 /// Mapper for token addresses to [`CrossAccountId`].492 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;493 }494495 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);496497 #[pallet::pallet]498 #[pallet::storage_version(STORAGE_VERSION)]499 #[pallet::generate_store(pub(super) trait Store)]500 pub struct Pallet<T>(_);501502 #[pallet::extra_constants]503 impl<T: Config> Pallet<T> {504 /// Maximum admins per collection.505 pub fn collection_admins_limit() -> u32 {506 COLLECTION_ADMINS_LIMIT507 }508 }509510 impl<T: Config> Pallet<T> {511 /// Helper function that handles deposit events512 pub fn deposit_event(event: Event<T>) {513 let event = <T as Config>::RuntimeEvent::from(event);514 let event = event.into();515 <frame_system::Pallet<T>>::deposit_event(event)516 }517 }518519 #[pallet::event]520 pub enum Event<T: Config> {521 /// New collection was created522 CollectionCreated(523 /// Globally unique identifier of newly created collection.524 CollectionId,525 /// [`CollectionMode`] converted into _u8_.526 u8,527 /// Collection owner.528 T::AccountId,529 ),530531 /// New collection was destroyed532 CollectionDestroyed(533 /// Globally unique identifier of collection.534 CollectionId,535 ),536537 /// New item was created.538 ItemCreated(539 /// Id of the collection where item was created.540 CollectionId,541 /// Id of an item. Unique within the collection.542 TokenId,543 /// Owner of newly created item544 T::CrossAccountId,545 /// Always 1 for NFT546 u128,547 ),548549 /// Collection item was burned.550 ItemDestroyed(551 /// Id of the collection where item was destroyed.552 CollectionId,553 /// Identifier of burned NFT.554 TokenId,555 /// Which user has destroyed its tokens.556 T::CrossAccountId,557 /// Amount of token pieces destroed. Always 1 for NFT.558 u128,559 ),560561 /// Item was transferred562 Transfer(563 /// Id of collection to which item is belong.564 CollectionId,565 /// Id of an item.566 TokenId,567 /// Original owner of item.568 T::CrossAccountId,569 /// New owner of item.570 T::CrossAccountId,571 /// Amount of token pieces transfered. Always 1 for NFT.572 u128,573 ),574575 /// Amount pieces of token owned by `sender` was approved for `spender`.576 Approved(577 /// Id of collection to which item is belong.578 CollectionId,579 /// Id of an item.580 TokenId,581 /// Original owner of item.582 T::CrossAccountId,583 /// Id for which the approval was granted.584 T::CrossAccountId,585 /// Amount of token pieces transfered. Always 1 for NFT.586 u128,587 ),588589 /// A `sender` approves operations on all owned tokens for `spender`.590 ApprovedForAll(591 /// Id of collection to which item is belong.592 CollectionId,593 /// Owner of a wallet.594 T::CrossAccountId,595 /// Id for which operator status was granted or rewoked.596 T::CrossAccountId,597 /// Is operator status granted or revoked?598 bool,599 ),600601 /// The colletion property has been added or edited.602 CollectionPropertySet(603 /// Id of collection to which property has been set.604 CollectionId,605 /// The property that was set.606 PropertyKey,607 ),608609 /// The property has been deleted.610 CollectionPropertyDeleted(611 /// Id of collection to which property has been deleted.612 CollectionId,613 /// The property that was deleted.614 PropertyKey,615 ),616617 /// The token property has been added or edited.618 TokenPropertySet(619 /// Identifier of the collection whose token has the property set.620 CollectionId,621 /// The token for which the property was set.622 TokenId,623 /// The property that was set.624 PropertyKey,625 ),626627 /// The token property has been deleted.628 TokenPropertyDeleted(629 /// Identifier of the collection whose token has the property deleted.630 CollectionId,631 /// The token for which the property was deleted.632 TokenId,633 /// The property that was deleted.634 PropertyKey,635 ),636637 /// The token property permission of a collection has been set.638 PropertyPermissionSet(639 /// ID of collection to which property permission has been set.640 CollectionId,641 /// The property permission that was set.642 PropertyKey,643 ),644645 /// Address was added to the allow list.646 AllowListAddressAdded(647 /// ID of the affected collection.648 CollectionId,649 /// Address of the added account.650 T::CrossAccountId,651 ),652653 /// Address was removed from the allow list.654 AllowListAddressRemoved(655 /// ID of the affected collection.656 CollectionId,657 /// Address of the removed account.658 T::CrossAccountId,659 ),660661 /// Collection admin was added.662 CollectionAdminAdded(663 /// ID of the affected collection.664 CollectionId,665 /// Admin address.666 T::CrossAccountId,667 ),668669 /// Collection admin was removed.670 CollectionAdminRemoved(671 /// ID of the affected collection.672 CollectionId,673 /// Removed admin address.674 T::CrossAccountId,675 ),676677 /// Collection limits were set.678 CollectionLimitSet(679 /// ID of the affected collection.680 CollectionId,681 ),682683 /// Collection owned was changed.684 CollectionOwnerChanged(685 /// ID of the affected collection.686 CollectionId,687 /// New owner address.688 T::AccountId,689 ),690691 /// Collection permissions were set.692 CollectionPermissionSet(693 /// ID of the affected collection.694 CollectionId,695 ),696697 /// Collection sponsor was set.698 CollectionSponsorSet(699 /// ID of the affected collection.700 CollectionId,701 /// New sponsor address.702 T::AccountId,703 ),704705 /// New sponsor was confirm.706 SponsorshipConfirmed(707 /// ID of the affected collection.708 CollectionId,709 /// New sponsor address.710 T::AccountId,711 ),712713 /// Collection sponsor was removed.714 CollectionSponsorRemoved(715 /// ID of the affected collection.716 CollectionId,717 ),718 }719720 #[pallet::error]721 pub enum Error<T> {722 /// This collection does not exist.723 CollectionNotFound,724 /// Sender parameter and item owner must be equal.725 MustBeTokenOwner,726 /// No permission to perform action727 NoPermission,728 /// Destroying only empty collections is allowed729 CantDestroyNotEmptyCollection,730 /// Collection is not in mint mode.731 PublicMintingNotAllowed,732 /// Address is not in allow list.733 AddressNotInAllowlist,734735 /// Collection name can not be longer than 63 char.736 CollectionNameLimitExceeded,737 /// Collection description can not be longer than 255 char.738 CollectionDescriptionLimitExceeded,739 /// Token prefix can not be longer than 15 char.740 CollectionTokenPrefixLimitExceeded,741 /// Total collections bound exceeded.742 TotalCollectionsLimitExceeded,743 /// Exceeded max admin count744 CollectionAdminCountExceeded,745 /// Collection limit bounds per collection exceeded746 CollectionLimitBoundsExceeded,747 /// Tried to enable permissions which are only permitted to be disabled748 OwnerPermissionsCantBeReverted,749 /// Collection settings not allowing items transferring750 TransferNotAllowed,751 /// Account token limit exceeded per collection752 AccountTokenLimitExceeded,753 /// Collection token limit exceeded754 CollectionTokenLimitExceeded,755 /// Metadata flag frozen756 MetadataFlagFrozen,757758 /// Item does not exist759 TokenNotFound,760 /// Item is balance not enough761 TokenValueTooLow,762 /// Requested value is more than the approved763 ApprovedValueTooLow,764 /// Tried to approve more than owned765 CantApproveMoreThanOwned,766 /// Only spending from eth mirror could be approved767 AddressIsNotEthMirror,768769 /// Can't transfer tokens to ethereum zero address770 AddressIsZero,771772 /// The operation is not supported773 UnsupportedOperation,774775 /// Insufficient funds to perform an action776 NotSufficientFounds,777778 /// User does not satisfy the nesting rule779 UserIsNotAllowedToNest,780 /// Only tokens from specific collections may nest tokens under this one781 SourceCollectionIsNotAllowedToNest,782783 /// Tried to store more data than allowed in collection field784 CollectionFieldSizeExceeded,785786 /// Tried to store more property data than allowed787 NoSpaceForProperty,788789 /// Tried to store more property keys than allowed790 PropertyLimitReached,791792 /// Property key is too long793 PropertyKeyIsTooLong,794795 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed796 InvalidCharacterInPropertyKey,797798 /// Empty property keys are forbidden799 EmptyPropertyKey,800801 /// Tried to access an external collection with an internal API802 CollectionIsExternal,803804 /// Tried to access an internal collection with an external API805 CollectionIsInternal,806807 /// This address is not set as sponsor, use setCollectionSponsor first.808 ConfirmSponsorshipFail,809810 /// The user is not an administrator.811 UserIsNotCollectionAdmin,812 }813814 /// Storage of the count of created collections. Essentially contains the last collection ID.815 #[pallet::storage]816 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;817818 /// Storage of the count of deleted collections.819 #[pallet::storage]820 pub type DestroyedCollectionCount<T> =821 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;822823 /// Storage of collection info.824 #[pallet::storage]825 pub type CollectionById<T> = StorageMap<826 Hasher = Blake2_128Concat,827 Key = CollectionId,828 Value = Collection<<T as frame_system::Config>::AccountId>,829 QueryKind = OptionQuery,830 >;831832 /// Storage of collection properties.833 #[pallet::storage]834 #[pallet::getter(fn collection_properties)]835 pub type CollectionProperties<T> = StorageMap<836 Hasher = Blake2_128Concat,837 Key = CollectionId,838 Value = Properties,839 QueryKind = ValueQuery,840 OnEmpty = up_data_structs::CollectionProperties,841 >;842843 /// Storage of token property permissions of a collection.844 #[pallet::storage]845 #[pallet::getter(fn property_permissions)]846 pub type CollectionPropertyPermissions<T> = StorageMap<847 Hasher = Blake2_128Concat,848 Key = CollectionId,849 Value = PropertiesPermissionMap,850 QueryKind = ValueQuery,851 >;852853 /// Storage of the amount of collection admins.854 #[pallet::storage]855 pub type AdminAmount<T> = StorageMap<856 Hasher = Blake2_128Concat,857 Key = CollectionId,858 Value = u32,859 QueryKind = ValueQuery,860 >;861862 /// List of collection admins.863 #[pallet::storage]864 pub type IsAdmin<T: Config> = StorageNMap<865 Key = (866 Key<Blake2_128Concat, CollectionId>,867 Key<Blake2_128Concat, T::CrossAccountId>,868 ),869 Value = bool,870 QueryKind = ValueQuery,871 >;872873 /// Allowlisted collection users.874 #[pallet::storage]875 pub type Allowlist<T: Config> = StorageNMap<876 Key = (877 Key<Blake2_128Concat, CollectionId>,878 Key<Blake2_128Concat, T::CrossAccountId>,879 ),880 Value = bool,881 QueryKind = ValueQuery,882 >;883884 /// Not used by code, exists only to provide some types to metadata.885 #[pallet::storage]886 pub type DummyStorageValue<T: Config> = StorageValue<887 Value = (888 CollectionStats,889 CollectionId,890 TokenId,891 TokenChild,892 PhantomType<(893 TokenData<T::CrossAccountId>,894 RpcCollection<T::AccountId>,895 // RMRK896 RmrkCollectionInfo<T::AccountId>,897 RmrkInstanceInfo<T::AccountId>,898 RmrkResourceInfo,899 RmrkPropertyInfo,900 RmrkBaseInfo<T::AccountId>,901 RmrkPartType,902 RmrkBoundedTheme,903 RmrkNftChild,904 // PoV Estimate Info905 PovInfo,906 )>,907 ),908 QueryKind = OptionQuery,909 >;910911 #[pallet::hooks]912 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {913 fn on_runtime_upgrade() -> Weight {914 StorageVersion::new(1).put::<Pallet<T>>();915916 Weight::zero()917 }918 }919}920921impl<T: Config> Pallet<T> {922 /// Enshure that receiver address is correct.923 ///924 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.925 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {926 ensure!(927 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,928 <Error<T>>::AddressIsZero929 );930 Ok(())931 }932933 /// Get a vector of collection admins.934 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {935 <IsAdmin<T>>::iter_prefix((collection,))936 .map(|(a, _)| a)937 .collect()938 }939940 /// Get a vector of users allowed to mint tokens.941 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {942 <Allowlist<T>>::iter_prefix((collection,))943 .map(|(a, _)| a)944 .collect()945 }946947 /// Is `user` allowed to mint token in `collection`.948 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {949 <Allowlist<T>>::get((collection, user))950 }951952 /// Get statistics of collections.953 pub fn collection_stats() -> CollectionStats {954 let created = <CreatedCollectionCount<T>>::get();955 let destroyed = <DestroyedCollectionCount<T>>::get();956 CollectionStats {957 created: created.0,958 destroyed: destroyed.0,959 alive: created.0 - destroyed.0,960 }961 }962963 /// Get the effective limits for the collection.964 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {965 let collection = <CollectionById<T>>::get(collection)?;966 let limits = collection.limits;967 let effective_limits = CollectionLimits {968 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),969 sponsored_data_size: Some(limits.sponsored_data_size()),970 sponsored_data_rate_limit: Some(971 limits972 .sponsored_data_rate_limit973 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),974 ),975 token_limit: Some(limits.token_limit()),976 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(977 match collection.mode {978 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,979 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,980 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,981 },982 )),983 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),984 owner_can_transfer: Some(limits.owner_can_transfer()),985 owner_can_destroy: Some(limits.owner_can_destroy()),986 transfers_enabled: Some(limits.transfers_enabled()),987 };988989 Some(effective_limits)990 }991992 /// Returns information about the `collection` adapted for rpc.993 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {994 let Collection {995 name,996 description,997 owner,998 mode,999 token_prefix,1000 sponsorship,1001 limits,1002 permissions,1003 flags,1004 } = <CollectionById<T>>::get(collection)?;10051006 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)1007 .into_iter()1008 .map(|(key, permission)| PropertyKeyPermission { key, permission })1009 .collect();10101011 let properties = <CollectionProperties<T>>::get(collection)1012 .into_iter()1013 .map(|(key, value)| Property { key, value })1014 .collect();10151016 let permissions = CollectionPermissions {1017 access: Some(permissions.access()),1018 mint_mode: Some(permissions.mint_mode()),1019 nesting: Some(permissions.nesting().clone()),1020 };10211022 Some(RpcCollection {1023 name: name.into_inner(),1024 description: description.into_inner(),1025 owner,1026 mode,1027 token_prefix: token_prefix.into_inner(),1028 sponsorship,1029 limits,1030 permissions,1031 token_property_permissions,1032 properties,1033 read_only: flags.external,10341035 flags: RpcCollectionFlags {1036 foreign: flags.foreign,1037 erc721metadata: flags.erc721metadata,1038 },1039 })1040 }1041}10421043macro_rules! limit_default {1044 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1045 $(1046 if let Some($new) = $new.$field {1047 let $old = $old.$field($($arg)?);1048 let _ = $new;1049 let _ = $old;1050 $check1051 } else {1052 $new.$field = $old.$field1053 }1054 )*1055 }};1056}1057macro_rules! limit_default_clone {1058 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{1059 $(1060 if let Some($new) = $new.$field.clone() {1061 let $old = $old.$field($($arg)?);1062 let _ = $new;1063 let _ = $old;1064 $check1065 } else {1066 $new.$field = $old.$field.clone()1067 }1068 )*1069 }};1070}10711072impl<T: Config> Pallet<T> {1073 /// Create new collection.1074 ///1075 /// * `owner` - The owner of the collection.1076 /// * `data` - Description of the created collection.1077 /// * `flags` - Extra flags to store.1078 pub fn init_collection(1079 owner: T::CrossAccountId,1080 payer: T::CrossAccountId,1081 data: CreateCollectionData<T::AccountId>,1082 flags: CollectionFlags,1083 ) -> Result<CollectionId, DispatchError> {1084 {1085 ensure!(1086 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,1087 Error::<T>::CollectionTokenPrefixLimitExceeded1088 );1089 }10901091 let created_count = <CreatedCollectionCount<T>>::get()1092 .01093 .checked_add(1)1094 .ok_or(ArithmeticError::Overflow)?;1095 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;1096 let id = CollectionId(created_count);10971098 // bound Total number of collections1099 ensure!(1100 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,1101 <Error<T>>::TotalCollectionsLimitExceeded1102 );11031104 // =========11051106 let collection = Collection {1107 owner: owner.as_sub().clone(),1108 name: data.name,1109 mode: data.mode.clone(),1110 description: data.description,1111 token_prefix: data.token_prefix,1112 sponsorship: data1113 .pending_sponsor1114 .map(SponsorshipState::Unconfirmed)1115 .unwrap_or_default(),1116 limits: data1117 .limits1118 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))1119 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,1120 permissions: data1121 .permissions1122 .map(|permissions| {1123 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)1124 })1125 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,1126 flags,1127 };11281129 let mut collection_properties = up_data_structs::CollectionProperties::get();1130 collection_properties1131 .try_set_from_iter(data.properties.into_iter())1132 .map_err(<Error<T>>::from)?;11331134 CollectionProperties::<T>::insert(id, collection_properties);11351136 let mut token_props_permissions = PropertiesPermissionMap::new();1137 token_props_permissions1138 .try_set_from_iter(data.token_property_permissions.into_iter())1139 .map_err(<Error<T>>::from)?;11401141 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);11421143 // Take a (non-refundable) deposit of collection creation1144 {1145 let mut imbalance =1146 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();1147 imbalance.subsume(1148 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(1149 &T::TreasuryAccountId::get(),1150 T::CollectionCreationPrice::get(),1151 ),1152 );1153 <T as Config>::Currency::settle(1154 payer.as_sub(),1155 imbalance,1156 WithdrawReasons::TRANSFER,1157 ExistenceRequirement::KeepAlive,1158 )1159 .map_err(|_| Error::<T>::NotSufficientFounds)?;1160 }11611162 <CreatedCollectionCount<T>>::put(created_count);1163 <Pallet<T>>::deposit_event(Event::CollectionCreated(1164 id,1165 data.mode.id(),1166 owner.as_sub().clone(),1167 ));1168 <PalletEvm<T>>::deposit_log(1169 erc::CollectionHelpersEvents::CollectionCreated {1170 owner: *owner.as_eth(),1171 collection_id: eth::collection_id_to_address(id),1172 }1173 .to_log(T::ContractAddress::get()),1174 );1175 <CollectionById<T>>::insert(id, collection);1176 Ok(id)1177 }11781179 /// Destroy collection.1180 ///1181 /// * `collection` - Collection handler.1182 /// * `sender` - The owner or administrator of the collection.1183 pub fn destroy_collection(1184 collection: CollectionHandle<T>,1185 sender: &T::CrossAccountId,1186 ) -> DispatchResult {1187 ensure!(1188 collection.limits.owner_can_destroy(),1189 <Error<T>>::NoPermission,1190 );1191 collection.check_is_owner(sender)?;11921193 let destroyed_collections = <DestroyedCollectionCount<T>>::get()1194 .01195 .checked_add(1)1196 .ok_or(ArithmeticError::Overflow)?;11971198 // =========11991200 <DestroyedCollectionCount<T>>::put(destroyed_collections);1201 <CollectionById<T>>::remove(collection.id);1202 <AdminAmount<T>>::remove(collection.id);1203 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);1204 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);1205 <CollectionProperties<T>>::remove(collection.id);12061207 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));12081209 <PalletEvm<T>>::deposit_log(1210 erc::CollectionHelpersEvents::CollectionDestroyed {1211 collection_id: eth::collection_id_to_address(collection.id),1212 }1213 .to_log(T::ContractAddress::get()),1214 );1215 Ok(())1216 }12171218 /// This function sets or removes a collection properties according to1219 /// `properties_updates` contents:1220 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1221 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1222 ///1223 /// This function fires an event for each property change.1224 /// In case of an error, all the changes (including the events) will be reverted1225 /// since the function is transactional.1226 #[transactional]1227 fn modify_collection_properties(1228 collection: &CollectionHandle<T>,1229 sender: &T::CrossAccountId,1230 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1231 ) -> DispatchResult {1232 collection.check_is_owner_or_admin(sender)?;12331234 let mut stored_properties = <CollectionProperties<T>>::get(collection.id);12351236 for (key, value) in properties_updates {1237 match value {1238 Some(value) => {1239 stored_properties1240 .try_set(key.clone(), value)1241 .map_err(<Error<T>>::from)?;12421243 Self::deposit_event(Event::CollectionPropertySet(collection.id, key));1244 <PalletEvm<T>>::deposit_log(1245 erc::CollectionHelpersEvents::CollectionChanged {1246 collection_id: eth::collection_id_to_address(collection.id),1247 }1248 .to_log(T::ContractAddress::get()),1249 );1250 }1251 None => {1252 stored_properties.remove(&key).map_err(<Error<T>>::from)?;12531254 Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, key));1255 <PalletEvm<T>>::deposit_log(1256 erc::CollectionHelpersEvents::CollectionChanged {1257 collection_id: eth::collection_id_to_address(collection.id),1258 }1259 .to_log(T::ContractAddress::get()),1260 );1261 }1262 }1263 }12641265 <CollectionProperties<T>>::set(collection.id, stored_properties);12661267 Ok(())1268 }12691270 /// A batch operation to add, edit or remove properties for a token.1271 /// It sets or removes a token's properties according to1272 /// `properties_updates` contents:1273 /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`1274 /// * removes a property under the <key> if the value is `None` `(<key>, None)`.1275 ///1276 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.1277 /// - `is_token_create`: Indicates that method is called during token initialization.1278 /// Allows to bypass ownership check.1279 ///1280 /// All affected properties should have `mutable` permission1281 /// to be **deleted** or to be **set more than once**,1282 /// and the sender should have permission to edit those properties.1283 ///1284 /// This function fires an event for each property change.1285 /// In case of an error, all the changes (including the events) will be reverted1286 /// since the function is transactional.1287 pub fn modify_token_properties(1288 collection: &CollectionHandle<T>,1289 sender: &T::CrossAccountId,1290 token_id: TokenId,1291 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,1292 is_token_create: bool,1293 mut stored_properties: Properties,1294 is_token_owner: impl Fn() -> Result<bool, DispatchError>,1295 set_token_properties: impl FnOnce(Properties),1296 ) -> DispatchResult {1297 let is_collection_admin = collection.is_owner_or_admin(sender);1298 let permissions = Self::property_permissions(collection.id);12991300 let mut token_owner_result = None;1301 let mut is_token_owner = || -> Result<bool, DispatchError> {1302 *token_owner_result.get_or_insert_with(&is_token_owner)1303 };13041305 for (key, value) in properties_updates {1306 let permission = permissions1307 .get(&key)1308 .cloned()1309 .unwrap_or_else(PropertyPermission::none);13101311 let is_property_exists = stored_properties.get(&key).is_some();13121313 match permission {1314 PropertyPermission { mutable: false, .. } if is_property_exists => {1315 return Err(<Error<T>>::NoPermission.into());1316 }13171318 PropertyPermission {1319 collection_admin,1320 token_owner,1321 ..1322 } => {1323 //TODO: investigate threats during public minting.1324 let is_token_create =1325 is_token_create && (collection_admin || token_owner) && value.is_some();1326 if !(is_token_create1327 || (collection_admin && is_collection_admin)1328 || (token_owner && is_token_owner()?))1329 {1330 fail!(<Error<T>>::NoPermission);1331 }1332 }1333 }13341335 match value {1336 Some(value) => {1337 stored_properties1338 .try_set(key.clone(), value)1339 .map_err(<Error<T>>::from)?;13401341 Self::deposit_event(Event::TokenPropertySet(collection.id, token_id, key));1342 }1343 None => {1344 stored_properties.remove(&key).map_err(<Error<T>>::from)?;13451346 Self::deposit_event(Event::TokenPropertyDeleted(collection.id, token_id, key));1347 }1348 }13491350 <PalletEvm<T>>::deposit_log(1351 CollectionHelpersEvents::TokenChanged {1352 collection_id: eth::collection_id_to_address(collection.id),1353 token_id: token_id.into(),1354 }1355 .to_log(T::ContractAddress::get()),1356 );1357 }13581359 set_token_properties(stored_properties);13601361 Ok(())1362 }13631364 /// Sets or unsets the approval of a given operator.1365 ///1366 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1367 /// - `owner`: Token owner1368 /// - `operator`: Operator1369 /// - `approve`: Should operator status be granted or revoked?1370 pub fn set_allowance_for_all(1371 collection: &CollectionHandle<T>,1372 owner: &T::CrossAccountId,1373 operator: &T::CrossAccountId,1374 approve: bool,1375 set_allowance: impl FnOnce(),1376 log: evm_coder::ethereum::Log,1377 ) -> DispatchResult {1378 if collection.permissions.access() == AccessMode::AllowList {1379 collection.check_allowlist(owner)?;1380 collection.check_allowlist(operator)?;1381 }13821383 Self::ensure_correct_receiver(operator)?;13841385 set_allowance();13861387 <PalletEvm<T>>::deposit_log(log);1388 Self::deposit_event(Event::ApprovedForAll(1389 collection.id,1390 owner.clone(),1391 operator.clone(),1392 approve,1393 ));1394 Ok(())1395 }13961397 /// Set collection property.1398 ///1399 /// * `collection` - Collection handler.1400 /// * `sender` - The owner or administrator of the collection.1401 /// * `property` - The property to set.1402 pub fn set_collection_property(1403 collection: &CollectionHandle<T>,1404 sender: &T::CrossAccountId,1405 property: Property,1406 ) -> DispatchResult {1407 Self::set_collection_properties(collection, sender, [property].into_iter())1408 }14091410 /// Set a scoped collection property, where the scope is a special prefix1411 /// prohibiting a user access to change the property directly.1412 ///1413 /// * `collection_id` - ID of the collection for which the property is being set.1414 /// * `scope` - Property scope.1415 /// * `property` - The property to set.1416 pub fn set_scoped_collection_property(1417 collection_id: CollectionId,1418 scope: PropertyScope,1419 property: Property,1420 ) -> DispatchResult {1421 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1422 properties.try_scoped_set(scope, property.key, property.value)1423 })1424 .map_err(<Error<T>>::from)?;14251426 Ok(())1427 }14281429 /// Set scoped collection properties, where the scope is a special prefix1430 /// prohibiting a user access to change the properties directly.1431 ///1432 /// * `collection_id` - ID of the collection for which the properties is being set.1433 /// * `scope` - Property scope.1434 /// * `properties` - The properties to set.1435 pub fn set_scoped_collection_properties(1436 collection_id: CollectionId,1437 scope: PropertyScope,1438 properties: impl Iterator<Item = Property>,1439 ) -> DispatchResult {1440 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1441 stored_properties.try_scoped_set_from_iter(scope, properties)1442 })1443 .map_err(<Error<T>>::from)?;14441445 Ok(())1446 }14471448 /// Set collection properties.1449 ///1450 /// * `collection` - Collection handler.1451 /// * `sender` - The owner or administrator of the collection.1452 /// * `properties` - The properties to set.1453 pub fn set_collection_properties(1454 collection: &CollectionHandle<T>,1455 sender: &T::CrossAccountId,1456 properties: impl Iterator<Item = Property>,1457 ) -> DispatchResult {1458 Self::modify_collection_properties(1459 collection,1460 sender,1461 properties.map(|property| (property.key, Some(property.value))),1462 )1463 }14641465 /// Delete collection property.1466 ///1467 /// * `collection` - Collection handler.1468 /// * `sender` - The owner or administrator of the collection.1469 /// * `property` - The property to delete.1470 pub fn delete_collection_property(1471 collection: &CollectionHandle<T>,1472 sender: &T::CrossAccountId,1473 property_key: PropertyKey,1474 ) -> DispatchResult {1475 Self::delete_collection_properties(collection, sender, [property_key].into_iter())1476 }14771478 /// Delete collection properties.1479 ///1480 /// * `collection` - Collection handler.1481 /// * `sender` - The owner or administrator of the collection.1482 /// * `properties` - The properties to delete.1483 pub fn delete_collection_properties(1484 collection: &CollectionHandle<T>,1485 sender: &T::CrossAccountId,1486 property_keys: impl Iterator<Item = PropertyKey>,1487 ) -> DispatchResult {1488 Self::modify_collection_properties(collection, sender, property_keys.map(|key| (key, None)))1489 }14901491 /// Set collection propetry permission without any checks.1492 ///1493 /// Used for migrations.1494 ///1495 /// * `collection` - Collection handler.1496 /// * `property_permissions` - Property permissions.1497 pub fn set_property_permission_unchecked(1498 collection: CollectionId,1499 property_permission: PropertyKeyPermission,1500 ) -> DispatchResult {1501 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1502 permissions.try_set(property_permission.key, property_permission.permission)1503 })1504 .map_err(<Error<T>>::from)?;1505 Ok(())1506 }15071508 /// Set collection property permission.1509 ///1510 /// * `collection` - Collection handler.1511 /// * `sender` - The owner or administrator of the collection.1512 /// * `property_permission` - Property permission.1513 pub fn set_property_permission(1514 collection: &CollectionHandle<T>,1515 sender: &T::CrossAccountId,1516 property_permission: PropertyKeyPermission,1517 ) -> DispatchResult {1518 Self::set_scoped_property_permission(1519 collection,1520 sender,1521 PropertyScope::None,1522 property_permission,1523 )1524 }15251526 /// Set collection property permission with scope.1527 ///1528 /// * `collection` - Collection handler.1529 /// * `sender` - The owner or administrator of the collection.1530 /// * `scope` - Property scope.1531 /// * `property_permission` - Property permission.1532 pub fn set_scoped_property_permission(1533 collection: &CollectionHandle<T>,1534 sender: &T::CrossAccountId,1535 scope: PropertyScope,1536 property_permission: PropertyKeyPermission,1537 ) -> DispatchResult {1538 collection.check_is_owner_or_admin(sender)?;15391540 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1541 let current_permission = all_permissions.get(&property_permission.key);1542 if matches![1543 current_permission,1544 Some(PropertyPermission { mutable: false, .. })1545 ] {1546 return Err(<Error<T>>::NoPermission.into());1547 }15481549 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1550 let property_permission = property_permission.clone();1551 permissions.try_scoped_set(1552 scope,1553 property_permission.key,1554 property_permission.permission,1555 )1556 })1557 .map_err(<Error<T>>::from)?;15581559 Self::deposit_event(Event::PropertyPermissionSet(1560 collection.id,1561 property_permission.key,1562 ));1563 <PalletEvm<T>>::deposit_log(1564 erc::CollectionHelpersEvents::CollectionChanged {1565 collection_id: eth::collection_id_to_address(collection.id),1566 }1567 .to_log(T::ContractAddress::get()),1568 );15691570 Ok(())1571 }15721573 /// Set token property permission.1574 ///1575 /// * `collection` - Collection handler.1576 /// * `sender` - The owner or administrator of the collection.1577 /// * `property_permissions` - Property permissions.1578 #[transactional]1579 pub fn set_token_property_permissions(1580 collection: &CollectionHandle<T>,1581 sender: &T::CrossAccountId,1582 property_permissions: Vec<PropertyKeyPermission>,1583 ) -> DispatchResult {1584 Self::set_scoped_token_property_permissions(1585 collection,1586 sender,1587 PropertyScope::None,1588 property_permissions,1589 )1590 }15911592 /// Set token property permission with scope.1593 ///1594 /// * `collection` - Collection handler.1595 /// * `sender` - The owner or administrator of the collection.1596 /// * `scope` - Property scope.1597 /// * `property_permissions` - Property permissions.1598 #[transactional]1599 pub fn set_scoped_token_property_permissions(1600 collection: &CollectionHandle<T>,1601 sender: &T::CrossAccountId,1602 scope: PropertyScope,1603 property_permissions: Vec<PropertyKeyPermission>,1604 ) -> DispatchResult {1605 for prop_pemission in property_permissions {1606 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1607 }16081609 Ok(())1610 }16111612 /// Get collection property.1613 pub fn get_collection_property(1614 collection_id: CollectionId,1615 key: &PropertyKey,1616 ) -> Option<PropertyValue> {1617 Self::collection_properties(collection_id).get(key).cloned()1618 }16191620 /// Convert byte vector to property key vector.1621 pub fn bytes_keys_to_property_keys(1622 keys: Vec<Vec<u8>>,1623 ) -> Result<Vec<PropertyKey>, DispatchError> {1624 keys.into_iter()1625 .map(|key| -> Result<PropertyKey, DispatchError> {1626 key.try_into()1627 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1628 })1629 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1630 }16311632 /// Get properties according to given keys.1633 pub fn filter_collection_properties(1634 collection_id: CollectionId,1635 keys: Option<Vec<PropertyKey>>,1636 ) -> Result<Vec<Property>, DispatchError> {1637 let properties = Self::collection_properties(collection_id);16381639 let properties = keys1640 .map(|keys| {1641 keys.into_iter()1642 .filter_map(|key| {1643 properties.get(&key).map(|value| Property {1644 key,1645 value: value.clone(),1646 })1647 })1648 .collect()1649 })1650 .unwrap_or_else(|| {1651 properties1652 .into_iter()1653 .map(|(key, value)| Property { key, value })1654 .collect()1655 });16561657 Ok(properties)1658 }16591660 /// Get property permissions according to given keys.1661 pub fn filter_property_permissions(1662 collection_id: CollectionId,1663 keys: Option<Vec<PropertyKey>>,1664 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1665 let permissions = Self::property_permissions(collection_id);16661667 let key_permissions = keys1668 .map(|keys| {1669 keys.into_iter()1670 .filter_map(|key| {1671 permissions1672 .get(&key)1673 .map(|permission| PropertyKeyPermission {1674 key,1675 permission: permission.clone(),1676 })1677 })1678 .collect()1679 })1680 .unwrap_or_else(|| {1681 permissions1682 .into_iter()1683 .map(|(key, permission)| PropertyKeyPermission { key, permission })1684 .collect()1685 });16861687 Ok(key_permissions)1688 }16891690 /// Toggle `user` participation in the `collection`'s allow list.1691 /// #### Store read/writes1692 /// 1 writes1693 pub fn toggle_allowlist(1694 collection: &CollectionHandle<T>,1695 sender: &T::CrossAccountId,1696 user: &T::CrossAccountId,1697 allowed: bool,1698 ) -> DispatchResult {1699 collection.check_is_owner_or_admin(sender)?;17001701 // =========17021703 if allowed {1704 <Allowlist<T>>::insert((collection.id, user), true);1705 Self::deposit_event(Event::<T>::AllowListAddressAdded(1706 collection.id,1707 user.clone(),1708 ));1709 } else {1710 <Allowlist<T>>::remove((collection.id, user));1711 Self::deposit_event(Event::<T>::AllowListAddressRemoved(1712 collection.id,1713 user.clone(),1714 ));1715 }17161717 <PalletEvm<T>>::deposit_log(1718 erc::CollectionHelpersEvents::CollectionChanged {1719 collection_id: eth::collection_id_to_address(collection.id),1720 }1721 .to_log(T::ContractAddress::get()),1722 );17231724 Ok(())1725 }17261727 /// Toggle `user` participation in the `collection`'s admin list.1728 /// #### Store read/writes1729 /// 2 reads, 2 writes1730 pub fn toggle_admin(1731 collection: &CollectionHandle<T>,1732 sender: &T::CrossAccountId,1733 user: &T::CrossAccountId,1734 admin: bool,1735 ) -> DispatchResult {1736 collection.check_is_internal()?;1737 collection.check_is_owner(sender)?;17381739 let is_admin = <IsAdmin<T>>::get((collection.id, user));1740 if is_admin == admin {1741 if admin {1742 return Ok(());1743 } else {1744 return Err(Error::<T>::UserIsNotCollectionAdmin.into());1745 }1746 }1747 let amount = <AdminAmount<T>>::get(collection.id);17481749 // =========17501751 if admin {1752 let amount = amount1753 .checked_add(1)1754 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1755 ensure!(1756 amount <= Self::collection_admins_limit(),1757 <Error<T>>::CollectionAdminCountExceeded,1758 );17591760 <AdminAmount<T>>::insert(collection.id, amount);1761 <IsAdmin<T>>::insert((collection.id, user), true);17621763 Self::deposit_event(Event::<T>::CollectionAdminAdded(1764 collection.id,1765 user.clone(),1766 ));1767 } else {1768 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1769 <IsAdmin<T>>::remove((collection.id, user));17701771 Self::deposit_event(Event::<T>::CollectionAdminRemoved(1772 collection.id,1773 user.clone(),1774 ));1775 }17761777 <PalletEvm<T>>::deposit_log(1778 erc::CollectionHelpersEvents::CollectionChanged {1779 collection_id: eth::collection_id_to_address(collection.id),1780 }1781 .to_log(T::ContractAddress::get()),1782 );17831784 Ok(())1785 }17861787 /// Update collection limits.1788 pub fn update_limits(1789 user: &T::CrossAccountId,1790 collection: &mut CollectionHandle<T>,1791 new_limit: CollectionLimits,1792 ) -> DispatchResult {1793 collection.check_is_internal()?;1794 collection.check_is_owner_or_admin(user)?;17951796 collection.limits =1797 Self::clamp_limits(collection.mode.clone(), &collection.limits, new_limit)?;17981799 Self::deposit_event(Event::<T>::CollectionLimitSet(collection.id));1800 <PalletEvm<T>>::deposit_log(1801 erc::CollectionHelpersEvents::CollectionChanged {1802 collection_id: eth::collection_id_to_address(collection.id),1803 }1804 .to_log(T::ContractAddress::get()),1805 );18061807 collection.save()1808 }18091810 /// Merge set fields from `new_limit` to `old_limit`.1811 fn clamp_limits(1812 mode: CollectionMode,1813 old_limit: &CollectionLimits,1814 mut new_limit: CollectionLimits,1815 ) -> Result<CollectionLimits, DispatchError> {1816 let limits = old_limit;1817 limit_default!(old_limit, new_limit,1818 account_token_ownership_limit => ensure!(1819 new_limit <= MAX_TOKEN_OWNERSHIP,1820 <Error<T>>::CollectionLimitBoundsExceeded,1821 ),1822 sponsored_data_size => ensure!(1823 new_limit <= CUSTOM_DATA_LIMIT,1824 <Error<T>>::CollectionLimitBoundsExceeded,1825 ),18261827 sponsored_data_rate_limit => {},1828 token_limit => ensure!(1829 old_limit >= new_limit && new_limit > 0,1830 <Error<T>>::CollectionTokenLimitExceeded1831 ),18321833 sponsor_transfer_timeout(match mode {1834 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1835 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1836 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1837 }) => ensure!(1838 new_limit <= MAX_SPONSOR_TIMEOUT,1839 <Error<T>>::CollectionLimitBoundsExceeded,1840 ),1841 sponsor_approve_timeout => {},1842 owner_can_transfer => ensure!(1843 !limits.owner_can_transfer_instaled() ||1844 old_limit || !new_limit,1845 <Error<T>>::OwnerPermissionsCantBeReverted,1846 ),1847 owner_can_destroy => ensure!(1848 old_limit || !new_limit,1849 <Error<T>>::OwnerPermissionsCantBeReverted,1850 ),1851 transfers_enabled => {},1852 );1853 Ok(new_limit)1854 }18551856 /// Update collection permissions.1857 pub fn update_permissions(1858 user: &T::CrossAccountId,1859 collection: &mut CollectionHandle<T>,1860 new_permission: CollectionPermissions,1861 ) -> DispatchResult {1862 collection.check_is_internal()?;1863 collection.check_is_owner_or_admin(user)?;1864 collection.permissions = Self::clamp_permissions(1865 collection.mode.clone(),1866 &collection.permissions,1867 new_permission,1868 )?;18691870 Self::deposit_event(Event::<T>::CollectionPermissionSet(collection.id));1871 <PalletEvm<T>>::deposit_log(1872 erc::CollectionHelpersEvents::CollectionChanged {1873 collection_id: eth::collection_id_to_address(collection.id),1874 }1875 .to_log(T::ContractAddress::get()),1876 );18771878 collection.save()1879 }18801881 /// Merge set fields from `new_permission` to `old_permission`.1882 fn clamp_permissions(1883 _mode: CollectionMode,1884 old_permission: &CollectionPermissions,1885 mut new_permission: CollectionPermissions,1886 ) -> Result<CollectionPermissions, DispatchError> {1887 limit_default_clone!(old_permission, new_permission,1888 access => {},1889 mint_mode => {},1890 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1891 );1892 Ok(new_permission)1893 }18941895 /// Repair possibly broken properties of a collection.1896 pub fn repair_collection(collection_id: CollectionId) -> DispatchResult {1897 CollectionProperties::<T>::mutate(collection_id, |properties| {1898 properties.recompute_consumed_space();1899 });19001901 Ok(())1902 }1903}19041905/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1906#[macro_export]1907macro_rules! unsupported {1908 ($runtime:path) => {1909 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1910 };1911}19121913/// Return weights for various worst-case operations.1914pub trait CommonWeightInfo<CrossAccountId> {1915 /// Weight of item creation.1916 fn create_item(data: &CreateItemData) -> Weight {1917 Self::create_multiple_items(from_ref(data))1918 }19191920 /// Weight of items creation.1921 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;19221923 /// Weight of items creation.1924 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;19251926 /// The weight of the burning item.1927 fn burn_item() -> Weight;19281929 /// Property setting weight.1930 ///1931 /// * `amount`- The number of properties to set.1932 fn set_collection_properties(amount: u32) -> Weight;19331934 /// Collection property deletion weight.1935 ///1936 /// * `amount`- The number of properties to set.1937 fn delete_collection_properties(amount: u32) -> Weight;19381939 /// Token property setting weight.1940 ///1941 /// * `amount`- The number of properties to set.1942 fn set_token_properties(amount: u32) -> Weight;19431944 /// Token property deletion weight.1945 ///1946 /// * `amount`- The number of properties to delete.1947 fn delete_token_properties(amount: u32) -> Weight;19481949 /// Token property permissions set weight.1950 ///1951 /// * `amount`- The number of property permissions to set.1952 fn set_token_property_permissions(amount: u32) -> Weight;19531954 /// Transfer price of the token or its parts.1955 fn transfer() -> Weight;19561957 /// The price of setting the permission of the operation from another user.1958 fn approve() -> Weight;19591960 /// The price of setting the permission of the operation from another user for eth mirror.1961 fn approve_from() -> Weight;19621963 /// Transfer price from another user.1964 fn transfer_from() -> Weight;19651966 /// The price of burning a token from another user.1967 fn burn_from() -> Weight;19681969 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1970 /// whole users's balance.1971 ///1972 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1973 fn burn_recursively_self_raw() -> Weight;19741975 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1976 ///1977 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1978 fn burn_recursively_breadth_raw(amount: u32) -> Weight;19791980 /// The price of recursive burning a token.1981 ///1982 /// `max_selfs` - The maximum burning weight of the token itself.1983 /// `max_breadth` - The maximum number of nested tokens to burn.1984 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1985 Self::burn_recursively_self_raw()1986 .saturating_mul(max_selfs.max(1) as u64)1987 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1988 }19891990 /// The price of retrieving token owner1991 fn token_owner() -> Weight;19921993 /// The price of setting approval for all1994 fn set_allowance_for_all() -> Weight;19951996 /// The price of repairing an item.1997 fn force_repair_item() -> Weight;1998}19992000/// Weight info extension trait for refungible pallet.2001pub trait RefungibleExtensionsWeightInfo {2002 /// Weight of token repartition.2003 fn repartition() -> Weight;2004}20052006/// Common collection operations.2007///2008/// It wraps methods in Fungible, Nonfungible and Refungible pallets2009/// and adds weight info.2010pub trait CommonCollectionOperations<T: Config> {2011 /// Create token.2012 ///2013 /// * `sender` - The user who mint the token and pays for the transaction.2014 /// * `to` - The user who will own the token.2015 /// * `data` - Token data.2016 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2017 fn create_item(2018 &self,2019 sender: T::CrossAccountId,2020 to: T::CrossAccountId,2021 data: CreateItemData,2022 nesting_budget: &dyn Budget,2023 ) -> DispatchResultWithPostInfo;20242025 /// Create multiple tokens.2026 ///2027 /// * `sender` - The user who mint the token and pays for the transaction.2028 /// * `to` - The user who will own the token.2029 /// * `data` - Token data.2030 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2031 fn create_multiple_items(2032 &self,2033 sender: T::CrossAccountId,2034 to: T::CrossAccountId,2035 data: Vec<CreateItemData>,2036 nesting_budget: &dyn Budget,2037 ) -> DispatchResultWithPostInfo;20382039 /// Create multiple tokens.2040 ///2041 /// * `sender` - The user who mint the token and pays for the transaction.2042 /// * `to` - The user who will own the token.2043 /// * `data` - Token data.2044 /// * `nesting_budget` - A budget that can be spent on nesting tokens.2045 fn create_multiple_items_ex(2046 &self,2047 sender: T::CrossAccountId,2048 data: CreateItemExData<T::CrossAccountId>,2049 nesting_budget: &dyn Budget,2050 ) -> DispatchResultWithPostInfo;20512052 /// Burn token.2053 ///2054 /// * `sender` - The user who owns the token.2055 /// * `token` - Token id that will burned.2056 /// * `amount` - The number of parts of the token that will be burned.2057 fn burn_item(2058 &self,2059 sender: T::CrossAccountId,2060 token: TokenId,2061 amount: u128,2062 ) -> DispatchResultWithPostInfo;20632064 /// Burn token and all nested tokens recursievly.2065 ///2066 /// * `sender` - The user who owns the token.2067 /// * `token` - Token id that will burned.2068 /// * `self_budget` - The budget that can be spent on burning tokens.2069 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.2070 fn burn_item_recursively(2071 &self,2072 sender: T::CrossAccountId,2073 token: TokenId,2074 self_budget: &dyn Budget,2075 breadth_budget: &dyn Budget,2076 ) -> DispatchResultWithPostInfo;20772078 /// Set collection properties.2079 ///2080 /// * `sender` - Must be either the owner of the collection or its admin.2081 /// * `properties` - Properties to be set.2082 fn set_collection_properties(2083 &self,2084 sender: T::CrossAccountId,2085 properties: Vec<Property>,2086 ) -> DispatchResultWithPostInfo;20872088 /// Delete collection properties.2089 ///2090 /// * `sender` - Must be either the owner of the collection or its admin.2091 /// * `properties` - The properties to be removed.2092 fn delete_collection_properties(2093 &self,2094 sender: &T::CrossAccountId,2095 property_keys: Vec<PropertyKey>,2096 ) -> DispatchResultWithPostInfo;20972098 /// Set token properties.2099 ///2100 /// The appropriate [`PropertyPermission`] for the token property2101 /// must be set with [`Self::set_token_property_permissions`].2102 ///2103 /// * `sender` - Must be either the owner of the token or its admin.2104 /// * `token_id` - The token for which the properties are being set.2105 /// * `properties` - Properties to be set.2106 /// * `budget` - Budget for setting properties.2107 fn set_token_properties(2108 &self,2109 sender: T::CrossAccountId,2110 token_id: TokenId,2111 properties: Vec<Property>,2112 budget: &dyn Budget,2113 ) -> DispatchResultWithPostInfo;21142115 /// Remove token properties.2116 ///2117 /// The appropriate [`PropertyPermission`] for the token property2118 /// must be set with [`Self::set_token_property_permissions`].2119 ///2120 /// * `sender` - Must be either the owner of the token or its admin.2121 /// * `token_id` - The token for which the properties are being remove.2122 /// * `property_keys` - Keys to remove corresponding properties.2123 /// * `budget` - Budget for removing properties.2124 fn delete_token_properties(2125 &self,2126 sender: T::CrossAccountId,2127 token_id: TokenId,2128 property_keys: Vec<PropertyKey>,2129 budget: &dyn Budget,2130 ) -> DispatchResultWithPostInfo;21312132 /// Set token property permissions.2133 ///2134 /// * `sender` - Must be either the owner of the token or its admin.2135 /// * `token_id` - The token for which the properties are being set.2136 /// * `property_permissions` - Property permissions to be set.2137 /// * `budget` - Budget for setting properties.2138 fn set_token_property_permissions(2139 &self,2140 sender: &T::CrossAccountId,2141 property_permissions: Vec<PropertyKeyPermission>,2142 ) -> DispatchResultWithPostInfo;21432144 /// Transfer amount of token pieces.2145 ///2146 /// * `sender` - Donor user.2147 /// * `to` - Recepient user.2148 /// * `token` - The token of which parts are being sent.2149 /// * `amount` - The number of parts of the token that will be transferred.2150 /// * `budget` - The maximum budget that can be spent on the transfer.2151 fn transfer(2152 &self,2153 sender: T::CrossAccountId,2154 to: T::CrossAccountId,2155 token: TokenId,2156 amount: u128,2157 budget: &dyn Budget,2158 ) -> DispatchResultWithPostInfo;21592160 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].2161 ///2162 /// * `sender` - The user who grants access to the token.2163 /// * `spender` - The user to whom the rights are granted.2164 /// * `token` - The token to which access is granted.2165 /// * `amount` - The amount of pieces that another user can dispose of.2166 fn approve(2167 &self,2168 sender: T::CrossAccountId,2169 spender: T::CrossAccountId,2170 token: TokenId,2171 amount: u128,2172 ) -> DispatchResultWithPostInfo;21732174 /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].2175 ///2176 /// * `sender` - The user who grants access to the token.2177 /// * `from` - Spender's eth mirror.2178 /// * `to` - The user to whom the rights are granted.2179 /// * `token` - The token to which access is granted.2180 /// * `amount` - The amount of pieces that another user can dispose of.2181 fn approve_from(2182 &self,2183 sender: T::CrossAccountId,2184 from: T::CrossAccountId,2185 to: T::CrossAccountId,2186 token: TokenId,2187 amount: u128,2188 ) -> DispatchResultWithPostInfo;21892190 /// Send parts of a token owned by another user.2191 ///2192 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2193 ///2194 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2195 /// * `from` - The user who owns the token.2196 /// * `to` - Recepient user.2197 /// * `token` - The token of which parts are being sent.2198 /// * `amount` - The number of parts of the token that will be transferred.2199 /// * `budget` - The maximum budget that can be spent on the transfer.2200 fn transfer_from(2201 &self,2202 sender: T::CrossAccountId,2203 from: T::CrossAccountId,2204 to: T::CrossAccountId,2205 token: TokenId,2206 amount: u128,2207 budget: &dyn Budget,2208 ) -> DispatchResultWithPostInfo;22092210 /// Burn parts of a token owned by another user.2211 ///2212 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].2213 ///2214 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).2215 /// * `from` - The user who owns the token.2216 /// * `token` - The token of which parts are being sent.2217 /// * `amount` - The number of parts of the token that will be transferred.2218 /// * `budget` - The maximum budget that can be spent on the burn.2219 fn burn_from(2220 &self,2221 sender: T::CrossAccountId,2222 from: T::CrossAccountId,2223 token: TokenId,2224 amount: u128,2225 budget: &dyn Budget,2226 ) -> DispatchResultWithPostInfo;22272228 /// Check permission to nest token.2229 ///2230 /// * `sender` - The user who initiated the check.2231 /// * `from` - The token that is checked for embedding.2232 /// * `under` - Token under which to check.2233 /// * `budget` - The maximum budget that can be spent on the check.2234 fn check_nesting(2235 &self,2236 sender: T::CrossAccountId,2237 from: (CollectionId, TokenId),2238 under: TokenId,2239 budget: &dyn Budget,2240 ) -> DispatchResult;22412242 /// Nest one token into another.2243 ///2244 /// * `under` - Token holder.2245 /// * `to_nest` - Nested token.2246 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22472248 /// Unnest token.2249 ///2250 /// * `under` - Token holder.2251 /// * `to_nest` - Token to unnest.2252 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));22532254 /// Get all user tokens.2255 ///2256 /// * `account` - Account for which you need to get tokens.2257 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;22582259 /// Get all the tokens in the collection.2260 fn collection_tokens(&self) -> Vec<TokenId>;22612262 /// Check if the token exists.2263 ///2264 /// * `token` - Id token to check.2265 fn token_exists(&self, token: TokenId) -> bool;22662267 /// Get the id of the last minted token.2268 fn last_token_id(&self) -> TokenId;22692270 /// Get the owner of the token.2271 ///2272 /// * `token` - The token for which you need to find out the owner.2273 fn token_owner(&self, token: TokenId) -> Result<T::CrossAccountId, TokenOwnerError>;22742275 /// Returns 10 tokens owners in no particular order.2276 ///2277 /// * `token` - The token for which you need to find out the owners.2278 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;22792280 /// Get the value of the token property by key.2281 ///2282 /// * `token` - Token with the property to get.2283 /// * `key` - Property name.2284 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;22852286 /// Get a set of token properties by key vector.2287 ///2288 /// * `token` - Token with the property to get.2289 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),2290 /// then all properties are returned.2291 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;22922293 /// Amount of unique collection tokens2294 fn total_supply(&self) -> u32;22952296 /// Amount of different tokens account has.2297 ///2298 /// * `account` - The account for which need to get the balance.2299 fn account_balance(&self, account: T::CrossAccountId) -> u32;23002301 /// Amount of specific token account have.2302 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;23032304 /// Amount of token pieces2305 fn total_pieces(&self, token: TokenId) -> Option<u128>;23062307 /// Get the number of parts of the token that a trusted user can manage.2308 ///2309 /// * `sender` - Trusted user.2310 /// * `spender` - Owner of the token.2311 /// * `token` - The token for which to get the value.2312 fn allowance(2313 &self,2314 sender: T::CrossAccountId,2315 spender: T::CrossAccountId,2316 token: TokenId,2317 ) -> u128;23182319 /// Get extension for RFT collection.2320 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;23212322 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.2323 /// * `owner` - Token owner2324 /// * `operator` - Operator2325 /// * `approve` - Should operator status be granted or revoked?2326 fn set_allowance_for_all(2327 &self,2328 owner: T::CrossAccountId,2329 operator: T::CrossAccountId,2330 approve: bool,2331 ) -> DispatchResultWithPostInfo;23322333 /// Tells whether the given `owner` approves the `operator`.2334 fn allowance_for_all(&self, owner: T::CrossAccountId, operator: T::CrossAccountId) -> bool;23352336 /// Repairs a possibly broken item.2337 fn repair_item(&self, token: TokenId) -> DispatchResultWithPostInfo;2338}23392340/// Extension for RFT collection.2341pub trait RefungibleExtensions<T>2342where2343 T: Config,2344{2345 /// Change the number of parts of the token.2346 ///2347 /// When the value changes down, this function is equivalent to burning parts of the token.2348 ///2349 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.2350 /// * `token` - The token for which you want to change the number of parts.2351 /// * `amount` - The new value of the parts of the token.2352 fn repartition(2353 &self,2354 sender: &T::CrossAccountId,2355 token: TokenId,2356 amount: u128,2357 ) -> DispatchResultWithPostInfo;2358}23592360/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].2361///2362/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.2363pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {2364 let post_info = PostDispatchInfo {2365 actual_weight: Some(weight),2366 pays_fee: Pays::Yes,2367 };2368 match res {2369 Ok(()) => Ok(post_info),2370 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),2371 }2372}23732374impl<T: Config> From<PropertiesError> for Error<T> {2375 fn from(error: PropertiesError) -> Self {2376 match error {2377 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,2378 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,2379 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,2380 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,2381 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,2382 }2383 }2384}pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.10] - 2023-02-01
+
+### Added
+
+- The functions `allowanceCross` to `ERC20UniqueExtensions` interface.
+
## [0.1.9] - 2022-12-01
### Added
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-fungible"
-version = "0.1.9"
+version = "0.1.10"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -19,6 +19,7 @@
extern crate alloc;
use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
use core::convert::TryInto;
+use evm_coder::AbiCoder;
use evm_coder::{
abi::AbiType, ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*,
weight,
@@ -27,6 +28,7 @@
use pallet_common::{
CollectionHandle,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
+ eth::CrossAddress,
};
use sp_std::vec::Vec;
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -57,6 +59,12 @@
},
}
+#[derive(AbiCoder, Debug)]
+pub struct AmountForAddress {
+ to: Address,
+ amount: U256,
+}
+
#[solidity_interface(name = ERC20, events(ERC20Events), expect_selector = 0x942e8b22)]
impl<T: Config> FungibleHandle<T> {
fn name(&self) -> Result<String> {
@@ -161,6 +169,17 @@
where
T::AccountId: From<[u8; 32]>,
{
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {
+ let owner = owner.into_sub_cross_account::<T>()?;
+ let spender = spender.into_sub_cross_account::<T>()?;
+
+ Ok(<Allowance<T>>::get((self.id, owner, spender)).into())
+ }
+
/// @notice A description for the collection.
fn description(&self) -> Result<String> {
Ok(decode_utf16(self.description.iter().copied())
@@ -169,12 +188,7 @@
}
#[weight(<SelfWeightOf<T>>::create_item())]
- fn mint_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn mint_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -190,7 +204,7 @@
fn approve_cross(
&mut self,
caller: Caller,
- spender: pallet_common::eth::CrossAddress,
+ spender: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -231,7 +245,7 @@
fn burn_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -249,14 +263,14 @@
/// Mint tokens for multiple accounts.
/// @param amounts array of pairs of account address and amount
#[weight(<SelfWeightOf<T>>::create_multiple_items_ex(amounts.len() as u32))]
- fn mint_bulk(&mut self, caller: Caller, amounts: Vec<(Address, U256)>) -> Result<bool> {
+ fn mint_bulk(&mut self, caller: Caller, amounts: Vec<AmountForAddress>) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let budget = self
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
let amounts = amounts
.into_iter()
- .map(|(to, amount)| {
+ .map(|AmountForAddress { to, amount }| {
Ok((
T::CrossAccountId::from_eth(to),
amount.try_into().map_err(|_| "amount overflow")?,
@@ -270,12 +284,7 @@
}
#[weight(<SelfWeightOf<T>>::transfer())]
- fn transfer_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -291,8 +300,8 @@
fn transfer_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
- to: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
+ to: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -165,8 +165,8 @@
pub type Allowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128, T::CrossAccountId>,
- Key<Blake2_128Concat, T::CrossAccountId>,
+ Key<Blake2_128, T::CrossAccountId>, // Owner
+ Key<Blake2_128Concat, T::CrossAccountId>, // Spender
),
Value = u128,
QueryKind = ValueQuery,
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -511,8 +511,22 @@
bytes value;
}
-/// @dev the ERC-165 identifier for this interface is 0x65789571
+/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
contract ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ /// @dev EVM selector for this function is: 0xe0af4bd7,
+ /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
+ function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ spender;
+ dummy;
+ return 0;
+ }
+
/// @notice A description for the collection.
/// @dev EVM selector for this function is: 0x7284e416,
/// or in textual repr: description()
@@ -576,7 +590,7 @@
/// @param amounts array of pairs of account address and amount
/// @dev EVM selector for this function is: 0x1acf2d55,
/// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(Tuple9[] memory amounts) public returns (bool) {
+ function mintBulk(AmountForAddress[] memory amounts) public returns (bool) {
require(false, stub_error);
amounts;
dummy = 0;
@@ -618,10 +632,9 @@
}
}
-/// @dev anonymous struct
-struct Tuple9 {
- address field_0;
- uint256 field_1;
+struct AmountForAddress {
+ address to;
+ uint256 amount;
}
/// @dev the ERC-165 identifier for this interface is 0x40c10f19
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -38,7 +38,7 @@
use pallet_common::{
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
- eth,
+ eth::{self, TokenUri},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -948,7 +948,7 @@
&mut self,
caller: Caller,
to: Address,
- tokens: Vec<(U256, String)>,
+ tokens: Vec<TokenUri>,
) -> Result<bool> {
let key = key::url();
let caller = T::CrossAccountId::from_eth(caller);
@@ -961,7 +961,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
let mut data = Vec::with_capacity(tokens.len());
- for (id, token_uri) in tokens {
+ for TokenUri { id, uri } in tokens {
let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
if id != expected_index {
return Err("item id should be next".into());
@@ -972,7 +972,7 @@
properties
.try_push(Property {
key: key.clone(),
- value: token_uri
+ value: uri
.into_bytes()
.try_into()
.map_err(|_| "token uri is too long")?,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -101,18 +101,18 @@
};
use up_data_structs::{
AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,
- CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission,
- PropertyKey, PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,
- TokenChild, AuxPropertyValue, PropertiesPermissionMap,
+ CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,
+ PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,
+ AuxPropertyValue, PropertiesPermissionMap,
};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_common::{
Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
- eth::collection_id_to_address, erc::CollectionHelpersEvents,
+ eth::collection_id_to_address,
};
use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_core::{H160, Get};
+use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use core::ops::Deref;
@@ -578,10 +578,6 @@
}
/// A batch operation to add, edit or remove properties for a token.
- /// It sets or removes a token's properties according to
- /// `properties_updates` contents:
- /// * sets a property under the <key> with the value provided `(<key>, Some(<value>))`
- /// * removes a property under the <key> if the value is `None` `(<key>, None)`.
///
/// - `nesting_budget`: Limit for searching parents in-depth to check ownership.
/// - `is_token_create`: Indicates that method is called during token initialization.
@@ -603,97 +599,30 @@
is_token_create: bool,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let mut collection_admin_status = None;
- let mut token_owner_result = None;
-
- let mut is_collection_admin =
- || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));
+ let is_token_owner = || {
+ let is_owned = <PalletStructure<T>>::check_indirectly_owned(
+ sender.clone(),
+ collection.id,
+ token_id,
+ None,
+ nesting_budget,
+ )?;
- let mut is_token_owner = || {
- *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {
- let is_owned = <PalletStructure<T>>::check_indirectly_owned(
- sender.clone(),
- collection.id,
- token_id,
- None,
- nesting_budget,
- )?;
-
- Ok(is_owned)
- })
+ Ok(is_owned)
};
-
- let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- let permissions = <PalletCommon<T>>::property_permissions(collection.id);
-
- for (key, value) in properties_updates {
- let permission = permissions
- .get(&key)
- .cloned()
- .unwrap_or_else(PropertyPermission::none);
-
- let is_property_exists = stored_properties.get(&key).is_some();
-
- match permission {
- PropertyPermission { mutable: false, .. } if is_property_exists => {
- return Err(<CommonError<T>>::NoPermission.into());
- }
-
- PropertyPermission {
- collection_admin,
- token_owner,
- ..
- } => {
- //TODO: investigate threats during public minting.
- if is_token_create && (collection_admin || token_owner) && value.is_some() {
- // Pass
- } else if collection_admin && is_collection_admin() {
- // Pass
- } else if token_owner && is_token_owner()? {
- // Pass
- } else {
- fail!(<CommonError<T>>::NoPermission);
- }
- }
- }
- match value {
- Some(value) => {
- stored_properties
- .try_set(key.clone(), value)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
- collection.id,
- token_id,
- key,
- ));
- }
- None => {
- stored_properties
- .remove(&key)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
- collection.id,
- token_id,
- key,
- ));
- }
- }
-
- <PalletEvm<T>>::deposit_log(
- CollectionHelpersEvents::TokenChanged {
- collection_id: collection_id_to_address(collection.id),
- token_id: token_id.into(),
- }
- .to_log(T::ContractAddress::get()),
- );
- }
-
- <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
+ let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- Ok(())
+ <PalletCommon<T>>::modify_token_properties(
+ collection,
+ sender,
+ token_id,
+ properties_updates,
+ is_token_create,
+ stored_properties,
+ is_token_owner,
+ |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ )
}
/// Batch operation to add or edit properties for the token
@@ -1418,31 +1347,19 @@
operator: &T::CrossAccountId,
approve: bool,
) -> DispatchResult {
- if collection.permissions.access() == AccessMode::AllowList {
- collection.check_allowlist(owner)?;
- collection.check_allowlist(operator)?;
- }
-
- <PalletCommon<T>>::ensure_correct_receiver(operator)?;
-
- // =========
-
- <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);
- <PalletEvm<T>>::deposit_log(
+ <PalletCommon<T>>::set_allowance_for_all(
+ collection,
+ owner,
+ operator,
+ approve,
+ || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),
ERC721Events::ApprovalForAll {
owner: *owner.as_eth(),
operator: *operator.as_eth(),
approved: approve,
}
.to_log(collection_id_to_address(collection.id)),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
- collection.id,
- owner.clone(),
- operator.clone(),
- approve,
- ));
- Ok(())
+ )
}
/// Tells whether the given `owner` approves the `operator`.
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -949,7 +949,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple15[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -981,10 +981,12 @@
}
}
-/// @dev anonymous struct
-struct Tuple15 {
- uint256 field_0;
- string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+ /// Id of new token.
+ uint256 id;
+ /// Uri of new token.
+ string uri;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
pallets/refungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/refungible/CHANGELOG.md
+++ b/pallets/refungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.2.13] - 2023-02-01
+
+### Added
+
+- The functions `allowanceCross` to `ERC20UniqueExtensions` interface.
+
## [0.2.12] - 2023-01-20
### Fixed
pallets/refungible/Cargo.tomldiffbeforeafterboth--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-refungible"
-version = "0.2.12"
+version = "0.2.13"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -34,7 +34,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
Error as CommonError,
erc::{CommonEvmHandler, CollectionCall, static_property::key},
- eth,
+ eth::{self, TokenUri},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm};
@@ -999,7 +999,7 @@
&mut self,
caller: Caller,
to: Address,
- tokens: Vec<(U256, String)>,
+ tokens: Vec<TokenUri>,
) -> Result<bool> {
let key = key::url();
let caller = T::CrossAccountId::from_eth(caller);
@@ -1017,7 +1017,7 @@
.collect::<BTreeMap<_, _>>()
.try_into()
.unwrap();
- for (id, token_uri) in tokens {
+ for TokenUri { id, uri } in tokens {
let id: u32 = id.try_into().map_err(|_| "token id overflow")?;
if id != expected_index {
return Err("item id should be next".into());
@@ -1028,7 +1028,7 @@
properties
.try_push(Property {
key: key.clone(),
- value: token_uri
+ value: uri
.into_bytes()
.try_into()
.map_err(|_| "token uri is too long")?,
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -31,7 +31,7 @@
use pallet_common::{
CommonWeightInfo,
erc::{CommonEvmHandler, PrecompileResult},
- eth::collection_id_to_address,
+ eth::{collection_id_to_address, CrossAddress},
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
@@ -203,6 +203,17 @@
where
T::AccountId: From<[u8; 32]>,
{
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ fn allowance_cross(&self, owner: CrossAddress, spender: CrossAddress) -> Result<U256> {
+ let owner = owner.into_sub_cross_account::<T>()?;
+ let spender = spender.into_sub_cross_account::<T>()?;
+
+ Ok(<Allowance<T>>::get((self.id, self.1, owner, spender)).into())
+ }
+
/// @dev Function that burns an amount of the token of a given account,
/// deducting from the sender's allowance for said account.
/// @param from The account whose tokens will be burnt.
@@ -230,7 +241,7 @@
fn burn_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -256,7 +267,7 @@
fn approve_cross(
&mut self,
caller: Caller,
- spender: pallet_common::eth::CrossAddress,
+ spender: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
@@ -283,12 +294,7 @@
/// @param to The crossaccount to transfer to.
/// @param amount The amount to be transferred.
#[weight(<CommonWeights<T>>::transfer())]
- fn transfer_cross(
- &mut self,
- caller: Caller,
- to: pallet_common::eth::CrossAddress,
- amount: U256,
- ) -> Result<bool> {
+ fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
let amount = amount.try_into().map_err(|_| "amount overflow")?;
@@ -309,8 +315,8 @@
fn transfer_from_cross(
&mut self,
caller: Caller,
- from: pallet_common::eth::CrossAddress,
- to: pallet_common::eth::CrossAddress,
+ from: CrossAddress,
+ to: CrossAddress,
amount: U256,
) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -92,22 +92,22 @@
use core::ops::Deref;
use evm_coder::ToLog;
-use frame_support::{ensure, fail, storage::with_transaction, transactional};
+use frame_support::{ensure, storage::with_transaction, transactional};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
CommonCollectionOperations, Error as CommonError, eth::collection_id_to_address,
- Event as CommonEvent, Pallet as PalletCommon, erc::CollectionHelpersEvents,
+ Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
-use sp_core::{Get, H160};
+use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
AccessMode, budget::Budget, CollectionId, CollectionFlags, CreateCollectionData,
mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, Property, PropertyKey,
- PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue, TokenId,
- TrySetProperty, PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
+ PropertyKeyPermission, PropertyScope, PropertyValue, TokenId, TrySetProperty,
+ PropertiesPermissionMap, CreateRefungibleExMultipleOwners, TokenOwnerError,
};
pub use pallet::*;
@@ -240,13 +240,13 @@
QueryKind = ValueQuery,
>;
- /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.
+ /// Spender set by a wallet owner that could perform certain transactions on all tokens in the wallet.
#[pallet::storage]
pub type CollectionAllowance<T: Config> = StorageNMap<
Key = (
Key<Twox64Concat, CollectionId>,
- Key<Blake2_128Concat, T::CrossAccountId>,
- Key<Blake2_128Concat, T::CrossAccountId>,
+ Key<Blake2_128Concat, T::CrossAccountId>, // Owner
+ Key<Blake2_128Concat, T::CrossAccountId>, // Spender
),
Value = bool,
QueryKind = ValueQuery,
@@ -541,7 +541,6 @@
is_token_create: bool,
nesting_budget: &dyn Budget,
) -> DispatchResult {
- let is_collection_admin = || collection.is_owner_or_admin(sender);
let is_token_owner = || -> Result<bool, DispatchError> {
let balance = collection.balance(sender.clone(), token_id);
let total_pieces: u128 =
@@ -560,77 +559,19 @@
Ok(is_bundle_owner)
};
-
- let mut stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- let permissions = <PalletCommon<T>>::property_permissions(collection.id);
-
- for (key, value) in properties_updates {
- let permission = permissions
- .get(&key)
- .cloned()
- .unwrap_or_else(PropertyPermission::none);
-
- let is_property_exists = stored_properties.get(&key).is_some();
-
- match permission {
- PropertyPermission { mutable: false, .. } if is_property_exists => {
- return Err(<CommonError<T>>::NoPermission.into());
- }
- PropertyPermission {
- collection_admin,
- token_owner,
- ..
- } => {
- //TODO: investigate threats during public minting.
- let is_token_create =
- is_token_create && (collection_admin || token_owner) && value.is_some();
- if !(is_token_create
- || (collection_admin && is_collection_admin())
- || (token_owner && is_token_owner()?))
- {
- fail!(<CommonError<T>>::NoPermission);
- }
- }
- }
-
- match value {
- Some(value) => {
- stored_properties
- .try_set(key.clone(), value)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
- collection.id,
- token_id,
- key,
- ));
- }
- None => {
- stored_properties
- .remove(&key)
- .map_err(<CommonError<T>>::from)?;
-
- <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
- collection.id,
- token_id,
- key,
- ));
- }
- }
-
- <PalletEvm<T>>::deposit_log(
- CollectionHelpersEvents::TokenChanged {
- collection_id: collection_id_to_address(collection.id),
- token_id: token_id.into(),
- }
- .to_log(T::ContractAddress::get()),
- );
- }
+ let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));
- <TokenProperties<T>>::set((collection.id, token_id), stored_properties);
-
- Ok(())
+ <PalletCommon<T>>::modify_token_properties(
+ collection,
+ sender,
+ token_id,
+ properties_updates,
+ is_token_create,
+ stored_properties,
+ is_token_owner,
+ |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),
+ )
}
pub fn set_token_properties(
@@ -1462,43 +1403,31 @@
pub fn set_allowance_for_all(
collection: &RefungibleHandle<T>,
owner: &T::CrossAccountId,
- operator: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
approve: bool,
) -> DispatchResult {
- if collection.permissions.access() == AccessMode::AllowList {
- collection.check_allowlist(owner)?;
- collection.check_allowlist(operator)?;
- }
-
- <PalletCommon<T>>::ensure_correct_receiver(operator)?;
-
- // =========
-
- <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve);
- <PalletEvm<T>>::deposit_log(
+ <PalletCommon<T>>::set_allowance_for_all(
+ collection,
+ owner,
+ spender,
+ approve,
+ || <CollectionAllowance<T>>::insert((collection.id, owner, spender), approve),
ERC721Events::ApprovalForAll {
owner: *owner.as_eth(),
- operator: *operator.as_eth(),
+ operator: *spender.as_eth(),
approved: approve,
}
.to_log(collection_id_to_address(collection.id)),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ApprovedForAll(
- collection.id,
- owner.clone(),
- operator.clone(),
- approve,
- ));
- Ok(())
+ )
}
/// Tells whether the given `owner` approves the `operator`.
pub fn allowance_for_all(
collection: &RefungibleHandle<T>,
owner: &T::CrossAccountId,
- operator: &T::CrossAccountId,
+ spender: &T::CrossAccountId,
) -> bool {
- <CollectionAllowance<T>>::get((collection.id, owner, operator))
+ <CollectionAllowance<T>>::get((collection.id, owner, spender))
}
pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -938,7 +938,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple14[] memory tokens) public returns (bool) {
+ // function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) public returns (bool) {
// require(false, stub_error);
// to;
// tokens;
@@ -982,10 +982,12 @@
}
}
-/// @dev anonymous struct
-struct Tuple14 {
- uint256 field_0;
- string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+ /// Id of new token.
+ uint256 id;
+ /// Uri of new token.
+ string uri;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
pallets/refungible/src/stubs/UniqueRefungibleToken.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -36,8 +36,22 @@
}
}
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
contract ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ /// @dev EVM selector for this function is: 0xe0af4bd7,
+ /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
+ function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ spender;
+ dummy;
+ return 0;
+ }
+
// /// @dev Function that burns an amount of the token of a given account,
// /// deducting from the sender's allowance for said account.
// /// @param from The account whose tokens will be burnt.
pallets/unique/src/eth/stubs/CollectionHelpers.rawdiffbeforeafterbothbinary blob — no preview
runtime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -341,7 +341,9 @@
ERC165Call(_, _) => None,
// Not sponsored
- BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => None,
+ AllowanceCross { .. } | BurnFrom { .. } | BurnFromCross { .. } | Repartition { .. } => {
+ None
+ }
TransferCross { .. } | TransferFromCross { .. } => {
let RefungibleTokenHandle(handle, token_id) = token;
tests/src/eth/abi/fungible.jsondiffbeforeafterboth--- a/tests/src/eth/abi/fungible.json
+++ b/tests/src/eth/abi/fungible.json
@@ -101,6 +101,32 @@
{ "internalType": "uint256", "name": "sub", "type": "uint256" }
],
"internalType": "struct CrossAddress",
+ "name": "owner",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
+ "name": "spender",
+ "type": "tuple"
+ }
+ ],
+ "name": "allowanceCross",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
"name": "user",
"type": "tuple"
}
@@ -408,10 +434,10 @@
"inputs": [
{
"components": [
- { "internalType": "address", "name": "field_0", "type": "address" },
- { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ { "internalType": "address", "name": "to", "type": "address" },
+ { "internalType": "uint256", "name": "amount", "type": "uint256" }
],
- "internalType": "struct Tuple9[]",
+ "internalType": "struct AmountForAddress[]",
"name": "amounts",
"type": "tuple[]"
}
tests/src/eth/abi/reFungibleToken.jsondiffbeforeafterboth--- a/tests/src/eth/abi/reFungibleToken.json
+++ b/tests/src/eth/abi/reFungibleToken.json
@@ -61,6 +61,32 @@
},
{
"inputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
+ "name": "owner",
+ "type": "tuple"
+ },
+ {
+ "components": [
+ { "internalType": "address", "name": "eth", "type": "address" },
+ { "internalType": "uint256", "name": "sub", "type": "uint256" }
+ ],
+ "internalType": "struct CrossAddress",
+ "name": "spender",
+ "type": "tuple"
+ }
+ ],
+ "name": "allowanceCross",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "spender", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -353,8 +353,16 @@
bytes value;
}
-/// @dev the ERC-165 identifier for this interface is 0x65789571
+/// @dev the ERC-165 identifier for this interface is 0x85d7dea6
interface ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ /// @dev EVM selector for this function is: 0xe0af4bd7,
+ /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
+ function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
/// @notice A description for the collection.
/// @dev EVM selector for this function is: 0x7284e416,
/// or in textual repr: description()
@@ -390,7 +398,7 @@
/// @param amounts array of pairs of account address and amount
/// @dev EVM selector for this function is: 0x1acf2d55,
/// or in textual repr: mintBulk((address,uint256)[])
- function mintBulk(Tuple9[] memory amounts) external returns (bool);
+ function mintBulk(AmountForAddress[] memory amounts) external returns (bool);
/// @dev EVM selector for this function is: 0x2ada85ff,
/// or in textual repr: transferCross((address,uint256),uint256)
@@ -410,10 +418,9 @@
function collectionHelperAddress() external view returns (address);
}
-/// @dev anonymous struct
-struct Tuple9 {
- address field_0;
- uint256 field_1;
+struct AmountForAddress {
+ address to;
+ uint256 amount;
}
/// @dev the ERC-165 identifier for this interface is 0x40c10f19
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -644,7 +644,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple13[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) external returns (bool);
/// @notice Function to mint a token.
/// @param to The new owner crossAccountId
@@ -660,10 +660,12 @@
function collectionHelperAddress() external view returns (address);
}
-/// @dev anonymous struct
-struct Tuple13 {
- uint256 field_0;
- string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+ /// Id of new token.
+ uint256 id;
+ /// Uri of new token.
+ string uri;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -638,7 +638,7 @@
// /// @param tokens array of pairs of token ID and token URI for minted tokens
// /// @dev EVM selector for this function is: 0x36543006,
// /// or in textual repr: mintBulkWithTokenURI(address,(uint256,string)[])
- // function mintBulkWithTokenURI(address to, Tuple12[] memory tokens) external returns (bool);
+ // function mintBulkWithTokenURI(address to, TokenUri[] memory tokens) external returns (bool);
/// @notice Function to mint a token.
/// @param to The new owner crossAccountId
@@ -661,10 +661,12 @@
function collectionHelperAddress() external view returns (address);
}
-/// @dev anonymous struct
-struct Tuple12 {
- uint256 field_0;
- string field_1;
+/// Data for creation token with uri.
+struct TokenUri {
+ /// Id of new token.
+ uint256 id;
+ /// Uri of new token.
+ string uri;
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -23,8 +23,16 @@
function parentTokenId() external view returns (uint256);
}
-/// @dev the ERC-165 identifier for this interface is 0xe17a7d2b
+/// @dev the ERC-165 identifier for this interface is 0x01d536fc
interface ERC20UniqueExtensions is Dummy, ERC165 {
+ /// @dev Function to check the amount of tokens that an owner allowed to a spender.
+ /// @param owner crossAddress The address which owns the funds.
+ /// @param spender crossAddress The address which will spend the funds.
+ /// @return A uint256 specifying the amount of tokens still available for the spender.
+ /// @dev EVM selector for this function is: 0xe0af4bd7,
+ /// or in textual repr: allowanceCross((address,uint256),(address,uint256))
+ function allowanceCross(CrossAddress memory owner, CrossAddress memory spender) external view returns (uint256);
+
// /// @dev Function that burns an amount of the token of a given account,
// /// deducting from the sender's allowance for said account.
// /// @param from The account whose tokens will be burnt.
tests/src/eth/fungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/fungible.test.ts
+++ b/tests/src/eth/fungible.test.ts
@@ -134,6 +134,12 @@
const allowance = await contract.methods.allowance(owner, spender).call();
expect(+allowance).to.equal(100);
}
+ {
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const spenderCross = helper.ethCrossAccount.fromAddress(spender);
+ const allowance = await contract.methods.allowanceCross(ownerCross, spenderCross).call();
+ expect(+allowance).to.equal(100);
+ }
});
itEth('Can perform approveCross()', async ({helper}) => {
tests/src/eth/proxy/UniqueNFTProxy.soldiffbeforeafterboth--- a/tests/src/eth/proxy/UniqueNFTProxy.sol
+++ b/tests/src/eth/proxy/UniqueNFTProxy.sol
@@ -168,7 +168,7 @@
return proxied.mintBulk(to, tokenIds);
}
- function mintBulkWithTokenURI(address to, Tuple6[] memory tokens)
+ function mintBulkWithTokenURI(address to, TokenUri[] memory tokens)
external
override
returns (bool)
tests/src/eth/reFungible.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungible.test.ts
+++ b/tests/src/eth/reFungible.test.ts
@@ -219,8 +219,16 @@
await rftToken.methods.approve(operator, 15n).send({from: owner});
await contract.methods.setApprovalForAll(operator, true).send({from: owner});
await rftToken.methods.burnFrom(owner, 10n).send({from: operator});
+ }
+ {
const allowance = await rftToken.methods.allowance(owner, operator).call();
- expect(allowance).to.be.equal('5');
+ expect(+allowance).to.be.equal(5);
+ }
+ {
+ const ownerCross = helper.ethCrossAccount.fromAddress(owner);
+ const operatorCross = helper.ethCrossAccount.fromAddress(operator);
+ const allowance = await rftToken.methods.allowanceCross(ownerCross, operatorCross).call();
+ expect(+allowance).to.equal(5);
}
});