difftreelog
feat(refungible-pallet) ERC 1633 implementation and `set_parent_nft` method
in: master
30 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -25,7 +25,8 @@
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_std::vec::Vec;
use up_data_structs::{
- Property, SponsoringRateLimit, OwnerRestrictedSet, AccessMode, CollectionPermissions,
+ AccessMode, CollectionMode, CollectionPermissions, OwnerRestrictedSet, Property,
+ SponsoringRateLimit,
};
use alloc::format;
@@ -408,6 +409,27 @@
save(self)
}
+
+ /// Check that account is the owner or admin of the collection
+ ///
+ /// @return "true" if account is the owner or admin
+ fn verify_owner_or_admin(&mut self, caller: caller) -> Result<bool> {
+ Ok(check_is_owner_or_admin(caller, self)
+ .map(|_| true)
+ .unwrap_or(false))
+ }
+
+ /// Returns collection type
+ ///
+ /// @return `Fungible` or `NFT` or `ReFungible`
+ fn unique_collection_type(&mut self) -> Result<string> {
+ let mode = match self.collection.mode {
+ CollectionMode::Fungible(_) => "Fungible",
+ CollectionMode::NFT => "NFT",
+ CollectionMode::ReFungible => "ReFungible",
+ };
+ Ok(mode.into())
+ }
}
fn check_is_owner_or_admin<T: Config>(
@@ -462,6 +484,11 @@
pub fn suffix() -> up_data_structs::PropertyKey {
property_key_from_bytes(b"suffix").expect(EXPECT_CONVERT_ERROR)
}
+
+ /// Key "parentNft".
+ pub fn parent_nft() -> up_data_structs::PropertyKey {
+ property_key_from_bytes(b"parentNft").expect(EXPECT_CONVERT_ERROR)
+ }
}
/// Values.
pallets/common/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionId,74 CreateItemData,75 MAX_TOKEN_PREFIX_LENGTH,76 COLLECTION_ADMINS_LIMIT,77 TokenId,78 TokenChild,79 CollectionStats,80 MAX_TOKEN_OWNERSHIP,81 CollectionMode,82 NFT_SPONSOR_TRANSFER_TIMEOUT,83 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 MAX_SPONSOR_TIMEOUT,86 CUSTOM_DATA_LIMIT,87 CollectionLimits,88 CreateCollectionData,89 SponsorshipState,90 CreateItemExData,91 SponsoringRateLimit,92 budget::Budget,93 PhantomType,94 Property,95 Properties,96 PropertiesPermissionMap,97 PropertyKey,98 PropertyValue,99 PropertyPermission,100 PropertiesError,101 PropertyKeyPermission,102 TokenData,103 TrySetProperty,104 PropertyScope,105 // RMRK106 RmrkCollectionInfo,107 RmrkInstanceInfo,108 RmrkResourceInfo,109 RmrkPropertyInfo,110 RmrkBaseInfo,111 RmrkPartType,112 RmrkBoundedTheme,113 RmrkNftChild,114 CollectionPermissions,115 SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139 /// Collection id140 pub id: CollectionId,141 collection: Collection<T::AccountId>,142 /// Substrate recorder for counting consumed gas143 pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 &self.recorder149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.recorder152 }153}154155impl<T: Config> CollectionHandle<T> {156 /// Same as [CollectionHandle::new] but with an explicit gas limit.157 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158 <CollectionById<T>>::get(id).map(|collection| Self {159 id,160 collection,161 recorder: SubstrateRecorder::new(gas_limit),162 })163 }164165 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder,171 })172 }173174 /// Retrives collection data from storage and creates collection handle with default parameters.175 /// If collection not found return `None`176 pub fn new(id: CollectionId) -> Option<Self> {177 Self::new_with_gas_limit(id, u64::MAX)178 }179180 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183 }184185 /// Consume gas for reading.186 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187 self.recorder188 .consume_gas(T::GasWeightMapping::weight_to_gas(189 <T as frame_system::Config>::DbWeight::get()190 .read191 .saturating_mul(reads),192 ))193 }194195 /// Consume gas for writing.196 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197 self.recorder198 .consume_gas(T::GasWeightMapping::weight_to_gas(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 ))203 }204205 /// Save collection to storage.206 pub fn save(self) -> DispatchResult {207 <CollectionById<T>>::insert(self.id, self.collection);208 Ok(())209 }210211 /// Set collection sponsor.212 ///213 /// Unique collections allows sponsoring for certain actions.214 /// This method allows you to set the sponsor of the collection.215 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218 Ok(())219 }220221 /// Confirm sponsorship222 ///223 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226 if self.collection.sponsorship.pending_sponsor() != Some(sender) {227 return Ok(false);228 }229230 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231 Ok(true)232 }233234 /// Checks that the collection was created with, and must be operated upon through **Unique API**.235 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236 pub fn check_is_internal(&self) -> DispatchResult {237 if self.external_collection {238 return Err(<Error<T>>::CollectionIsExternal)?;239 }240241 Ok(())242 }243244 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246 pub fn check_is_external(&self) -> DispatchResult {247 if !self.external_collection {248 return Err(<Error<T>>::CollectionIsInternal)?;249 }250251 Ok(())252 }253}254255impl<T: Config> Deref for CollectionHandle<T> {256 type Target = Collection<T::AccountId>;257258 fn deref(&self) -> &Self::Target {259 &self.collection260 }261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264 fn deref_mut(&mut self) -> &mut Self::Target {265 &mut self.collection266 }267}268269impl<T: Config> CollectionHandle<T> {270 /// Checks if the `user` is the owner of the collection.271 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273 Ok(())274 }275276 /// Returns **true** if the `user` is the owner or administrator of the collection.277 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279 }280281 /// Checks if the `user` is the owner or administrator of the collection.282 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284 Ok(())285 }286287 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290 }291292 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295 }296297 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299 ensure!(300 <Allowlist<T>>::get((self.id, user)),301 <Error<T>>::AddressNotInAllowlist302 );303 Ok(())304 }305}306307#[frame_support::pallet]308pub mod pallet {309 use super::*;310 use pallet_evm::account;311 use dispatch::CollectionDispatch;312 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313 use frame_system::pallet_prelude::*;314 use frame_support::traits::Currency;315 use up_data_structs::{TokenId, mapping::TokenAddressMapping};316 use scale_info::TypeInfo;317 use weights::WeightInfo;318319 #[pallet::config]320 pub trait Config:321 frame_system::Config322 + pallet_evm_coder_substrate::Config323 + pallet_evm::Config324 + TypeInfo325 + account::Config326 {327 /// Weight information for functions of this pallet.328 type WeightInfo: WeightInfo;329330 /// Events compatible with [`frame_system::Config::Event`].331 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333 /// Handler of accounts and payment.334 type Currency: Currency<Self::AccountId>;335336 /// Set price to create a collection.337 #[pallet::constant]338 type CollectionCreationPrice: Get<339 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340 >;341342 /// Dispatcher of operations on collections.343 type CollectionDispatch: CollectionDispatch<Self>;344345 /// Account which holds the chain's treasury.346 type TreasuryAccountId: Get<Self::AccountId>;347348 /// Address under which the CollectionHelper contract would be available.349 type ContractAddress: Get<H160>;350351 /// Mapper for token addresses to Ethereum addresses.352 type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354 /// Mapper for token addresses to [`CrossAccountId`].355 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356 }357358 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360 #[pallet::pallet]361 #[pallet::storage_version(STORAGE_VERSION)]362 #[pallet::generate_store(pub(super) trait Store)]363 pub struct Pallet<T>(_);364365 #[pallet::extra_constants]366 impl<T: Config> Pallet<T> {367 /// Maximum admins per collection.368 pub fn collection_admins_limit() -> u32 {369 COLLECTION_ADMINS_LIMIT370 }371 }372373 #[pallet::event]374 #[pallet::generate_deposit(pub fn deposit_event)]375 pub enum Event<T: Config> {376 /// New collection was created377 CollectionCreated(378 /// Globally unique identifier of newly created collection.379 CollectionId,380 /// [`CollectionMode`] converted into _u8_.381 u8,382 /// Collection owner.383 T::AccountId,384 ),385386 /// New collection was destroyed387 CollectionDestroyed(388 /// Globally unique identifier of collection.389 CollectionId,390 ),391392 /// New item was created.393 ItemCreated(394 /// Id of the collection where item was created.395 CollectionId,396 /// Id of an item. Unique within the collection.397 TokenId,398 /// Owner of newly created item399 T::CrossAccountId,400 /// Always 1 for NFT401 u128,402 ),403404 /// Collection item was burned.405 ItemDestroyed(406 /// Id of the collection where item was destroyed.407 CollectionId,408 /// Identifier of burned NFT.409 TokenId,410 /// Which user has destroyed its tokens.411 T::CrossAccountId,412 /// Amount of token pieces destroed. Always 1 for NFT.413 u128,414 ),415416 /// Item was transferred417 Transfer(418 /// Id of collection to which item is belong.419 CollectionId,420 /// Id of an item.421 TokenId,422 /// Original owner of item.423 T::CrossAccountId,424 /// New owner of item.425 T::CrossAccountId,426 /// Amount of token pieces transfered. Always 1 for NFT.427 u128,428 ),429430 /// Amount pieces of token owned by `sender` was approved for `spender`.431 Approved(432 /// Id of collection to which item is belong.433 CollectionId,434 /// Id of an item.435 TokenId,436 /// Original owner of item.437 T::CrossAccountId,438 /// Id for which the approval was granted.439 T::CrossAccountId,440 /// Amount of token pieces transfered. Always 1 for NFT.441 u128,442 ),443444 /// The colletion property has been added or edited.445 CollectionPropertySet(446 /// Id of collection to which property has been set.447 CollectionId,448 /// The property that was set.449 PropertyKey,450 ),451452 /// The property has been deleted.453 CollectionPropertyDeleted(454 /// Id of collection to which property has been deleted.455 CollectionId,456 /// The property that was deleted.457 PropertyKey,458 ),459460 /// The token property has been added or edited.461 TokenPropertySet(462 /// Identifier of the collection whose token has the property set.463 CollectionId,464 /// The token for which the property was set.465 TokenId,466 /// The property that was set.467 PropertyKey,468 ),469470 /// The token property has been deleted.471 TokenPropertyDeleted(472 /// Identifier of the collection whose token has the property deleted.473 CollectionId,474 /// The token for which the property was deleted.475 TokenId,476 /// The property that was deleted.477 PropertyKey,478 ),479480 /// The token property permission of a collection has been set.481 PropertyPermissionSet(482 /// ID of collection to which property permission has been set.483 CollectionId,484 /// The property permission that was set.485 PropertyKey,486 ),487 }488489 #[pallet::error]490 pub enum Error<T> {491 /// This collection does not exist.492 CollectionNotFound,493 /// Sender parameter and item owner must be equal.494 MustBeTokenOwner,495 /// No permission to perform action496 NoPermission,497 /// Destroying only empty collections is allowed498 CantDestroyNotEmptyCollection,499 /// Collection is not in mint mode.500 PublicMintingNotAllowed,501 /// Address is not in allow list.502 AddressNotInAllowlist,503504 /// Collection name can not be longer than 63 char.505 CollectionNameLimitExceeded,506 /// Collection description can not be longer than 255 char.507 CollectionDescriptionLimitExceeded,508 /// Token prefix can not be longer than 15 char.509 CollectionTokenPrefixLimitExceeded,510 /// Total collections bound exceeded.511 TotalCollectionsLimitExceeded,512 /// Exceeded max admin count513 CollectionAdminCountExceeded,514 /// Collection limit bounds per collection exceeded515 CollectionLimitBoundsExceeded,516 /// Tried to enable permissions which are only permitted to be disabled517 OwnerPermissionsCantBeReverted,518 /// Collection settings not allowing items transferring519 TransferNotAllowed,520 /// Account token limit exceeded per collection521 AccountTokenLimitExceeded,522 /// Collection token limit exceeded523 CollectionTokenLimitExceeded,524 /// Metadata flag frozen525 MetadataFlagFrozen,526527 /// Item does not exist528 TokenNotFound,529 /// Item is balance not enough530 TokenValueTooLow,531 /// Requested value is more than the approved532 ApprovedValueTooLow,533 /// Tried to approve more than owned534 CantApproveMoreThanOwned,535536 /// Can't transfer tokens to ethereum zero address537 AddressIsZero,538 /// Target collection doesn't support this operation539 UnsupportedOperation,540541 /// Insufficient funds to perform an action542 NotSufficientFounds,543544 /// User does not satisfy the nesting rule545 UserIsNotAllowedToNest,546 /// Only tokens from specific collections may nest tokens under this one547 SourceCollectionIsNotAllowedToNest,548549 /// Tried to store more data than allowed in collection field550 CollectionFieldSizeExceeded,551552 /// Tried to store more property data than allowed553 NoSpaceForProperty,554555 /// Tried to store more property keys than allowed556 PropertyLimitReached,557558 /// Property key is too long559 PropertyKeyIsTooLong,560561 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed562 InvalidCharacterInPropertyKey,563564 /// Empty property keys are forbidden565 EmptyPropertyKey,566567 /// Tried to access an external collection with an internal API568 CollectionIsExternal,569570 /// Tried to access an internal collection with an external API571 CollectionIsInternal,572 }573574 /// Storage of the count of created collections. Essentially contains the last collection ID.575 #[pallet::storage]576 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;577578 /// Storage of the count of deleted collections.579 #[pallet::storage]580 pub type DestroyedCollectionCount<T> =581 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;582583 /// Storage of collection info.584 #[pallet::storage]585 pub type CollectionById<T> = StorageMap<586 Hasher = Blake2_128Concat,587 Key = CollectionId,588 Value = Collection<<T as frame_system::Config>::AccountId>,589 QueryKind = OptionQuery,590 >;591592 /// Storage of collection properties.593 #[pallet::storage]594 #[pallet::getter(fn collection_properties)]595 pub type CollectionProperties<T> = StorageMap<596 Hasher = Blake2_128Concat,597 Key = CollectionId,598 Value = Properties,599 QueryKind = ValueQuery,600 OnEmpty = up_data_structs::CollectionProperties,601 >;602603 /// Storage of token property permissions of a collection.604 #[pallet::storage]605 #[pallet::getter(fn property_permissions)]606 pub type CollectionPropertyPermissions<T> = StorageMap<607 Hasher = Blake2_128Concat,608 Key = CollectionId,609 Value = PropertiesPermissionMap,610 QueryKind = ValueQuery,611 >;612613 /// Storage of the amount of collection admins.614 #[pallet::storage]615 pub type AdminAmount<T> = StorageMap<616 Hasher = Blake2_128Concat,617 Key = CollectionId,618 Value = u32,619 QueryKind = ValueQuery,620 >;621622 /// List of collection admins.623 #[pallet::storage]624 pub type IsAdmin<T: Config> = StorageNMap<625 Key = (626 Key<Blake2_128Concat, CollectionId>,627 Key<Blake2_128Concat, T::CrossAccountId>,628 ),629 Value = bool,630 QueryKind = ValueQuery,631 >;632633 /// Allowlisted collection users.634 #[pallet::storage]635 pub type Allowlist<T: Config> = StorageNMap<636 Key = (637 Key<Blake2_128Concat, CollectionId>,638 Key<Blake2_128Concat, T::CrossAccountId>,639 ),640 Value = bool,641 QueryKind = ValueQuery,642 >;643644 /// Not used by code, exists only to provide some types to metadata.645 #[pallet::storage]646 pub type DummyStorageValue<T: Config> = StorageValue<647 Value = (648 CollectionStats,649 CollectionId,650 TokenId,651 TokenChild,652 PhantomType<(653 TokenData<T::CrossAccountId>,654 RpcCollection<T::AccountId>,655 // RMRK656 RmrkCollectionInfo<T::AccountId>,657 RmrkInstanceInfo<T::AccountId>,658 RmrkResourceInfo,659 RmrkPropertyInfo,660 RmrkBaseInfo<T::AccountId>,661 RmrkPartType,662 RmrkBoundedTheme,663 RmrkNftChild,664 )>,665 ),666 QueryKind = OptionQuery,667 >;668669 #[pallet::hooks]670 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {671 fn on_runtime_upgrade() -> Weight {672 StorageVersion::new(1).put::<Pallet<T>>();673674 0675 }676 }677}678679impl<T: Config> Pallet<T> {680 /// Enshure that receiver address is correct.681 ///682 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.683 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {684 ensure!(685 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,686 <Error<T>>::AddressIsZero687 );688 Ok(())689 }690691 /// Get a vector of collection admins.692 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {693 <IsAdmin<T>>::iter_prefix((collection,))694 .map(|(a, _)| a)695 .collect()696 }697698 /// Get a vector of users allowed to mint tokens.699 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {700 <Allowlist<T>>::iter_prefix((collection,))701 .map(|(a, _)| a)702 .collect()703 }704705 /// Is `user` allowed to mint token in `collection`.706 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {707 <Allowlist<T>>::get((collection, user))708 }709710 /// Get statistics of collections.711 pub fn collection_stats() -> CollectionStats {712 let created = <CreatedCollectionCount<T>>::get();713 let destroyed = <DestroyedCollectionCount<T>>::get();714 CollectionStats {715 created: created.0,716 destroyed: destroyed.0,717 alive: created.0 - destroyed.0,718 }719 }720721 /// Get the effective limits for the collection.722 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {723 let collection = <CollectionById<T>>::get(collection);724 if collection.is_none() {725 return None;726 }727728 let collection = collection.unwrap();729 let limits = collection.limits;730 let effective_limits = CollectionLimits {731 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),732 sponsored_data_size: Some(limits.sponsored_data_size()),733 sponsored_data_rate_limit: Some(734 limits735 .sponsored_data_rate_limit736 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),737 ),738 token_limit: Some(limits.token_limit()),739 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(740 match collection.mode {741 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,742 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,743 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,744 },745 )),746 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),747 owner_can_transfer: Some(limits.owner_can_transfer()),748 owner_can_destroy: Some(limits.owner_can_destroy()),749 transfers_enabled: Some(limits.transfers_enabled()),750 };751752 Some(effective_limits)753 }754755 /// Returns information about the `collection` adapted for rpc.756 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {757 let Collection {758 name,759 description,760 owner,761 mode,762 token_prefix,763 sponsorship,764 limits,765 permissions,766 external_collection,767 } = <CollectionById<T>>::get(collection)?;768769 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)770 .into_iter()771 .map(|(key, permission)| PropertyKeyPermission { key, permission })772 .collect();773774 let properties = <CollectionProperties<T>>::get(collection)775 .into_iter()776 .map(|(key, value)| Property { key, value })777 .collect();778779 let permissions = CollectionPermissions {780 access: Some(permissions.access()),781 mint_mode: Some(permissions.mint_mode()),782 nesting: Some(permissions.nesting().clone()),783 };784785 Some(RpcCollection {786 name: name.into_inner(),787 description: description.into_inner(),788 owner,789 mode,790 token_prefix: token_prefix.into_inner(),791 sponsorship,792 limits,793 permissions,794 token_property_permissions,795 properties,796 read_only: external_collection,797 })798 }799}800801macro_rules! limit_default {802 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{803 $(804 if let Some($new) = $new.$field {805 let $old = $old.$field($($arg)?);806 let _ = $new;807 let _ = $old;808 $check809 } else {810 $new.$field = $old.$field811 }812 )*813 }};814}815macro_rules! limit_default_clone {816 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{817 $(818 if let Some($new) = $new.$field.clone() {819 let $old = $old.$field($($arg)?);820 let _ = $new;821 let _ = $old;822 $check823 } else {824 $new.$field = $old.$field.clone()825 }826 )*827 }};828}829830impl<T: Config> Pallet<T> {831 /// Create new collection.832 ///833 /// * `owner` - The owner of the collection.834 /// * `data` - Description of the created collection.835 /// * `is_external` - Marks that collection managet by not "Unique network".836 pub fn init_collection(837 owner: T::CrossAccountId,838 data: CreateCollectionData<T::AccountId>,839 is_external: bool,840 ) -> Result<CollectionId, DispatchError> {841 {842 ensure!(843 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,844 Error::<T>::CollectionTokenPrefixLimitExceeded845 );846 }847848 let created_count = <CreatedCollectionCount<T>>::get()849 .0850 .checked_add(1)851 .ok_or(ArithmeticError::Overflow)?;852 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;853 let id = CollectionId(created_count);854855 // bound Total number of collections856 ensure!(857 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,858 <Error<T>>::TotalCollectionsLimitExceeded859 );860861 // =========862863 let collection = Collection {864 owner: owner.as_sub().clone(),865 name: data.name,866 mode: data.mode.clone(),867 description: data.description,868 token_prefix: data.token_prefix,869 sponsorship: data870 .pending_sponsor871 .map(SponsorshipState::Unconfirmed)872 .unwrap_or_default(),873 limits: data874 .limits875 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))876 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,877 permissions: data878 .permissions879 .map(|permissions| {880 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)881 })882 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,883 external_collection: is_external,884 };885886 let mut collection_properties = up_data_structs::CollectionProperties::get();887 collection_properties888 .try_set_from_iter(data.properties.into_iter())889 .map_err(<Error<T>>::from)?;890891 CollectionProperties::<T>::insert(id, collection_properties);892893 let mut token_props_permissions = PropertiesPermissionMap::new();894 token_props_permissions895 .try_set_from_iter(data.token_property_permissions.into_iter())896 .map_err(<Error<T>>::from)?;897898 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);899900 // Take a (non-refundable) deposit of collection creation901 {902 let mut imbalance =903 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();904 imbalance.subsume(905 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(906 &T::TreasuryAccountId::get(),907 T::CollectionCreationPrice::get(),908 ),909 );910 <T as Config>::Currency::settle(911 owner.as_sub(),912 imbalance,913 WithdrawReasons::TRANSFER,914 ExistenceRequirement::KeepAlive,915 )916 .map_err(|_| Error::<T>::NotSufficientFounds)?;917 }918919 <CreatedCollectionCount<T>>::put(created_count);920 <Pallet<T>>::deposit_event(Event::CollectionCreated(921 id,922 data.mode.id(),923 owner.as_sub().clone(),924 ));925 <PalletEvm<T>>::deposit_log(926 erc::CollectionHelpersEvents::CollectionCreated {927 owner: *owner.as_eth(),928 collection_id: eth::collection_id_to_address(id),929 }930 .to_log(T::ContractAddress::get()),931 );932 <CollectionById<T>>::insert(id, collection);933 Ok(id)934 }935936 /// Destroy collection.937 ///938 /// * `collection` - Collection handler.939 /// * `sender` - The owner or administrator of the collection.940 pub fn destroy_collection(941 collection: CollectionHandle<T>,942 sender: &T::CrossAccountId,943 ) -> DispatchResult {944 ensure!(945 collection.limits.owner_can_destroy(),946 <Error<T>>::NoPermission,947 );948 collection.check_is_owner(sender)?;949950 let destroyed_collections = <DestroyedCollectionCount<T>>::get()951 .0952 .checked_add(1)953 .ok_or(ArithmeticError::Overflow)?;954955 // =========956957 <DestroyedCollectionCount<T>>::put(destroyed_collections);958 <CollectionById<T>>::remove(collection.id);959 <AdminAmount<T>>::remove(collection.id);960 <IsAdmin<T>>::remove_prefix((collection.id,), None);961 <Allowlist<T>>::remove_prefix((collection.id,), None);962 <CollectionProperties<T>>::remove(collection.id);963964 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));965 Ok(())966 }967968 /// Set collection property.969 ///970 /// * `collection` - Collection handler.971 /// * `sender` - The owner or administrator of the collection.972 /// * `property` - The property to set.973 pub fn set_collection_property(974 collection: &CollectionHandle<T>,975 sender: &T::CrossAccountId,976 property: Property,977 ) -> DispatchResult {978 collection.check_is_owner_or_admin(sender)?;979980 CollectionProperties::<T>::try_mutate(collection.id, |properties| {981 let property = property.clone();982 properties.try_set(property.key, property.value)983 })984 .map_err(<Error<T>>::from)?;985986 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));987988 Ok(())989 }990991 /// Set scouped collection property.992 ///993 /// * `collection_id` - ID of the collection for which the property is being set.994 /// * `scope` - Property scope.995 /// * `property` - The property to set.996 pub fn set_scoped_collection_property(997 collection_id: CollectionId,998 scope: PropertyScope,999 property: Property,1000 ) -> DispatchResult {1001 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1002 properties.try_scoped_set(scope, property.key, property.value)1003 })1004 .map_err(<Error<T>>::from)?;10051006 Ok(())1007 }10081009 /// Set scouped collection properties.1010 ///1011 /// * `collection_id` - ID of the collection for which the properties is being set.1012 /// * `scope` - Property scope.1013 /// * `properties` - The properties to set.1014 pub fn set_scoped_collection_properties(1015 collection_id: CollectionId,1016 scope: PropertyScope,1017 properties: impl Iterator<Item = Property>,1018 ) -> DispatchResult {1019 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1020 stored_properties.try_scoped_set_from_iter(scope, properties)1021 })1022 .map_err(<Error<T>>::from)?;10231024 Ok(())1025 }10261027 /// Set collection properties.1028 ///1029 /// * `collection` - Collection handler.1030 /// * `sender` - The owner or administrator of the collection.1031 /// * `properties` - The properties to set.1032 #[transactional]1033 pub fn set_collection_properties(1034 collection: &CollectionHandle<T>,1035 sender: &T::CrossAccountId,1036 properties: Vec<Property>,1037 ) -> DispatchResult {1038 for property in properties {1039 Self::set_collection_property(collection, sender, property)?;1040 }10411042 Ok(())1043 }10441045 /// Delete collection property.1046 ///1047 /// * `collection` - Collection handler.1048 /// * `sender` - The owner or administrator of the collection.1049 /// * `property` - The property to delete.1050 pub fn delete_collection_property(1051 collection: &CollectionHandle<T>,1052 sender: &T::CrossAccountId,1053 property_key: PropertyKey,1054 ) -> DispatchResult {1055 collection.check_is_owner_or_admin(sender)?;10561057 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1058 properties.remove(&property_key)1059 })1060 .map_err(<Error<T>>::from)?;10611062 Self::deposit_event(Event::CollectionPropertyDeleted(1063 collection.id,1064 property_key,1065 ));10661067 Ok(())1068 }10691070 /// Delete collection properties.1071 ///1072 /// * `collection` - Collection handler.1073 /// * `sender` - The owner or administrator of the collection.1074 /// * `properties` - The properties to delete.1075 #[transactional]1076 pub fn delete_collection_properties(1077 collection: &CollectionHandle<T>,1078 sender: &T::CrossAccountId,1079 property_keys: Vec<PropertyKey>,1080 ) -> DispatchResult {1081 for key in property_keys {1082 Self::delete_collection_property(collection, sender, key)?;1083 }10841085 Ok(())1086 }10871088 /// Set collection propetry permission without any checks.1089 ///1090 /// Used for migrations.1091 ///1092 /// * `collection` - Collection handler.1093 /// * `property_permissions` - Property permissions.1094 pub fn set_property_permission_unchecked(1095 collection: CollectionId,1096 property_permission: PropertyKeyPermission,1097 ) -> DispatchResult {1098 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1099 permissions.try_set(property_permission.key, property_permission.permission)1100 })1101 .map_err(<Error<T>>::from)?;1102 Ok(())1103 }11041105 /// Set collection property permission.1106 ///1107 /// * `collection` - Collection handler.1108 /// * `sender` - The owner or administrator of the collection.1109 /// * `property_permission` - Property permission.1110 pub fn set_property_permission(1111 collection: &CollectionHandle<T>,1112 sender: &T::CrossAccountId,1113 property_permission: PropertyKeyPermission,1114 ) -> DispatchResult {1115 collection.check_is_owner_or_admin(sender)?;11161117 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1118 let current_permission = all_permissions.get(&property_permission.key);1119 if matches![1120 current_permission,1121 Some(PropertyPermission { mutable: false, .. })1122 ] {1123 return Err(<Error<T>>::NoPermission.into());1124 }11251126 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1127 let property_permission = property_permission.clone();1128 permissions.try_set(property_permission.key, property_permission.permission)1129 })1130 .map_err(<Error<T>>::from)?;11311132 Self::deposit_event(Event::PropertyPermissionSet(1133 collection.id,1134 property_permission.key,1135 ));11361137 Ok(())1138 }11391140 /// Set token property permission.1141 ///1142 /// * `collection` - Collection handler.1143 /// * `sender` - The owner or administrator of the collection.1144 /// * `property_permissions` - Property permissions.1145 #[transactional]1146 pub fn set_token_property_permissions(1147 collection: &CollectionHandle<T>,1148 sender: &T::CrossAccountId,1149 property_permissions: Vec<PropertyKeyPermission>,1150 ) -> DispatchResult {1151 for prop_pemission in property_permissions {1152 Self::set_property_permission(collection, sender, prop_pemission)?;1153 }11541155 Ok(())1156 }11571158 /// Get collection property.1159 pub fn get_collection_property(1160 collection_id: CollectionId,1161 key: &PropertyKey,1162 ) -> Option<PropertyValue> {1163 Self::collection_properties(collection_id).get(key).cloned()1164 }11651166 /// Convert byte vector to property key vector.1167 pub fn bytes_keys_to_property_keys(1168 keys: Vec<Vec<u8>>,1169 ) -> Result<Vec<PropertyKey>, DispatchError> {1170 keys.into_iter()1171 .map(|key| -> Result<PropertyKey, DispatchError> {1172 key.try_into()1173 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1174 })1175 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1176 }11771178 /// Get properties according to given keys.1179 pub fn filter_collection_properties(1180 collection_id: CollectionId,1181 keys: Option<Vec<PropertyKey>>,1182 ) -> Result<Vec<Property>, DispatchError> {1183 let properties = Self::collection_properties(collection_id);11841185 let properties = keys1186 .map(|keys| {1187 keys.into_iter()1188 .filter_map(|key| {1189 properties.get(&key).map(|value| Property {1190 key,1191 value: value.clone(),1192 })1193 })1194 .collect()1195 })1196 .unwrap_or_else(|| {1197 properties1198 .into_iter()1199 .map(|(key, value)| Property { key, value })1200 .collect()1201 });12021203 Ok(properties)1204 }12051206 /// Get property permissions according to given keys.1207 pub fn filter_property_permissions(1208 collection_id: CollectionId,1209 keys: Option<Vec<PropertyKey>>,1210 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1211 let permissions = Self::property_permissions(collection_id);12121213 let key_permissions = keys1214 .map(|keys| {1215 keys.into_iter()1216 .filter_map(|key| {1217 permissions1218 .get(&key)1219 .map(|permission| PropertyKeyPermission {1220 key,1221 permission: permission.clone(),1222 })1223 })1224 .collect()1225 })1226 .unwrap_or_else(|| {1227 permissions1228 .into_iter()1229 .map(|(key, permission)| PropertyKeyPermission { key, permission })1230 .collect()1231 });12321233 Ok(key_permissions)1234 }12351236 /// Toggle `user` participation in the `collection`'s allow list.1237 pub fn toggle_allowlist(1238 collection: &CollectionHandle<T>,1239 sender: &T::CrossAccountId,1240 user: &T::CrossAccountId,1241 allowed: bool,1242 ) -> DispatchResult {1243 collection.check_is_owner_or_admin(sender)?;12441245 // =========12461247 if allowed {1248 <Allowlist<T>>::insert((collection.id, user), true);1249 } else {1250 <Allowlist<T>>::remove((collection.id, user));1251 }12521253 Ok(())1254 }12551256 /// Toggle `user` participation in the `collection`'s admin list.1257 pub fn toggle_admin(1258 collection: &CollectionHandle<T>,1259 sender: &T::CrossAccountId,1260 user: &T::CrossAccountId,1261 admin: bool,1262 ) -> DispatchResult {1263 collection.check_is_owner(sender)?;12641265 let was_admin = <IsAdmin<T>>::get((collection.id, user));1266 if was_admin == admin {1267 return Ok(());1268 }1269 let amount = <AdminAmount<T>>::get(collection.id);12701271 if admin {1272 let amount = amount1273 .checked_add(1)1274 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1275 ensure!(1276 amount <= Self::collection_admins_limit(),1277 <Error<T>>::CollectionAdminCountExceeded,1278 );12791280 // =========12811282 <AdminAmount<T>>::insert(collection.id, amount);1283 <IsAdmin<T>>::insert((collection.id, user), true);1284 } else {1285 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1286 <IsAdmin<T>>::remove((collection.id, user));1287 }12881289 Ok(())1290 }12911292 /// Merge set fields from `new_limit` to `old_limit`.1293 pub fn clamp_limits(1294 mode: CollectionMode,1295 old_limit: &CollectionLimits,1296 mut new_limit: CollectionLimits,1297 ) -> Result<CollectionLimits, DispatchError> {1298 let limits = old_limit;1299 limit_default!(old_limit, new_limit,1300 account_token_ownership_limit => ensure!(1301 new_limit <= MAX_TOKEN_OWNERSHIP,1302 <Error<T>>::CollectionLimitBoundsExceeded,1303 ),1304 sponsored_data_size => ensure!(1305 new_limit <= CUSTOM_DATA_LIMIT,1306 <Error<T>>::CollectionLimitBoundsExceeded,1307 ),13081309 sponsored_data_rate_limit => {},1310 token_limit => ensure!(1311 old_limit >= new_limit && new_limit > 0,1312 <Error<T>>::CollectionTokenLimitExceeded1313 ),13141315 sponsor_transfer_timeout(match mode {1316 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1317 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1318 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1319 }) => ensure!(1320 new_limit <= MAX_SPONSOR_TIMEOUT,1321 <Error<T>>::CollectionLimitBoundsExceeded,1322 ),1323 sponsor_approve_timeout => {},1324 owner_can_transfer => ensure!(1325 !limits.owner_can_transfer_instaled() ||1326 old_limit || !new_limit,1327 <Error<T>>::OwnerPermissionsCantBeReverted,1328 ),1329 owner_can_destroy => ensure!(1330 old_limit || !new_limit,1331 <Error<T>>::OwnerPermissionsCantBeReverted,1332 ),1333 transfers_enabled => {},1334 );1335 Ok(new_limit)1336 }13371338 /// Merge set fields from `new_permission` to `old_permission`.1339 pub fn clamp_permissions(1340 _mode: CollectionMode,1341 old_permission: &CollectionPermissions,1342 mut new_permission: CollectionPermissions,1343 ) -> Result<CollectionPermissions, DispatchError> {1344 limit_default_clone!(old_permission, new_permission,1345 access => {},1346 mint_mode => {},1347 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1348 );1349 Ok(new_permission)1350 }1351}13521353/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1354#[macro_export]1355macro_rules! unsupported {1356 () => {1357 Err(<Error<T>>::UnsupportedOperation.into())1358 };1359}13601361/// Return weights for various worst-case operations.1362pub trait CommonWeightInfo<CrossAccountId> {1363 /// Weight of item creation.1364 fn create_item() -> Weight;13651366 /// Weight of items creation.1367 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;13681369 /// Weight of items creation.1370 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;13711372 /// The weight of the burning item.1373 fn burn_item() -> Weight;13741375 /// Property setting weight.1376 ///1377 /// * `amount`- The number of properties to set.1378 fn set_collection_properties(amount: u32) -> Weight;13791380 /// Collection property deletion weight.1381 ///1382 /// * `amount`- The number of properties to set.1383 fn delete_collection_properties(amount: u32) -> Weight;13841385 /// Token property setting weight.1386 ///1387 /// * `amount`- The number of properties to set.1388 fn set_token_properties(amount: u32) -> Weight;13891390 /// Token property deletion weight.1391 ///1392 /// * `amount`- The number of properties to delete.1393 fn delete_token_properties(amount: u32) -> Weight;13941395 /// Token property permissions set weight.1396 ///1397 /// * `amount`- The number of property permissions to set.1398 fn set_token_property_permissions(amount: u32) -> Weight;13991400 /// Transfer price of the token or its parts.1401 fn transfer() -> Weight;14021403 /// The price of setting the permission of the operation from another user.1404 fn approve() -> Weight;14051406 /// Transfer price from another user.1407 fn transfer_from() -> Weight;14081409 /// The price of burning a token from another user.1410 fn burn_from() -> Weight;14111412 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1413 /// whole users's balance.1414 ///1415 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1416 fn burn_recursively_self_raw() -> Weight;14171418 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1419 ///1420 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1421 fn burn_recursively_breadth_raw(amount: u32) -> Weight;14221423 /// The price of recursive burning a token.1424 ///1425 /// `max_selfs` - The maximum burning weight of the token itself.1426 /// `max_breadth` - The maximum number of nested tokens to burn.1427 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1428 Self::burn_recursively_self_raw()1429 .saturating_mul(max_selfs.max(1) as u64)1430 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1431 }1432}14331434/// Weight info extension trait for refungible pallet.1435pub trait RefungibleExtensionsWeightInfo {1436 /// Weight of token repartition.1437 fn repartition() -> Weight;1438}14391440/// Common collection operations.1441///1442/// It wraps methods in Fungible, Nonfungible and Refungible pallets1443/// and adds weight info.1444pub trait CommonCollectionOperations<T: Config> {1445 /// Create token.1446 ///1447 /// * `sender` - The user who mint the token and pays for the transaction.1448 /// * `to` - The user who will own the token.1449 /// * `data` - Token data.1450 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1451 fn create_item(1452 &self,1453 sender: T::CrossAccountId,1454 to: T::CrossAccountId,1455 data: CreateItemData,1456 nesting_budget: &dyn Budget,1457 ) -> DispatchResultWithPostInfo;14581459 /// Create multiple tokens.1460 ///1461 /// * `sender` - The user who mint the token and pays for the transaction.1462 /// * `to` - The user who will own the token.1463 /// * `data` - Token data.1464 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1465 fn create_multiple_items(1466 &self,1467 sender: T::CrossAccountId,1468 to: T::CrossAccountId,1469 data: Vec<CreateItemData>,1470 nesting_budget: &dyn Budget,1471 ) -> DispatchResultWithPostInfo;14721473 /// Create multiple tokens.1474 ///1475 /// * `sender` - The user who mint the token and pays for the transaction.1476 /// * `to` - The user who will own the token.1477 /// * `data` - Token data.1478 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1479 fn create_multiple_items_ex(1480 &self,1481 sender: T::CrossAccountId,1482 data: CreateItemExData<T::CrossAccountId>,1483 nesting_budget: &dyn Budget,1484 ) -> DispatchResultWithPostInfo;14851486 /// Burn token.1487 ///1488 /// * `sender` - The user who owns the token.1489 /// * `token` - Token id that will burned.1490 /// * `amount` - The number of parts of the token that will be burned.1491 fn burn_item(1492 &self,1493 sender: T::CrossAccountId,1494 token: TokenId,1495 amount: u128,1496 ) -> DispatchResultWithPostInfo;14971498 /// Burn token and all nested tokens recursievly.1499 ///1500 /// * `sender` - The user who owns the token.1501 /// * `token` - Token id that will burned.1502 /// * `self_budget` - The budget that can be spent on burning tokens.1503 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1504 fn burn_item_recursively(1505 &self,1506 sender: T::CrossAccountId,1507 token: TokenId,1508 self_budget: &dyn Budget,1509 breadth_budget: &dyn Budget,1510 ) -> DispatchResultWithPostInfo;15111512 /// Set collection properties.1513 ///1514 /// * `sender` - Must be either the owner of the collection or its admin.1515 /// * `properties` - Properties to be set.1516 fn set_collection_properties(1517 &self,1518 sender: T::CrossAccountId,1519 properties: Vec<Property>,1520 ) -> DispatchResultWithPostInfo;15211522 /// Delete collection properties.1523 ///1524 /// * `sender` - Must be either the owner of the collection or its admin.1525 /// * `properties` - The properties to be removed.1526 fn delete_collection_properties(1527 &self,1528 sender: &T::CrossAccountId,1529 property_keys: Vec<PropertyKey>,1530 ) -> DispatchResultWithPostInfo;15311532 /// Set token properties.1533 ///1534 /// The appropriate [`PropertyPermission`] for the token property1535 /// must be set with [`Self::set_token_property_permissions`].1536 ///1537 /// * `sender` - Must be either the owner of the token or its admin.1538 /// * `token_id` - The token for which the properties are being set.1539 /// * `properties` - Properties to be set.1540 /// * `budget` - Budget for setting properties.1541 fn set_token_properties(1542 &self,1543 sender: T::CrossAccountId,1544 token_id: TokenId,1545 properties: Vec<Property>,1546 budget: &dyn Budget,1547 ) -> DispatchResultWithPostInfo;15481549 /// Remove token properties.1550 ///1551 /// The appropriate [`PropertyPermission`] for the token property1552 /// must be set with [`Self::set_token_property_permissions`].1553 ///1554 /// * `sender` - Must be either the owner of the token or its admin.1555 /// * `token_id` - The token for which the properties are being remove.1556 /// * `property_keys` - Keys to remove corresponding properties.1557 /// * `budget` - Budget for removing properties.1558 fn delete_token_properties(1559 &self,1560 sender: T::CrossAccountId,1561 token_id: TokenId,1562 property_keys: Vec<PropertyKey>,1563 budget: &dyn Budget,1564 ) -> DispatchResultWithPostInfo;15651566 /// Set token property permissions.1567 ///1568 /// * `sender` - Must be either the owner of the token or its admin.1569 /// * `token_id` - The token for which the properties are being set.1570 /// * `properties` - Properties to be set.1571 /// * `budget` - Budget for setting properties.1572 fn set_token_property_permissions(1573 &self,1574 sender: &T::CrossAccountId,1575 property_permissions: Vec<PropertyKeyPermission>,1576 ) -> DispatchResultWithPostInfo;15771578 /// Transfer amount of token pieces.1579 ///1580 /// * `sender` - Donor user.1581 /// * `to` - Recepient user.1582 /// * `token` - The token of which parts are being sent.1583 /// * `amount` - The number of parts of the token that will be transferred.1584 /// * `budget` - The maximum budget that can be spent on the transfer.1585 fn transfer(1586 &self,1587 sender: T::CrossAccountId,1588 to: T::CrossAccountId,1589 token: TokenId,1590 amount: u128,1591 budget: &dyn Budget,1592 ) -> DispatchResultWithPostInfo;15931594 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1595 ///1596 /// * `sender` - The user who grants access to the token.1597 /// * `spender` - The user to whom the rights are granted.1598 /// * `token` - The token to which access is granted.1599 /// * `amount` - The amount of pieces that another user can dispose of.1600 fn approve(1601 &self,1602 sender: T::CrossAccountId,1603 spender: T::CrossAccountId,1604 token: TokenId,1605 amount: u128,1606 ) -> DispatchResultWithPostInfo;16071608 /// Send parts of a token owned by another user.1609 ///1610 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1611 ///1612 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1613 /// * `from` - The user who owns the token.1614 /// * `to` - Recepient user.1615 /// * `token` - The token of which parts are being sent.1616 /// * `amount` - The number of parts of the token that will be transferred.1617 /// * `budget` - The maximum budget that can be spent on the transfer.1618 fn transfer_from(1619 &self,1620 sender: T::CrossAccountId,1621 from: T::CrossAccountId,1622 to: T::CrossAccountId,1623 token: TokenId,1624 amount: u128,1625 budget: &dyn Budget,1626 ) -> DispatchResultWithPostInfo;16271628 /// Burn parts of a token owned by another user.1629 ///1630 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1631 ///1632 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1633 /// * `from` - The user who owns the token.1634 /// * `token` - The token of which parts are being sent.1635 /// * `amount` - The number of parts of the token that will be transferred.1636 /// * `budget` - The maximum budget that can be spent on the burn.1637 fn burn_from(1638 &self,1639 sender: T::CrossAccountId,1640 from: T::CrossAccountId,1641 token: TokenId,1642 amount: u128,1643 budget: &dyn Budget,1644 ) -> DispatchResultWithPostInfo;16451646 /// Check permission to nest token.1647 ///1648 /// * `sender` - The user who initiated the check.1649 /// * `from` - The token that is checked for embedding.1650 /// * `under` - Token under which to check.1651 /// * `budget` - The maximum budget that can be spent on the check.1652 fn check_nesting(1653 &self,1654 sender: T::CrossAccountId,1655 from: (CollectionId, TokenId),1656 under: TokenId,1657 budget: &dyn Budget,1658 ) -> DispatchResult;16591660 /// Nest one token into another.1661 ///1662 /// * `under` - Token holder.1663 /// * `to_nest` - Nested token.1664 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16651666 /// Unnest token.1667 ///1668 /// * `under` - Token holder.1669 /// * `to_nest` - Token to unnest.1670 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));16711672 /// Get all user tokens.1673 ///1674 /// * `account` - Account for which you need to get tokens.1675 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;16761677 /// Get all the tokens in the collection.1678 fn collection_tokens(&self) -> Vec<TokenId>;16791680 /// Check if the token exists.1681 ///1682 /// * `token` - Id token to check.1683 fn token_exists(&self, token: TokenId) -> bool;16841685 /// Get the id of the last minted token.1686 fn last_token_id(&self) -> TokenId;16871688 /// Get the owner of the token.1689 ///1690 /// * `token` - The token for which you need to find out the owner.1691 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;16921693 /// Returns 10 tokens owners in no particular order.1694 ///1695 /// * `token` - The token for which you need to find out the owners.1696 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;16971698 /// Get the value of the token property by key.1699 ///1700 /// * `token` - Token with the property to get.1701 /// * `key` - Property name.1702 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17031704 /// Get a set of token properties by key vector.1705 ///1706 /// * `token` - Token with the property to get.1707 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1708 /// then all properties are returned.1709 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17101711 /// Amount of unique collection tokens1712 fn total_supply(&self) -> u32;17131714 /// Amount of different tokens account has.1715 ///1716 /// * `account` - The account for which need to get the balance.1717 fn account_balance(&self, account: T::CrossAccountId) -> u32;17181719 /// Amount of specific token account have.1720 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17211722 /// Amount of token pieces1723 fn total_pieces(&self, token: TokenId) -> Option<u128>;17241725 /// Get the number of parts of the token that a trusted user can manage.1726 ///1727 /// * `sender` - Trusted user.1728 /// * `spender` - Owner of the token.1729 /// * `token` - The token for which to get the value.1730 fn allowance(1731 &self,1732 sender: T::CrossAccountId,1733 spender: T::CrossAccountId,1734 token: TokenId,1735 ) -> u128;17361737 /// Get extension for RFT collection.1738 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1739}17401741/// Extension for RFT collection.1742pub trait RefungibleExtensions<T>1743where1744 T: Config,1745{1746 /// Change the number of parts of the token.1747 ///1748 /// When the value changes down, this function is equivalent to burning parts of the token.1749 ///1750 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1751 /// * `token` - The token for which you want to change the number of parts.1752 /// * `amount` - The new value of the parts of the token.1753 fn repartition(1754 &self,1755 sender: &T::CrossAccountId,1756 token: TokenId,1757 amount: u128,1758 ) -> DispatchResultWithPostInfo;1759}17601761/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1762///1763/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1764pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1765 let post_info = PostDispatchInfo {1766 actual_weight: Some(weight),1767 pays_fee: Pays::Yes,1768 };1769 match res {1770 Ok(()) => Ok(post_info),1771 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1772 }1773}17741775impl<T: Config> From<PropertiesError> for Error<T> {1776 fn from(error: PropertiesError) -> Self {1777 match error {1778 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1779 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1780 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1781 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1782 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1783 }1784 }1785}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Common pallet18//!19//! The Common pallet provides functionality for handling collections.20//!21//! ## Overview22//!23//! The Common pallet provides an interface for common collection operations for different collection types24//! (see [CommonCollectionOperations]), as well as a generic dispatcher for these, see [dispatch] module.25//! It also provides this functionality to EVM, see [erc] and [eth] modules.26//!27//! The Common pallet provides functions for:28//!29//! - Setting and approving collection sponsor.30//! - Get\set\delete allow list.31//! - Get\set\delete collection properties.32//! - Get\set\delete collection property permissions.33//! - Get\set\delete token property permissions.34//! - Get\set\delete collection administrators.35//! - Checking access permissions.36//!37//! ### Terminology38//! **Collection sponsor** - For the collection, you can set a sponsor, at whose expense it will39//! be possible to mint tokens.40//!41//! **Allow list** - List of users who have the right to minting tokens.42//!43//! **Collection properties** - Collection properties are simply key-value stores where various44//! metadata can be placed.45//!46//! **Permissions on token properties** - For each property in the token can be set permission47//! to change, see [`PropertyPermission`].48//!49//! **Collection administrator** - For a collection, you can set administrators who have the right50//! to most actions on the collection.5152#![warn(missing_docs)]53#![cfg_attr(not(feature = "std"), no_std)]54extern crate alloc;5556use core::ops::{Deref, DerefMut};57use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};58use sp_std::vec::Vec;59use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};60use evm_coder::ToLog;61use frame_support::{62 dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},63 ensure,64 traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},65 weights::Pays,66 transactional,67};68use pallet_evm::GasWeightMapping;69use up_data_structs::{70 COLLECTION_NUMBER_LIMIT,71 Collection,72 RpcCollection,73 CollectionId,74 CreateItemData,75 MAX_TOKEN_PREFIX_LENGTH,76 COLLECTION_ADMINS_LIMIT,77 TokenId,78 TokenChild,79 CollectionStats,80 MAX_TOKEN_OWNERSHIP,81 CollectionMode,82 NFT_SPONSOR_TRANSFER_TIMEOUT,83 FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,84 REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,85 MAX_SPONSOR_TIMEOUT,86 CUSTOM_DATA_LIMIT,87 CollectionLimits,88 CreateCollectionData,89 SponsorshipState,90 CreateItemExData,91 SponsoringRateLimit,92 budget::Budget,93 PhantomType,94 Property,95 Properties,96 PropertiesPermissionMap,97 PropertyKey,98 PropertyValue,99 PropertyPermission,100 PropertiesError,101 PropertyKeyPermission,102 TokenData,103 TrySetProperty,104 PropertyScope,105 // RMRK106 RmrkCollectionInfo,107 RmrkInstanceInfo,108 RmrkResourceInfo,109 RmrkPropertyInfo,110 RmrkBaseInfo,111 RmrkPartType,112 RmrkBoundedTheme,113 RmrkNftChild,114 CollectionPermissions,115 SchemaVersion,116};117118pub use pallet::*;119use sp_core::H160;120use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};121#[cfg(feature = "runtime-benchmarks")]122pub mod benchmarking;123pub mod dispatch;124pub mod erc;125pub mod eth;126pub mod weights;127128/// Weight info.129pub type SelfWeightOf<T> = <T as Config>::WeightInfo;130131/// Collection handle contains information about collection data and id.132/// Also provides functionality to count consumed gas.133///134/// CollectionHandle is used as a generic wrapper for collections of all types.135/// It allows to perform common operations and queries on any collection type,136/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].137#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]138pub struct CollectionHandle<T: Config> {139 /// Collection id140 pub id: CollectionId,141 collection: Collection<T::AccountId>,142 /// Substrate recorder for counting consumed gas143 pub recorder: SubstrateRecorder<T>,144}145146impl<T: Config> WithRecorder<T> for CollectionHandle<T> {147 fn recorder(&self) -> &SubstrateRecorder<T> {148 &self.recorder149 }150 fn into_recorder(self) -> SubstrateRecorder<T> {151 self.recorder152 }153}154155impl<T: Config> CollectionHandle<T> {156 /// Same as [CollectionHandle::new] but with an explicit gas limit.157 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {158 <CollectionById<T>>::get(id).map(|collection| Self {159 id,160 collection,161 recorder: SubstrateRecorder::new(gas_limit),162 })163 }164165 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].166 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {167 <CollectionById<T>>::get(id).map(|collection| Self {168 id,169 collection,170 recorder,171 })172 }173174 /// Retrives collection data from storage and creates collection handle with default parameters.175 /// If collection not found return `None`176 pub fn new(id: CollectionId) -> Option<Self> {177 Self::new_with_gas_limit(id, u64::MAX)178 }179180 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.181 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {182 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)183 }184185 /// Consume gas for reading.186 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {187 self.recorder188 .consume_gas(T::GasWeightMapping::weight_to_gas(189 <T as frame_system::Config>::DbWeight::get()190 .read191 .saturating_mul(reads),192 ))193 }194195 /// Consume gas for writing.196 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {197 self.recorder198 .consume_gas(T::GasWeightMapping::weight_to_gas(199 <T as frame_system::Config>::DbWeight::get()200 .write201 .saturating_mul(writes),202 ))203 }204205 /// Save collection to storage.206 pub fn save(self) -> DispatchResult {207 <CollectionById<T>>::insert(self.id, self.collection);208 Ok(())209 }210211 /// Set collection sponsor.212 ///213 /// Unique collections allows sponsoring for certain actions.214 /// This method allows you to set the sponsor of the collection.215 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].216 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {217 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);218 Ok(())219 }220221 /// Confirm sponsorship222 ///223 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.224 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].225 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {226 if self.collection.sponsorship.pending_sponsor() != Some(sender) {227 return Ok(false);228 }229230 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());231 Ok(true)232 }233234 /// Checks that the collection was created with, and must be operated upon through **Unique API**.235 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.236 pub fn check_is_internal(&self) -> DispatchResult {237 if self.external_collection {238 return Err(<Error<T>>::CollectionIsExternal)?;239 }240241 Ok(())242 }243244 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.245 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.246 pub fn check_is_external(&self) -> DispatchResult {247 if !self.external_collection {248 return Err(<Error<T>>::CollectionIsInternal)?;249 }250251 Ok(())252 }253}254255impl<T: Config> Deref for CollectionHandle<T> {256 type Target = Collection<T::AccountId>;257258 fn deref(&self) -> &Self::Target {259 &self.collection260 }261}262263impl<T: Config> DerefMut for CollectionHandle<T> {264 fn deref_mut(&mut self) -> &mut Self::Target {265 &mut self.collection266 }267}268269impl<T: Config> CollectionHandle<T> {270 /// Checks if the `user` is the owner of the collection.271 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {272 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);273 Ok(())274 }275276 /// Returns **true** if the `user` is the owner or administrator of the collection.277 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {278 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))279 }280281 /// Checks if the `user` is the owner or administrator of the collection.282 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {283 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);284 Ok(())285 }286287 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.288 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {289 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)290 }291292 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.293 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {294 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)295 }296297 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.298 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {299 ensure!(300 <Allowlist<T>>::get((self.id, user)),301 <Error<T>>::AddressNotInAllowlist302 );303 Ok(())304 }305}306307#[frame_support::pallet]308pub mod pallet {309 use super::*;310 use pallet_evm::account;311 use dispatch::CollectionDispatch;312 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};313 use frame_system::pallet_prelude::*;314 use frame_support::traits::Currency;315 use up_data_structs::{TokenId, mapping::TokenAddressMapping};316 use scale_info::TypeInfo;317 use weights::WeightInfo;318319 #[pallet::config]320 pub trait Config:321 frame_system::Config322 + pallet_evm_coder_substrate::Config323 + pallet_evm::Config324 + TypeInfo325 + account::Config326 {327 /// Weight information for functions of this pallet.328 type WeightInfo: WeightInfo;329330 /// Events compatible with [`frame_system::Config::Event`].331 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;332333 /// Handler of accounts and payment.334 type Currency: Currency<Self::AccountId>;335336 /// Set price to create a collection.337 #[pallet::constant]338 type CollectionCreationPrice: Get<339 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,340 >;341342 /// Dispatcher of operations on collections.343 type CollectionDispatch: CollectionDispatch<Self>;344345 /// Account which holds the chain's treasury.346 type TreasuryAccountId: Get<Self::AccountId>;347348 /// Address under which the CollectionHelper contract would be available.349 type ContractAddress: Get<H160>;350351 /// Mapper for token addresses to Ethereum addresses.352 type EvmTokenAddressMapping: TokenAddressMapping<H160>;353354 /// Mapper for token addresses to [`CrossAccountId`].355 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;356 }357358 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);359360 #[pallet::pallet]361 #[pallet::storage_version(STORAGE_VERSION)]362 #[pallet::generate_store(pub(super) trait Store)]363 pub struct Pallet<T>(_);364365 #[pallet::extra_constants]366 impl<T: Config> Pallet<T> {367 /// Maximum admins per collection.368 pub fn collection_admins_limit() -> u32 {369 COLLECTION_ADMINS_LIMIT370 }371 }372373 #[pallet::event]374 #[pallet::generate_deposit(pub fn deposit_event)]375 pub enum Event<T: Config> {376 /// New collection was created377 CollectionCreated(378 /// Globally unique identifier of newly created collection.379 CollectionId,380 /// [`CollectionMode`] converted into _u8_.381 u8,382 /// Collection owner.383 T::AccountId,384 ),385386 /// New collection was destroyed387 CollectionDestroyed(388 /// Globally unique identifier of collection.389 CollectionId,390 ),391392 /// New item was created.393 ItemCreated(394 /// Id of the collection where item was created.395 CollectionId,396 /// Id of an item. Unique within the collection.397 TokenId,398 /// Owner of newly created item399 T::CrossAccountId,400 /// Always 1 for NFT401 u128,402 ),403404 /// Collection item was burned.405 ItemDestroyed(406 /// Id of the collection where item was destroyed.407 CollectionId,408 /// Identifier of burned NFT.409 TokenId,410 /// Which user has destroyed its tokens.411 T::CrossAccountId,412 /// Amount of token pieces destroed. Always 1 for NFT.413 u128,414 ),415416 /// Item was transferred417 Transfer(418 /// Id of collection to which item is belong.419 CollectionId,420 /// Id of an item.421 TokenId,422 /// Original owner of item.423 T::CrossAccountId,424 /// New owner of item.425 T::CrossAccountId,426 /// Amount of token pieces transfered. Always 1 for NFT.427 u128,428 ),429430 /// Amount pieces of token owned by `sender` was approved for `spender`.431 Approved(432 /// Id of collection to which item is belong.433 CollectionId,434 /// Id of an item.435 TokenId,436 /// Original owner of item.437 T::CrossAccountId,438 /// Id for which the approval was granted.439 T::CrossAccountId,440 /// Amount of token pieces transfered. Always 1 for NFT.441 u128,442 ),443444 /// The colletion property has been added or edited.445 CollectionPropertySet(446 /// Id of collection to which property has been set.447 CollectionId,448 /// The property that was set.449 PropertyKey,450 ),451452 /// The property has been deleted.453 CollectionPropertyDeleted(454 /// Id of collection to which property has been deleted.455 CollectionId,456 /// The property that was deleted.457 PropertyKey,458 ),459460 /// The token property has been added or edited.461 TokenPropertySet(462 /// Identifier of the collection whose token has the property set.463 CollectionId,464 /// The token for which the property was set.465 TokenId,466 /// The property that was set.467 PropertyKey,468 ),469470 /// The token property has been deleted.471 TokenPropertyDeleted(472 /// Identifier of the collection whose token has the property deleted.473 CollectionId,474 /// The token for which the property was deleted.475 TokenId,476 /// The property that was deleted.477 PropertyKey,478 ),479480 /// The token property permission of a collection has been set.481 PropertyPermissionSet(482 /// ID of collection to which property permission has been set.483 CollectionId,484 /// The property permission that was set.485 PropertyKey,486 ),487 }488489 #[pallet::error]490 pub enum Error<T> {491 /// This collection does not exist.492 CollectionNotFound,493 /// Sender parameter and item owner must be equal.494 MustBeTokenOwner,495 /// No permission to perform action496 NoPermission,497 /// Destroying only empty collections is allowed498 CantDestroyNotEmptyCollection,499 /// Collection is not in mint mode.500 PublicMintingNotAllowed,501 /// Address is not in allow list.502 AddressNotInAllowlist,503504 /// Collection name can not be longer than 63 char.505 CollectionNameLimitExceeded,506 /// Collection description can not be longer than 255 char.507 CollectionDescriptionLimitExceeded,508 /// Token prefix can not be longer than 15 char.509 CollectionTokenPrefixLimitExceeded,510 /// Total collections bound exceeded.511 TotalCollectionsLimitExceeded,512 /// Exceeded max admin count513 CollectionAdminCountExceeded,514 /// Collection limit bounds per collection exceeded515 CollectionLimitBoundsExceeded,516 /// Tried to enable permissions which are only permitted to be disabled517 OwnerPermissionsCantBeReverted,518 /// Collection settings not allowing items transferring519 TransferNotAllowed,520 /// Account token limit exceeded per collection521 AccountTokenLimitExceeded,522 /// Collection token limit exceeded523 CollectionTokenLimitExceeded,524 /// Metadata flag frozen525 MetadataFlagFrozen,526527 /// Item does not exist528 TokenNotFound,529 /// Item is balance not enough530 TokenValueTooLow,531 /// Requested value is more than the approved532 ApprovedValueTooLow,533 /// Tried to approve more than owned534 CantApproveMoreThanOwned,535536 /// Can't transfer tokens to ethereum zero address537 AddressIsZero,538 /// Target collection doesn't support this operation539 UnsupportedOperation,540541 /// Insufficient funds to perform an action542 NotSufficientFounds,543544 /// User does not satisfy the nesting rule545 UserIsNotAllowedToNest,546 /// Only tokens from specific collections may nest tokens under this one547 SourceCollectionIsNotAllowedToNest,548549 /// Tried to store more data than allowed in collection field550 CollectionFieldSizeExceeded,551552 /// Tried to store more property data than allowed553 NoSpaceForProperty,554555 /// Tried to store more property keys than allowed556 PropertyLimitReached,557558 /// Property key is too long559 PropertyKeyIsTooLong,560561 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed562 InvalidCharacterInPropertyKey,563564 /// Empty property keys are forbidden565 EmptyPropertyKey,566567 /// Tried to access an external collection with an internal API568 CollectionIsExternal,569570 /// Tried to access an internal collection with an external API571 CollectionIsInternal,572 }573574 /// Storage of the count of created collections. Essentially contains the last collection ID.575 #[pallet::storage]576 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;577578 /// Storage of the count of deleted collections.579 #[pallet::storage]580 pub type DestroyedCollectionCount<T> =581 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;582583 /// Storage of collection info.584 #[pallet::storage]585 pub type CollectionById<T> = StorageMap<586 Hasher = Blake2_128Concat,587 Key = CollectionId,588 Value = Collection<<T as frame_system::Config>::AccountId>,589 QueryKind = OptionQuery,590 >;591592 /// Storage of collection properties.593 #[pallet::storage]594 #[pallet::getter(fn collection_properties)]595 pub type CollectionProperties<T> = StorageMap<596 Hasher = Blake2_128Concat,597 Key = CollectionId,598 Value = Properties,599 QueryKind = ValueQuery,600 OnEmpty = up_data_structs::CollectionProperties,601 >;602603 /// Storage of token property permissions of a collection.604 #[pallet::storage]605 #[pallet::getter(fn property_permissions)]606 pub type CollectionPropertyPermissions<T> = StorageMap<607 Hasher = Blake2_128Concat,608 Key = CollectionId,609 Value = PropertiesPermissionMap,610 QueryKind = ValueQuery,611 >;612613 /// Storage of the amount of collection admins.614 #[pallet::storage]615 pub type AdminAmount<T> = StorageMap<616 Hasher = Blake2_128Concat,617 Key = CollectionId,618 Value = u32,619 QueryKind = ValueQuery,620 >;621622 /// List of collection admins.623 #[pallet::storage]624 pub type IsAdmin<T: Config> = StorageNMap<625 Key = (626 Key<Blake2_128Concat, CollectionId>,627 Key<Blake2_128Concat, T::CrossAccountId>,628 ),629 Value = bool,630 QueryKind = ValueQuery,631 >;632633 /// Allowlisted collection users.634 #[pallet::storage]635 pub type Allowlist<T: Config> = StorageNMap<636 Key = (637 Key<Blake2_128Concat, CollectionId>,638 Key<Blake2_128Concat, T::CrossAccountId>,639 ),640 Value = bool,641 QueryKind = ValueQuery,642 >;643644 /// Not used by code, exists only to provide some types to metadata.645 #[pallet::storage]646 pub type DummyStorageValue<T: Config> = StorageValue<647 Value = (648 CollectionStats,649 CollectionId,650 TokenId,651 TokenChild,652 PhantomType<(653 TokenData<T::CrossAccountId>,654 RpcCollection<T::AccountId>,655 // RMRK656 RmrkCollectionInfo<T::AccountId>,657 RmrkInstanceInfo<T::AccountId>,658 RmrkResourceInfo,659 RmrkPropertyInfo,660 RmrkBaseInfo<T::AccountId>,661 RmrkPartType,662 RmrkBoundedTheme,663 RmrkNftChild,664 )>,665 ),666 QueryKind = OptionQuery,667 >;668669 #[pallet::hooks]670 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {671 fn on_runtime_upgrade() -> Weight {672 StorageVersion::new(1).put::<Pallet<T>>();673674 0675 }676 }677}678679impl<T: Config> Pallet<T> {680 /// Enshure that receiver address is correct.681 ///682 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.683 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {684 ensure!(685 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,686 <Error<T>>::AddressIsZero687 );688 Ok(())689 }690691 /// Get a vector of collection admins.692 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {693 <IsAdmin<T>>::iter_prefix((collection,))694 .map(|(a, _)| a)695 .collect()696 }697698 /// Get a vector of users allowed to mint tokens.699 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {700 <Allowlist<T>>::iter_prefix((collection,))701 .map(|(a, _)| a)702 .collect()703 }704705 /// Is `user` allowed to mint token in `collection`.706 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {707 <Allowlist<T>>::get((collection, user))708 }709710 /// Get statistics of collections.711 pub fn collection_stats() -> CollectionStats {712 let created = <CreatedCollectionCount<T>>::get();713 let destroyed = <DestroyedCollectionCount<T>>::get();714 CollectionStats {715 created: created.0,716 destroyed: destroyed.0,717 alive: created.0 - destroyed.0,718 }719 }720721 /// Get the effective limits for the collection.722 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {723 let collection = <CollectionById<T>>::get(collection);724 if collection.is_none() {725 return None;726 }727728 let collection = collection.unwrap();729 let limits = collection.limits;730 let effective_limits = CollectionLimits {731 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),732 sponsored_data_size: Some(limits.sponsored_data_size()),733 sponsored_data_rate_limit: Some(734 limits735 .sponsored_data_rate_limit736 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),737 ),738 token_limit: Some(limits.token_limit()),739 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(740 match collection.mode {741 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,742 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,743 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,744 },745 )),746 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),747 owner_can_transfer: Some(limits.owner_can_transfer()),748 owner_can_destroy: Some(limits.owner_can_destroy()),749 transfers_enabled: Some(limits.transfers_enabled()),750 };751752 Some(effective_limits)753 }754755 /// Returns information about the `collection` adapted for rpc.756 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {757 let Collection {758 name,759 description,760 owner,761 mode,762 token_prefix,763 sponsorship,764 limits,765 permissions,766 external_collection,767 } = <CollectionById<T>>::get(collection)?;768769 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)770 .into_iter()771 .map(|(key, permission)| PropertyKeyPermission { key, permission })772 .collect();773774 let properties = <CollectionProperties<T>>::get(collection)775 .into_iter()776 .map(|(key, value)| Property { key, value })777 .collect();778779 let permissions = CollectionPermissions {780 access: Some(permissions.access()),781 mint_mode: Some(permissions.mint_mode()),782 nesting: Some(permissions.nesting().clone()),783 };784785 Some(RpcCollection {786 name: name.into_inner(),787 description: description.into_inner(),788 owner,789 mode,790 token_prefix: token_prefix.into_inner(),791 sponsorship,792 limits,793 permissions,794 token_property_permissions,795 properties,796 read_only: external_collection,797 })798 }799}800801macro_rules! limit_default {802 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{803 $(804 if let Some($new) = $new.$field {805 let $old = $old.$field($($arg)?);806 let _ = $new;807 let _ = $old;808 $check809 } else {810 $new.$field = $old.$field811 }812 )*813 }};814}815macro_rules! limit_default_clone {816 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{817 $(818 if let Some($new) = $new.$field.clone() {819 let $old = $old.$field($($arg)?);820 let _ = $new;821 let _ = $old;822 $check823 } else {824 $new.$field = $old.$field.clone()825 }826 )*827 }};828}829830impl<T: Config> Pallet<T> {831 /// Create new collection.832 ///833 /// * `owner` - The owner of the collection.834 /// * `data` - Description of the created collection.835 /// * `is_external` - Marks that collection managet by not "Unique network".836 pub fn init_collection(837 owner: T::CrossAccountId,838 data: CreateCollectionData<T::AccountId>,839 is_external: bool,840 ) -> Result<CollectionId, DispatchError> {841 {842 ensure!(843 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,844 Error::<T>::CollectionTokenPrefixLimitExceeded845 );846 }847848 let created_count = <CreatedCollectionCount<T>>::get()849 .0850 .checked_add(1)851 .ok_or(ArithmeticError::Overflow)?;852 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;853 let id = CollectionId(created_count);854855 // bound Total number of collections856 ensure!(857 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,858 <Error<T>>::TotalCollectionsLimitExceeded859 );860861 // =========862863 let collection = Collection {864 owner: owner.as_sub().clone(),865 name: data.name,866 mode: data.mode.clone(),867 description: data.description,868 token_prefix: data.token_prefix,869 sponsorship: data870 .pending_sponsor871 .map(SponsorshipState::Unconfirmed)872 .unwrap_or_default(),873 limits: data874 .limits875 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))876 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,877 permissions: data878 .permissions879 .map(|permissions| {880 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)881 })882 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,883 external_collection: is_external,884 };885886 let mut collection_properties = up_data_structs::CollectionProperties::get();887 collection_properties888 .try_set_from_iter(data.properties.into_iter())889 .map_err(<Error<T>>::from)?;890891 CollectionProperties::<T>::insert(id, collection_properties);892893 let mut token_props_permissions = PropertiesPermissionMap::new();894 token_props_permissions895 .try_set_from_iter(data.token_property_permissions.into_iter())896 .map_err(<Error<T>>::from)?;897898 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);899900 // Take a (non-refundable) deposit of collection creation901 {902 let mut imbalance =903 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();904 imbalance.subsume(905 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(906 &T::TreasuryAccountId::get(),907 T::CollectionCreationPrice::get(),908 ),909 );910 <T as Config>::Currency::settle(911 owner.as_sub(),912 imbalance,913 WithdrawReasons::TRANSFER,914 ExistenceRequirement::KeepAlive,915 )916 .map_err(|_| Error::<T>::NotSufficientFounds)?;917 }918919 <CreatedCollectionCount<T>>::put(created_count);920 <Pallet<T>>::deposit_event(Event::CollectionCreated(921 id,922 data.mode.id(),923 owner.as_sub().clone(),924 ));925 <PalletEvm<T>>::deposit_log(926 erc::CollectionHelpersEvents::CollectionCreated {927 owner: *owner.as_eth(),928 collection_id: eth::collection_id_to_address(id),929 }930 .to_log(T::ContractAddress::get()),931 );932 <CollectionById<T>>::insert(id, collection);933 Ok(id)934 }935936 /// Destroy collection.937 ///938 /// * `collection` - Collection handler.939 /// * `sender` - The owner or administrator of the collection.940 pub fn destroy_collection(941 collection: CollectionHandle<T>,942 sender: &T::CrossAccountId,943 ) -> DispatchResult {944 ensure!(945 collection.limits.owner_can_destroy(),946 <Error<T>>::NoPermission,947 );948 collection.check_is_owner(sender)?;949950 let destroyed_collections = <DestroyedCollectionCount<T>>::get()951 .0952 .checked_add(1)953 .ok_or(ArithmeticError::Overflow)?;954955 // =========956957 <DestroyedCollectionCount<T>>::put(destroyed_collections);958 <CollectionById<T>>::remove(collection.id);959 <AdminAmount<T>>::remove(collection.id);960 <IsAdmin<T>>::remove_prefix((collection.id,), None);961 <Allowlist<T>>::remove_prefix((collection.id,), None);962 <CollectionProperties<T>>::remove(collection.id);963964 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));965 Ok(())966 }967968 /// Set collection property.969 ///970 /// * `collection` - Collection handler.971 /// * `sender` - The owner or administrator of the collection.972 /// * `property` - The property to set.973 pub fn set_collection_property(974 collection: &CollectionHandle<T>,975 sender: &T::CrossAccountId,976 property: Property,977 ) -> DispatchResult {978 collection.check_is_owner_or_admin(sender)?;979980 CollectionProperties::<T>::try_mutate(collection.id, |properties| {981 let property = property.clone();982 properties.try_set(property.key, property.value)983 })984 .map_err(<Error<T>>::from)?;985986 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));987988 Ok(())989 }990991 /// Set scouped collection property.992 ///993 /// * `collection_id` - ID of the collection for which the property is being set.994 /// * `scope` - Property scope.995 /// * `property` - The property to set.996 pub fn set_scoped_collection_property(997 collection_id: CollectionId,998 scope: PropertyScope,999 property: Property,1000 ) -> DispatchResult {1001 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1002 properties.try_scoped_set(scope, property.key, property.value)1003 })1004 .map_err(<Error<T>>::from)?;10051006 Ok(())1007 }10081009 /// Set scouped collection properties.1010 ///1011 /// * `collection_id` - ID of the collection for which the properties is being set.1012 /// * `scope` - Property scope.1013 /// * `properties` - The properties to set.1014 pub fn set_scoped_collection_properties(1015 collection_id: CollectionId,1016 scope: PropertyScope,1017 properties: impl Iterator<Item = Property>,1018 ) -> DispatchResult {1019 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1020 stored_properties.try_scoped_set_from_iter(scope, properties)1021 })1022 .map_err(<Error<T>>::from)?;10231024 Ok(())1025 }10261027 /// Set collection properties.1028 ///1029 /// * `collection` - Collection handler.1030 /// * `sender` - The owner or administrator of the collection.1031 /// * `properties` - The properties to set.1032 #[transactional]1033 pub fn set_collection_properties(1034 collection: &CollectionHandle<T>,1035 sender: &T::CrossAccountId,1036 properties: Vec<Property>,1037 ) -> DispatchResult {1038 for property in properties {1039 Self::set_collection_property(collection, sender, property)?;1040 }10411042 Ok(())1043 }10441045 /// Delete collection property.1046 ///1047 /// * `collection` - Collection handler.1048 /// * `sender` - The owner or administrator of the collection.1049 /// * `property` - The property to delete.1050 pub fn delete_collection_property(1051 collection: &CollectionHandle<T>,1052 sender: &T::CrossAccountId,1053 property_key: PropertyKey,1054 ) -> DispatchResult {1055 collection.check_is_owner_or_admin(sender)?;10561057 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1058 properties.remove(&property_key)1059 })1060 .map_err(<Error<T>>::from)?;10611062 Self::deposit_event(Event::CollectionPropertyDeleted(1063 collection.id,1064 property_key,1065 ));10661067 Ok(())1068 }10691070 /// Delete collection properties.1071 ///1072 /// * `collection` - Collection handler.1073 /// * `sender` - The owner or administrator of the collection.1074 /// * `properties` - The properties to delete.1075 #[transactional]1076 pub fn delete_collection_properties(1077 collection: &CollectionHandle<T>,1078 sender: &T::CrossAccountId,1079 property_keys: Vec<PropertyKey>,1080 ) -> DispatchResult {1081 for key in property_keys {1082 Self::delete_collection_property(collection, sender, key)?;1083 }10841085 Ok(())1086 }10871088 /// Set collection propetry permission without any checks.1089 ///1090 /// Used for migrations.1091 ///1092 /// * `collection` - Collection handler.1093 /// * `property_permissions` - Property permissions.1094 pub fn set_property_permission_unchecked(1095 collection: CollectionId,1096 property_permission: PropertyKeyPermission,1097 ) -> DispatchResult {1098 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1099 permissions.try_set(property_permission.key, property_permission.permission)1100 })1101 .map_err(<Error<T>>::from)?;1102 Ok(())1103 }11041105 /// Set collection property permission.1106 ///1107 /// * `collection` - Collection handler.1108 /// * `sender` - The owner or administrator of the collection.1109 /// * `property_permission` - Property permission.1110 pub fn set_property_permission(1111 collection: &CollectionHandle<T>,1112 sender: &T::CrossAccountId,1113 property_permission: PropertyKeyPermission,1114 ) -> DispatchResult {1115 Self::set_scoped_property_permission(1116 collection,1117 sender,1118 PropertyScope::None,1119 property_permission,1120 )1121 }11221123 /// Set collection property permission with scope.1124 ///1125 /// * `collection` - Collection handler.1126 /// * `sender` - The owner or administrator of the collection.1127 /// * `scope` - Property scope.1128 /// * `property_permission` - Property permission.1129 pub fn set_scoped_property_permission(1130 collection: &CollectionHandle<T>,1131 sender: &T::CrossAccountId,1132 scope: PropertyScope,1133 property_permission: PropertyKeyPermission,1134 ) -> DispatchResult {1135 collection.check_is_owner_or_admin(sender)?;11361137 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1138 let current_permission = all_permissions.get(&property_permission.key);1139 if matches![1140 current_permission,1141 Some(PropertyPermission { mutable: false, .. })1142 ] {1143 return Err(<Error<T>>::NoPermission.into());1144 }11451146 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1147 let property_permission = property_permission.clone();1148 permissions.try_scoped_set(1149 scope,1150 property_permission.key,1151 property_permission.permission,1152 )1153 })1154 .map_err(<Error<T>>::from)?;11551156 Self::deposit_event(Event::PropertyPermissionSet(1157 collection.id,1158 property_permission.key,1159 ));11601161 Ok(())1162 }11631164 /// Set token property permission.1165 ///1166 /// * `collection` - Collection handler.1167 /// * `sender` - The owner or administrator of the collection.1168 /// * `property_permissions` - Property permissions.1169 #[transactional]1170 pub fn set_token_property_permissions(1171 collection: &CollectionHandle<T>,1172 sender: &T::CrossAccountId,1173 property_permissions: Vec<PropertyKeyPermission>,1174 ) -> DispatchResult {1175 Self::set_scoped_token_property_permissions(1176 collection,1177 sender,1178 PropertyScope::None,1179 property_permissions,1180 )1181 }11821183 /// Set token property permission with scope.1184 ///1185 /// * `collection` - Collection handler.1186 /// * `sender` - The owner or administrator of the collection.1187 /// * `scope` - Property scope.1188 /// * `property_permissions` - Property permissions.1189 #[transactional]1190 pub fn set_scoped_token_property_permissions(1191 collection: &CollectionHandle<T>,1192 sender: &T::CrossAccountId,1193 scope: PropertyScope,1194 property_permissions: Vec<PropertyKeyPermission>,1195 ) -> DispatchResult {1196 for prop_pemission in property_permissions {1197 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1198 }11991200 Ok(())1201 }12021203 /// Get collection property.1204 pub fn get_collection_property(1205 collection_id: CollectionId,1206 key: &PropertyKey,1207 ) -> Option<PropertyValue> {1208 Self::collection_properties(collection_id).get(key).cloned()1209 }12101211 /// Convert byte vector to property key vector.1212 pub fn bytes_keys_to_property_keys(1213 keys: Vec<Vec<u8>>,1214 ) -> Result<Vec<PropertyKey>, DispatchError> {1215 keys.into_iter()1216 .map(|key| -> Result<PropertyKey, DispatchError> {1217 key.try_into()1218 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1219 })1220 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1221 }12221223 /// Get properties according to given keys.1224 pub fn filter_collection_properties(1225 collection_id: CollectionId,1226 keys: Option<Vec<PropertyKey>>,1227 ) -> Result<Vec<Property>, DispatchError> {1228 let properties = Self::collection_properties(collection_id);12291230 let properties = keys1231 .map(|keys| {1232 keys.into_iter()1233 .filter_map(|key| {1234 properties.get(&key).map(|value| Property {1235 key,1236 value: value.clone(),1237 })1238 })1239 .collect()1240 })1241 .unwrap_or_else(|| {1242 properties1243 .into_iter()1244 .map(|(key, value)| Property { key, value })1245 .collect()1246 });12471248 Ok(properties)1249 }12501251 /// Get property permissions according to given keys.1252 pub fn filter_property_permissions(1253 collection_id: CollectionId,1254 keys: Option<Vec<PropertyKey>>,1255 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1256 let permissions = Self::property_permissions(collection_id);12571258 let key_permissions = keys1259 .map(|keys| {1260 keys.into_iter()1261 .filter_map(|key| {1262 permissions1263 .get(&key)1264 .map(|permission| PropertyKeyPermission {1265 key,1266 permission: permission.clone(),1267 })1268 })1269 .collect()1270 })1271 .unwrap_or_else(|| {1272 permissions1273 .into_iter()1274 .map(|(key, permission)| PropertyKeyPermission { key, permission })1275 .collect()1276 });12771278 Ok(key_permissions)1279 }12801281 /// Toggle `user` participation in the `collection`'s allow list.1282 pub fn toggle_allowlist(1283 collection: &CollectionHandle<T>,1284 sender: &T::CrossAccountId,1285 user: &T::CrossAccountId,1286 allowed: bool,1287 ) -> DispatchResult {1288 collection.check_is_owner_or_admin(sender)?;12891290 // =========12911292 if allowed {1293 <Allowlist<T>>::insert((collection.id, user), true);1294 } else {1295 <Allowlist<T>>::remove((collection.id, user));1296 }12971298 Ok(())1299 }13001301 /// Toggle `user` participation in the `collection`'s admin list.1302 pub fn toggle_admin(1303 collection: &CollectionHandle<T>,1304 sender: &T::CrossAccountId,1305 user: &T::CrossAccountId,1306 admin: bool,1307 ) -> DispatchResult {1308 collection.check_is_owner(sender)?;13091310 let was_admin = <IsAdmin<T>>::get((collection.id, user));1311 if was_admin == admin {1312 return Ok(());1313 }1314 let amount = <AdminAmount<T>>::get(collection.id);13151316 if admin {1317 let amount = amount1318 .checked_add(1)1319 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1320 ensure!(1321 amount <= Self::collection_admins_limit(),1322 <Error<T>>::CollectionAdminCountExceeded,1323 );13241325 // =========13261327 <AdminAmount<T>>::insert(collection.id, amount);1328 <IsAdmin<T>>::insert((collection.id, user), true);1329 } else {1330 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1331 <IsAdmin<T>>::remove((collection.id, user));1332 }13331334 Ok(())1335 }13361337 /// Merge set fields from `new_limit` to `old_limit`.1338 pub fn clamp_limits(1339 mode: CollectionMode,1340 old_limit: &CollectionLimits,1341 mut new_limit: CollectionLimits,1342 ) -> Result<CollectionLimits, DispatchError> {1343 let limits = old_limit;1344 limit_default!(old_limit, new_limit,1345 account_token_ownership_limit => ensure!(1346 new_limit <= MAX_TOKEN_OWNERSHIP,1347 <Error<T>>::CollectionLimitBoundsExceeded,1348 ),1349 sponsored_data_size => ensure!(1350 new_limit <= CUSTOM_DATA_LIMIT,1351 <Error<T>>::CollectionLimitBoundsExceeded,1352 ),13531354 sponsored_data_rate_limit => {},1355 token_limit => ensure!(1356 old_limit >= new_limit && new_limit > 0,1357 <Error<T>>::CollectionTokenLimitExceeded1358 ),13591360 sponsor_transfer_timeout(match mode {1361 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1362 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1363 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1364 }) => ensure!(1365 new_limit <= MAX_SPONSOR_TIMEOUT,1366 <Error<T>>::CollectionLimitBoundsExceeded,1367 ),1368 sponsor_approve_timeout => {},1369 owner_can_transfer => ensure!(1370 !limits.owner_can_transfer_instaled() ||1371 old_limit || !new_limit,1372 <Error<T>>::OwnerPermissionsCantBeReverted,1373 ),1374 owner_can_destroy => ensure!(1375 old_limit || !new_limit,1376 <Error<T>>::OwnerPermissionsCantBeReverted,1377 ),1378 transfers_enabled => {},1379 );1380 Ok(new_limit)1381 }13821383 /// Merge set fields from `new_permission` to `old_permission`.1384 pub fn clamp_permissions(1385 _mode: CollectionMode,1386 old_permission: &CollectionPermissions,1387 mut new_permission: CollectionPermissions,1388 ) -> Result<CollectionPermissions, DispatchError> {1389 limit_default_clone!(old_permission, new_permission,1390 access => {},1391 mint_mode => {},1392 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1393 );1394 Ok(new_permission)1395 }1396}13971398/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1399#[macro_export]1400macro_rules! unsupported {1401 () => {1402 Err(<Error<T>>::UnsupportedOperation.into())1403 };1404}14051406/// Return weights for various worst-case operations.1407pub trait CommonWeightInfo<CrossAccountId> {1408 /// Weight of item creation.1409 fn create_item() -> Weight;14101411 /// Weight of items creation.1412 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14131414 /// Weight of items creation.1415 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14161417 /// The weight of the burning item.1418 fn burn_item() -> Weight;14191420 /// Property setting weight.1421 ///1422 /// * `amount`- The number of properties to set.1423 fn set_collection_properties(amount: u32) -> Weight;14241425 /// Collection property deletion weight.1426 ///1427 /// * `amount`- The number of properties to set.1428 fn delete_collection_properties(amount: u32) -> Weight;14291430 /// Token property setting weight.1431 ///1432 /// * `amount`- The number of properties to set.1433 fn set_token_properties(amount: u32) -> Weight;14341435 /// Token property deletion weight.1436 ///1437 /// * `amount`- The number of properties to delete.1438 fn delete_token_properties(amount: u32) -> Weight;14391440 /// Token property permissions set weight.1441 ///1442 /// * `amount`- The number of property permissions to set.1443 fn set_token_property_permissions(amount: u32) -> Weight;14441445 /// Transfer price of the token or its parts.1446 fn transfer() -> Weight;14471448 /// The price of setting the permission of the operation from another user.1449 fn approve() -> Weight;14501451 /// Transfer price from another user.1452 fn transfer_from() -> Weight;14531454 /// The price of burning a token from another user.1455 fn burn_from() -> Weight;14561457 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1458 /// whole users's balance.1459 ///1460 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1461 fn burn_recursively_self_raw() -> Weight;14621463 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1464 ///1465 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1466 fn burn_recursively_breadth_raw(amount: u32) -> Weight;14671468 /// The price of recursive burning a token.1469 ///1470 /// `max_selfs` - The maximum burning weight of the token itself.1471 /// `max_breadth` - The maximum number of nested tokens to burn.1472 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1473 Self::burn_recursively_self_raw()1474 .saturating_mul(max_selfs.max(1) as u64)1475 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1476 }14771478 /// The price of retrieving token owner1479 fn token_owner() -> Weight;1480}14811482/// Weight info extension trait for refungible pallet.1483pub trait RefungibleExtensionsWeightInfo {1484 /// Weight of token repartition.1485 fn repartition() -> Weight;1486}14871488/// Common collection operations.1489///1490/// It wraps methods in Fungible, Nonfungible and Refungible pallets1491/// and adds weight info.1492pub trait CommonCollectionOperations<T: Config> {1493 /// Create token.1494 ///1495 /// * `sender` - The user who mint the token and pays for the transaction.1496 /// * `to` - The user who will own the token.1497 /// * `data` - Token data.1498 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1499 fn create_item(1500 &self,1501 sender: T::CrossAccountId,1502 to: T::CrossAccountId,1503 data: CreateItemData,1504 nesting_budget: &dyn Budget,1505 ) -> DispatchResultWithPostInfo;15061507 /// Create multiple tokens.1508 ///1509 /// * `sender` - The user who mint the token and pays for the transaction.1510 /// * `to` - The user who will own the token.1511 /// * `data` - Token data.1512 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1513 fn create_multiple_items(1514 &self,1515 sender: T::CrossAccountId,1516 to: T::CrossAccountId,1517 data: Vec<CreateItemData>,1518 nesting_budget: &dyn Budget,1519 ) -> DispatchResultWithPostInfo;15201521 /// Create multiple tokens.1522 ///1523 /// * `sender` - The user who mint the token and pays for the transaction.1524 /// * `to` - The user who will own the token.1525 /// * `data` - Token data.1526 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1527 fn create_multiple_items_ex(1528 &self,1529 sender: T::CrossAccountId,1530 data: CreateItemExData<T::CrossAccountId>,1531 nesting_budget: &dyn Budget,1532 ) -> DispatchResultWithPostInfo;15331534 /// Burn token.1535 ///1536 /// * `sender` - The user who owns the token.1537 /// * `token` - Token id that will burned.1538 /// * `amount` - The number of parts of the token that will be burned.1539 fn burn_item(1540 &self,1541 sender: T::CrossAccountId,1542 token: TokenId,1543 amount: u128,1544 ) -> DispatchResultWithPostInfo;15451546 /// Burn token and all nested tokens recursievly.1547 ///1548 /// * `sender` - The user who owns the token.1549 /// * `token` - Token id that will burned.1550 /// * `self_budget` - The budget that can be spent on burning tokens.1551 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1552 fn burn_item_recursively(1553 &self,1554 sender: T::CrossAccountId,1555 token: TokenId,1556 self_budget: &dyn Budget,1557 breadth_budget: &dyn Budget,1558 ) -> DispatchResultWithPostInfo;15591560 /// Set collection properties.1561 ///1562 /// * `sender` - Must be either the owner of the collection or its admin.1563 /// * `properties` - Properties to be set.1564 fn set_collection_properties(1565 &self,1566 sender: T::CrossAccountId,1567 properties: Vec<Property>,1568 ) -> DispatchResultWithPostInfo;15691570 /// Delete collection properties.1571 ///1572 /// * `sender` - Must be either the owner of the collection or its admin.1573 /// * `properties` - The properties to be removed.1574 fn delete_collection_properties(1575 &self,1576 sender: &T::CrossAccountId,1577 property_keys: Vec<PropertyKey>,1578 ) -> DispatchResultWithPostInfo;15791580 /// Set token properties.1581 ///1582 /// The appropriate [`PropertyPermission`] for the token property1583 /// must be set with [`Self::set_token_property_permissions`].1584 ///1585 /// * `sender` - Must be either the owner of the token or its admin.1586 /// * `token_id` - The token for which the properties are being set.1587 /// * `properties` - Properties to be set.1588 /// * `budget` - Budget for setting properties.1589 fn set_token_properties(1590 &self,1591 sender: T::CrossAccountId,1592 token_id: TokenId,1593 properties: Vec<Property>,1594 budget: &dyn Budget,1595 ) -> DispatchResultWithPostInfo;15961597 /// Remove token properties.1598 ///1599 /// The appropriate [`PropertyPermission`] for the token property1600 /// must be set with [`Self::set_token_property_permissions`].1601 ///1602 /// * `sender` - Must be either the owner of the token or its admin.1603 /// * `token_id` - The token for which the properties are being remove.1604 /// * `property_keys` - Keys to remove corresponding properties.1605 /// * `budget` - Budget for removing properties.1606 fn delete_token_properties(1607 &self,1608 sender: T::CrossAccountId,1609 token_id: TokenId,1610 property_keys: Vec<PropertyKey>,1611 budget: &dyn Budget,1612 ) -> DispatchResultWithPostInfo;16131614 /// Set token property permissions.1615 ///1616 /// * `sender` - Must be either the owner of the token or its admin.1617 /// * `token_id` - The token for which the properties are being set.1618 /// * `property_permissions` - Property permissions to be set.1619 /// * `budget` - Budget for setting properties.1620 fn set_token_property_permissions(1621 &self,1622 sender: &T::CrossAccountId,1623 property_permissions: Vec<PropertyKeyPermission>,1624 ) -> DispatchResultWithPostInfo;16251626 /// Transfer amount of token pieces.1627 ///1628 /// * `sender` - Donor user.1629 /// * `to` - Recepient user.1630 /// * `token` - The token of which parts are being sent.1631 /// * `amount` - The number of parts of the token that will be transferred.1632 /// * `budget` - The maximum budget that can be spent on the transfer.1633 fn transfer(1634 &self,1635 sender: T::CrossAccountId,1636 to: T::CrossAccountId,1637 token: TokenId,1638 amount: u128,1639 budget: &dyn Budget,1640 ) -> DispatchResultWithPostInfo;16411642 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1643 ///1644 /// * `sender` - The user who grants access to the token.1645 /// * `spender` - The user to whom the rights are granted.1646 /// * `token` - The token to which access is granted.1647 /// * `amount` - The amount of pieces that another user can dispose of.1648 fn approve(1649 &self,1650 sender: T::CrossAccountId,1651 spender: T::CrossAccountId,1652 token: TokenId,1653 amount: u128,1654 ) -> DispatchResultWithPostInfo;16551656 /// Send parts of a token owned by another user.1657 ///1658 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1659 ///1660 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1661 /// * `from` - The user who owns the token.1662 /// * `to` - Recepient user.1663 /// * `token` - The token of which parts are being sent.1664 /// * `amount` - The number of parts of the token that will be transferred.1665 /// * `budget` - The maximum budget that can be spent on the transfer.1666 fn transfer_from(1667 &self,1668 sender: T::CrossAccountId,1669 from: T::CrossAccountId,1670 to: T::CrossAccountId,1671 token: TokenId,1672 amount: u128,1673 budget: &dyn Budget,1674 ) -> DispatchResultWithPostInfo;16751676 /// Burn parts of a token owned by another user.1677 ///1678 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1679 ///1680 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1681 /// * `from` - The user who owns the token.1682 /// * `token` - The token of which parts are being sent.1683 /// * `amount` - The number of parts of the token that will be transferred.1684 /// * `budget` - The maximum budget that can be spent on the burn.1685 fn burn_from(1686 &self,1687 sender: T::CrossAccountId,1688 from: T::CrossAccountId,1689 token: TokenId,1690 amount: u128,1691 budget: &dyn Budget,1692 ) -> DispatchResultWithPostInfo;16931694 /// Check permission to nest token.1695 ///1696 /// * `sender` - The user who initiated the check.1697 /// * `from` - The token that is checked for embedding.1698 /// * `under` - Token under which to check.1699 /// * `budget` - The maximum budget that can be spent on the check.1700 fn check_nesting(1701 &self,1702 sender: T::CrossAccountId,1703 from: (CollectionId, TokenId),1704 under: TokenId,1705 budget: &dyn Budget,1706 ) -> DispatchResult;17071708 /// Nest one token into another.1709 ///1710 /// * `under` - Token holder.1711 /// * `to_nest` - Nested token.1712 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17131714 /// Unnest token.1715 ///1716 /// * `under` - Token holder.1717 /// * `to_nest` - Token to unnest.1718 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17191720 /// Get all user tokens.1721 ///1722 /// * `account` - Account for which you need to get tokens.1723 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17241725 /// Get all the tokens in the collection.1726 fn collection_tokens(&self) -> Vec<TokenId>;17271728 /// Check if the token exists.1729 ///1730 /// * `token` - Id token to check.1731 fn token_exists(&self, token: TokenId) -> bool;17321733 /// Get the id of the last minted token.1734 fn last_token_id(&self) -> TokenId;17351736 /// Get the owner of the token.1737 ///1738 /// * `token` - The token for which you need to find out the owner.1739 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17401741 /// Returns 10 tokens owners in no particular order.1742 ///1743 /// * `token` - The token for which you need to find out the owners.1744 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17451746 /// Get the value of the token property by key.1747 ///1748 /// * `token` - Token with the property to get.1749 /// * `key` - Property name.1750 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17511752 /// Get a set of token properties by key vector.1753 ///1754 /// * `token` - Token with the property to get.1755 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1756 /// then all properties are returned.1757 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17581759 /// Amount of unique collection tokens1760 fn total_supply(&self) -> u32;17611762 /// Amount of different tokens account has.1763 ///1764 /// * `account` - The account for which need to get the balance.1765 fn account_balance(&self, account: T::CrossAccountId) -> u32;17661767 /// Amount of specific token account have.1768 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17691770 /// Amount of token pieces1771 fn total_pieces(&self, token: TokenId) -> Option<u128>;17721773 /// Get the number of parts of the token that a trusted user can manage.1774 ///1775 /// * `sender` - Trusted user.1776 /// * `spender` - Owner of the token.1777 /// * `token` - The token for which to get the value.1778 fn allowance(1779 &self,1780 sender: T::CrossAccountId,1781 spender: T::CrossAccountId,1782 token: TokenId,1783 ) -> u128;17841785 /// Get extension for RFT collection.1786 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1787}17881789/// Extension for RFT collection.1790pub trait RefungibleExtensions<T>1791where1792 T: Config,1793{1794 /// Change the number of parts of the token.1795 ///1796 /// When the value changes down, this function is equivalent to burning parts of the token.1797 ///1798 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1799 /// * `token` - The token for which you want to change the number of parts.1800 /// * `amount` - The new value of the parts of the token.1801 fn repartition(1802 &self,1803 sender: &T::CrossAccountId,1804 token: TokenId,1805 amount: u128,1806 ) -> DispatchResultWithPostInfo;1807}18081809/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1810///1811/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1812pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1813 let post_info = PostDispatchInfo {1814 actual_weight: Some(weight),1815 pays_fee: Pays::Yes,1816 };1817 match res {1818 Ok(()) => Ok(post_info),1819 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1820 }1821}18221823impl<T: Config> From<PropertiesError> for Error<T> {1824 fn from(error: PropertiesError) -> Self {1825 match error {1826 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1827 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1828 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1829 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1830 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1831 }1832 }1833}pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -103,6 +103,10 @@
// Fungible tokens can't have children
0
}
+
+ fn token_owner() -> Weight {
+ 0
+ }
}
/// Implementation of `CommonCollectionOperations` for `FungibleHandle`. It wraps FungibleHandle Pallete
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -43,7 +43,91 @@
}
}
-// Selector: 7d9262e6
+// Selector: 942e8b22
+contract ERC20 is Dummy, ERC165, ERC20Events {
+ // Selector: name() 06fdde03
+ function name() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: symbol() 95d89b41
+ function symbol() public view returns (string memory) {
+ require(false, stub_error);
+ dummy;
+ return "";
+ }
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: decimals() 313ce567
+ function decimals() public view returns (uint8) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) public view returns (uint256) {
+ require(false, stub_error);
+ owner;
+ dummy;
+ return 0;
+ }
+
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 amount
+ ) public returns (bool) {
+ require(false, stub_error);
+ from;
+ to;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address spender, uint256 amount) public returns (bool) {
+ require(false, stub_error);
+ spender;
+ amount;
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: allowance(address,address) dd62ed3e
+ function allowance(address owner, address spender)
+ public
+ view
+ returns (uint256)
+ {
+ require(false, stub_error);
+ owner;
+ spender;
+ dummy;
+ return 0;
+ }
+}
+
+// Selector: aa7d570d
contract Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -267,90 +351,24 @@
require(false, stub_error);
mode;
dummy = 0;
- }
-}
-
-// Selector: 942e8b22
-contract ERC20 is Dummy, ERC165, ERC20Events {
- // Selector: name() 06fdde03
- function name() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
}
- // Selector: symbol() 95d89b41
- function symbol() public view returns (string memory) {
- require(false, stub_error);
- dummy;
- return "";
- }
-
- // Selector: totalSupply() 18160ddd
- function totalSupply() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // Selector: decimals() 313ce567
- function decimals() public view returns (uint8) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // Selector: balanceOf(address) 70a08231
- function balanceOf(address owner) public view returns (uint256) {
- require(false, stub_error);
- owner;
- dummy;
- return 0;
- }
-
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 amount) public returns (bool) {
- require(false, stub_error);
- to;
- amount;
- dummy = 0;
- return false;
- }
-
- // Selector: transferFrom(address,address,uint256) 23b872dd
- function transferFrom(
- address from,
- address to,
- uint256 amount
- ) public returns (bool) {
+ // Check that account is the owner or admin of the collection
+ //
+ // @return "true" if account is the owner or admin
+ //
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() public returns (bool) {
require(false, stub_error);
- from;
- to;
- amount;
dummy = 0;
return false;
}
- // Selector: approve(address,uint256) 095ea7b3
- function approve(address spender, uint256 amount) public returns (bool) {
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() public returns (string memory) {
require(false, stub_error);
- spender;
- amount;
dummy = 0;
- return false;
- }
-
- // Selector: allowance(address,address) dd62ed3e
- function allowance(address owner, address spender)
- public
- view
- returns (uint256)
- {
- require(false, stub_error);
- owner;
- spender;
- dummy;
- return 0;
+ return "";
}
}
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -17,11 +17,14 @@
use super::*;
use crate::{Pallet, Config, NonfungibleHandle};
-use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, property_key, property_value};
use frame_benchmarking::{benchmarks, account};
+use pallet_common::{
+ bench_init,
+ benchmarking::{create_collection_raw, property_key, property_value},
+ CommonCollectionOperations,
+};
+use sp_std::prelude::*;
use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, budget::Unlimited};
-use pallet_common::bench_init;
const SEED: u32 = 1;
@@ -208,4 +211,13 @@
<Pallet<T>>::set_token_properties(&collection, &owner, item, props.into_iter(), false, &Unlimited)?;
let to_delete = (0..b).map(|k| property_key(k as usize)).collect::<Vec<_>>();
}: {<Pallet<T>>::delete_token_properties(&collection, &owner, item, to_delete.into_iter(), &Unlimited)?}
+
+ token_owner {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub;
+ };
+ let item = create_max_item(&collection, &owner, owner.clone())?;
+
+ }: {collection.token_owner(item)}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -118,6 +118,10 @@
<SelfWeightOf<T>>::burn_recursively_breadth_plus_self_plus_self_per_each_raw(amount)
.saturating_sub(Self::burn_recursively_self_raw().saturating_mul(amount as u64 + 1))
}
+
+ fn token_owner() -> Weight {
+ 0 //<SelfWeightOf<T>>::token_owner()
+ }
}
fn map_create_data<T: Config>(
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -784,6 +784,23 @@
<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
}
+ /// Set property permissions for the token with scope.
+ ///
+ /// Sender should be the owner or admin of token's collection.
+ pub fn set_scoped_token_property_permissions(
+ collection: &CollectionHandle<T>,
+ sender: &T::CrossAccountId,
+ scope: PropertyScope,
+ property_permissions: Vec<PropertyKeyPermission>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::set_scoped_token_property_permissions(
+ collection,
+ sender,
+ scope,
+ property_permissions,
+ )
+ }
+
/// Set property permissions for the collection.
///
/// Sender should be the owner or admin of the collection.
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -415,7 +415,7 @@
}
}
-// Selector: 7d9262e6
+// Selector: aa7d570d
contract Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -640,6 +640,24 @@
mode;
dummy = 0;
}
+
+ // Check that account is the owner or admin of the collection
+ //
+ // @return "true" if account is the owner or admin
+ //
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() public returns (bool) {
+ require(false, stub_error);
+ dummy = 0;
+ return false;
+ }
+
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() public returns (string memory) {
+ require(false, stub_error);
+ dummy = 0;
+ return "";
+ }
}
// Selector: d74d154f
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -3,7 +3,7 @@
//! Autogenerated weights for pallet_nonfungible
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-08-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
// Executed Command:
@@ -46,6 +46,7 @@
fn set_token_property_permissions(b: u32, ) -> Weight;
fn set_token_properties(b: u32, ) -> Weight;
fn delete_token_properties(b: u32, ) -> Weight;
+ fn token_owner() -> Weight;
}
/// Weights for pallet_nonfungible using the Substrate node and recommended hardware.
@@ -56,7 +57,7 @@
// Storage: Nonfungible TokenData (r:0 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (20_328_000 as Weight)
+ (20_909_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -65,9 +66,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (10_134_000 as Weight)
- // Standard Error: 3_000
- .saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
+ (12_601_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((4_920_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -77,9 +78,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items_ex(b: u32, ) -> Weight {
- (5_710_000 as Weight)
- // Standard Error: 4_000
- .saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
+ (0 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((7_734_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -93,7 +94,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_item() -> Weight {
- (28_433_000 as Weight)
+ (29_746_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -105,7 +106,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_recursively_self_raw() -> Weight {
- (34_435_000 as Weight)
+ (36_077_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -119,8 +120,8 @@
// Storage: Common CollectionById (r:1 w:0)
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_539_000
- .saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_605_000
+ .saturating_add((312_391_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(7 as Weight))
.saturating_add(T::DbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
@@ -131,14 +132,14 @@
// Storage: Nonfungible Allowance (r:1 w:0)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer() -> Weight {
- (24_376_000 as Weight)
+ (25_248_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
// Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible Allowance (r:1 w:1)
fn approve() -> Weight {
- (15_890_000 as Weight)
+ (16_321_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -147,7 +148,7 @@
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer_from() -> Weight {
- (28_634_000 as Weight)
+ (29_325_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
@@ -159,15 +160,15 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (32_201_000 as Weight)
+ (33_323_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:1)
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 57_000
- .saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 62_000
+ .saturating_add((16_222_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -175,8 +176,8 @@
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_648_000
- .saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_750_000
+ .saturating_add((304_476_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -184,11 +185,16 @@
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_632_000
- .saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_638_000
+ .saturating_add((294_096_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ fn token_owner() -> Weight {
+ (2_986_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ }
}
// For backwards compatibility and tests
@@ -198,7 +204,7 @@
// Storage: Nonfungible TokenData (r:0 w:1)
// Storage: Nonfungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (20_328_000 as Weight)
+ (20_909_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -207,9 +213,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (10_134_000 as Weight)
- // Standard Error: 3_000
- .saturating_add((4_927_000 as Weight).saturating_mul(b as Weight))
+ (12_601_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((4_920_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(b as Weight)))
@@ -219,9 +225,9 @@
// Storage: Nonfungible TokenData (r:0 w:4)
// Storage: Nonfungible Owned (r:0 w:4)
fn create_multiple_items_ex(b: u32, ) -> Weight {
- (5_710_000 as Weight)
- // Standard Error: 4_000
- .saturating_add((7_578_000 as Weight).saturating_mul(b as Weight))
+ (0 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((7_734_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -235,7 +241,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_item() -> Weight {
- (28_433_000 as Weight)
+ (29_746_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -247,7 +253,7 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_recursively_self_raw() -> Weight {
- (34_435_000 as Weight)
+ (36_077_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -261,8 +267,8 @@
// Storage: Common CollectionById (r:1 w:0)
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_539_000
- .saturating_add((304_456_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_605_000
+ .saturating_add((312_391_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(7 as Weight))
.saturating_add(RocksDbWeight::get().reads((4 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
@@ -273,14 +279,14 @@
// Storage: Nonfungible Allowance (r:1 w:0)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer() -> Weight {
- (24_376_000 as Weight)
+ (25_248_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
// Storage: Nonfungible TokenData (r:1 w:0)
// Storage: Nonfungible Allowance (r:1 w:1)
fn approve() -> Weight {
- (15_890_000 as Weight)
+ (16_321_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -289,7 +295,7 @@
// Storage: Nonfungible AccountBalance (r:2 w:2)
// Storage: Nonfungible Owned (r:0 w:2)
fn transfer_from() -> Weight {
- (28_634_000 as Weight)
+ (29_325_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
@@ -301,15 +307,15 @@
// Storage: Nonfungible Owned (r:0 w:1)
// Storage: Nonfungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (32_201_000 as Weight)
+ (33_323_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:1)
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 57_000
- .saturating_add((15_232_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 62_000
+ .saturating_add((16_222_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -317,8 +323,8 @@
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_648_000
- .saturating_add((288_654_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_750_000
+ .saturating_add((304_476_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -326,9 +332,14 @@
// Storage: Nonfungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_632_000
- .saturating_add((289_190_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_638_000
+ .saturating_add((294_096_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ fn token_owner() -> Weight {
+ (2_986_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ }
}
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -17,16 +17,19 @@
use super::*;
use crate::{Pallet, Config, RefungibleHandle};
-use sp_std::prelude::*;
-use pallet_common::benchmarking::{create_collection_raw, property_key, property_value, create_data};
+use core::convert::TryInto;
+use core::iter::IntoIterator;
use frame_benchmarking::{benchmarks, account};
+use pallet_common::{
+ bench_init,
+ benchmarking::{create_collection_raw, property_key, property_value, create_data},
+};
+use sp_core::H160;
+use sp_std::prelude::*;
use up_data_structs::{
CollectionMode, MAX_ITEMS_PER_BATCH, MAX_PROPERTIES_PER_ITEM, CUSTOM_DATA_LIMIT,
budget::Unlimited,
};
-use pallet_common::bench_init;
-use core::convert::TryInto;
-use core::iter::IntoIterator;
const SEED: u32 = 1;
@@ -44,6 +47,7 @@
properties: Default::default(),
}
}
+
fn create_max_item<T: Config>(
collection: &RefungibleHandle<T>,
sender: &T::CrossAccountId,
@@ -59,11 +63,12 @@
) -> Result<RefungibleHandle<T>, DispatchError> {
create_collection_raw(
owner,
- CollectionMode::NFT,
+ CollectionMode::ReFungible,
<Pallet<T>>::init_collection,
RefungibleHandle::cast,
)
}
+
benchmarks! {
create_item {
bench_init!{
@@ -277,4 +282,21 @@
};
let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
}: {<Pallet<T>>::repartition(&collection, &owner, item, 200)?}
+
+ set_parent_nft_unchecked {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); owner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
+
+ }: {<Pallet<T>>::set_parent_nft_unchecked(&collection, item, owner, T::CrossAccountId::from_eth(H160::default()))?}
+
+ token_owner {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner); owner: cross_sub;
+ };
+ let item = create_max_item(&collection, &sender, [(owner.clone(), 100)])?;
+ }: {<Pallet<T>>::token_owner(collection.id, item)}
}
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -148,6 +148,10 @@
// Refungible token can't have children
0
}
+
+ fn token_owner() -> Weight {
+ 0 //<SelfWeightOf<T>>::token_owner()
+ }
}
fn map_create_data<T: Config>(
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -41,8 +41,8 @@
use sp_core::H160;
use sp_std::{collections::btree_map::BTreeMap, vec::Vec, vec};
use up_data_structs::{
- CollectionId, CollectionPropertiesVec, Property, PropertyKey, PropertyKeyPermission,
- PropertyPermission, TokenId,
+ CollectionId, CollectionPropertiesVec, mapping::TokenAddressMapping, Property, PropertyKey,
+ PropertyKeyPermission, PropertyPermission, TokenId,
};
use crate::{
@@ -413,7 +413,7 @@
}
/// Returns amount of pieces of `token` that `owner` have
-fn balance<T: Config>(
+pub fn balance<T: Config>(
collection: &RefungibleHandle<T>,
token: TokenId,
owner: &T::CrossAccountId,
@@ -424,7 +424,7 @@
}
/// Throws if `owner_balance` is lower than total amount of `token` pieces
-fn ensure_single_owner<T: Config>(
+pub fn ensure_single_owner<T: Config>(
collection: &RefungibleHandle<T>,
token: TokenId,
owner_balance: u128,
@@ -788,6 +788,16 @@
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
+
+ /// Returns EVM address for refungible token
+ ///
+ /// @param token ID of the token
+ fn token_contract_address(&self, token: uint256) -> Result<address> {
+ Ok(T::EvmTokenAddressMapping::token_to_address(
+ self.id,
+ token.try_into().map_err(|_| "token id overflow")?,
+ ))
+ }
}
#[solidity_interface(
pallets/refungible/src/erc_token.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc_token.rs
+++ b/pallets/refungible/src/erc_token.rs
@@ -20,29 +20,89 @@
//! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
extern crate alloc;
+
+#[cfg(not(feature = "std"))]
+use alloc::format;
+
use core::{
char::{REPLACEMENT_CHARACTER, decode_utf16},
convert::TryInto,
ops::Deref,
};
-use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
+use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use pallet_common::{
CommonWeightInfo,
- erc::{CommonEvmHandler, PrecompileResult},
+ erc::{CommonEvmHandler, PrecompileResult, static_property::key},
+ eth::map_eth_to_id,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::{call, dispatch_to_evm, WithRecorder};
use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
+use sp_core::H160;
use sp_std::vec::Vec;
-use up_data_structs::TokenId;
+use up_data_structs::{mapping::TokenAddressMapping, PropertyScope, TokenId};
use crate::{
Allowance, Balance, common::CommonWeights, Config, Pallet, RefungibleHandle, SelfWeightOf,
- weights::WeightInfo, TotalSupply,
+ TokenProperties, TotalSupply, weights::WeightInfo,
};
pub struct RefungibleTokenHandle<T: Config>(pub RefungibleHandle<T>, pub TokenId);
+#[solidity_interface(name = "ERC1633")]
+impl<T: Config> RefungibleTokenHandle<T> {
+ fn parent_token(&self) -> Result<address> {
+ self.consume_store_reads(2)?;
+ let props = <TokenProperties<T>>::get((self.id, self.1));
+ let key = key::parent_nft();
+
+ let key_scoped = PropertyScope::Eth
+ .apply(key)
+ .expect("property key shouldn't exceed length limit");
+ let value = props.get(&key_scoped).ok_or("key not found")?;
+ Ok(H160::from_slice(value.as_slice()))
+ }
+
+ fn parent_token_id(&self) -> Result<uint256> {
+ self.consume_store_reads(2)?;
+ let props = <TokenProperties<T>>::get((self.id, self.1));
+ let key = key::parent_nft();
+
+ let key_scoped = PropertyScope::Eth
+ .apply(key)
+ .expect("property key shouldn't exceed length limit");
+ let value = props.get(&key_scoped).ok_or("key not found")?;
+ let nft_token_address = H160::from_slice(value.as_slice());
+ let nft_token_account = T::CrossAccountId::from_eth(nft_token_address);
+ let (_, token_id) = T::CrossTokenAddressMapping::address_to_token(&nft_token_account)
+ .ok_or("parent NFT should contain NFT token address")?;
+
+ Ok(token_id.into())
+ }
+}
+
+#[solidity_interface(name = "ERC1633UniqueExtensions")]
+impl<T: Config> RefungibleTokenHandle<T> {
+ #[solidity(rename_selector = "setParentNFT")]
+ #[weight(<CommonWeights<T>>::token_owner() + <SelfWeightOf<T>>::set_parent_nft_unchecked())]
+ fn set_parent_nft(
+ &mut self,
+ caller: caller,
+ collection: address,
+ nft_id: uint256,
+ ) -> Result<bool> {
+ self.consume_store_reads(1)?;
+ let caller = T::CrossAccountId::from_eth(caller);
+ let nft_collection = map_eth_to_id(&collection).ok_or("collection not found")?;
+ let nft_token = nft_id.try_into()?;
+
+ <Pallet<T>>::set_parent_nft(&self.0, self.1, caller, nft_collection, nft_token)
+ .map_err(dispatch_to_evm::<T>)?;
+
+ Ok(true)
+ }
+}
+
#[derive(ToLog)]
pub enum ERC20Events {
/// @dev This event is emitted when the amount of tokens (value) is sent
@@ -239,7 +299,10 @@
}
}
-#[solidity_interface(name = "UniqueRefungibleToken", is(ERC20, ERC20UniqueExtensions,))]
+#[solidity_interface(
+ name = "UniqueRefungibleToken",
+ is(ERC20, ERC20UniqueExtensions, ERC1633, ERC1633UniqueExtensions)
+)]
impl<T: Config> RefungibleTokenHandle<T> where T::AccountId: From<[u8; 32]> {}
generate_stubgen!(gen_impl, UniqueRefungibleTokenCall<()>, true);
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -99,8 +99,12 @@
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
use pallet_evm_coder_substrate::WithRecorder;
use pallet_common::{
- CommonCollectionOperations, Error as CommonError, Event as CommonEvent,
- eth::collection_id_to_address, Pallet as PalletCommon,
+ CollectionHandle, CommonCollectionOperations,
+ dispatch::CollectionDispatch,
+ erc::static_property::{key, property_value_from_bytes},
+ Error as CommonError,
+ eth::collection_id_to_address,
+ Event as CommonEvent, Pallet as PalletCommon,
};
use pallet_structure::Pallet as PalletStructure;
use scale_info::TypeInfo;
@@ -108,10 +112,10 @@
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};
use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};
use up_data_structs::{
- AccessMode, budget::Budget, CollectionId, CreateCollectionData, CustomDataLimit,
- mapping::TokenAddressMapping, MAX_REFUNGIBLE_PIECES, MAX_ITEMS_PER_BATCH, TokenId, Property,
+ AccessMode, budget::Budget, CollectionId, CollectionMode, CollectionPropertiesVec, CreateCollectionData, CustomDataLimit,
+ mapping::TokenAddressMapping, MAX_ITEMS_PER_BATCH, MAX_REFUNGIBLE_PIECES, Property,
PropertyKey, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
- TrySetProperty, CollectionPropertiesVec,
+ TokenId, TrySetProperty,
};
use frame_support::BoundedBTreeMap;
use derivative::Derivative;
@@ -1341,6 +1345,20 @@
<PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)
}
+ pub fn set_scoped_token_property_permissions(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ scope: PropertyScope,
+ property_permissions: Vec<PropertyKeyPermission>,
+ ) -> DispatchResult {
+ <PalletCommon<T>>::set_scoped_token_property_permissions(
+ collection,
+ sender,
+ scope,
+ property_permissions,
+ )
+ }
+
/// Returns 10 token in no particular order.
///
/// There is no direct way to get token holders in ascending order,
@@ -1362,4 +1380,68 @@
Some(res)
}
}
+
+ /// Sets the NFT token as a parent for the RFT token
+ ///
+ /// Throws if `sender` is not the owner of the NFT token.
+ /// Throws if `sender` is not the owner of all of the RFT token pieces.
+ pub fn set_parent_nft(
+ collection: &RefungibleHandle<T>,
+ rft_token_id: TokenId,
+ sender: T::CrossAccountId,
+ nft_collection: CollectionId,
+ nft_token: TokenId,
+ ) -> DispatchResult {
+ let handle = <CollectionHandle<T>>::try_get(nft_collection)?;
+ if handle.mode != CollectionMode::NFT {
+ return Err("Only NFT token could be parent to RFT".into());
+ }
+ let dispatch = T::CollectionDispatch::dispatch(handle);
+ let dispatch = dispatch.as_dyn();
+
+ let owner = dispatch.token_owner(nft_token).ok_or("owner not found")?;
+ if owner != sender {
+ return Err("Only owned token could be set as parent".into());
+ }
+
+ let nft_token_address =
+ T::CrossTokenAddressMapping::token_to_address(nft_collection, nft_token);
+
+ Self::set_parent_nft_unchecked(collection, rft_token_id, sender, nft_token_address)
+ }
+
+ /// Sets the NFT token as a parent for the RFT token
+ ///
+ /// `sender` should be the owner of the NFT token.
+ /// Throws if `sender` is not the owner of all of the RFT token pieces.
+ pub fn set_parent_nft_unchecked(
+ collection: &RefungibleHandle<T>,
+ rft_token_id: TokenId,
+ sender: T::CrossAccountId,
+ nft_token_address: T::CrossAccountId,
+ ) -> DispatchResult {
+ let owner_balance = <Balance<T>>::get((collection.id, rft_token_id, &sender));
+ let total_supply = <TotalSupply<T>>::get((collection.id, rft_token_id));
+ if total_supply != owner_balance {
+ return Err("token has multiple owners".into());
+ }
+
+ let parent_nft_property_key = key::parent_nft();
+
+ let parent_nft_property_value =
+ property_value_from_bytes(&nft_token_address.as_eth().to_fixed_bytes())
+ .expect("address should fit in value length limit");
+
+ <Pallet<T>>::set_scoped_token_property(
+ collection.id,
+ rft_token_id,
+ PropertyScope::Eth,
+ Property {
+ key: parent_nft_property_key,
+ value: parent_nft_property_value,
+ },
+ )?;
+
+ Ok(())
+ }
}
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
@@ -413,7 +413,100 @@
}
}
-// Selector: 7d9262e6
+// Selector: 7c3bef89
+contract ERC721UniqueExtensions is Dummy, ERC165 {
+ // @notice Transfer ownership of an RFT
+ // @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ // is the zero address. Throws if `tokenId` is not a valid RFT.
+ // Throws if RFT pieces have multiple owners.
+ // @param to The new owner
+ // @param tokenId The RFT to transfer
+ // @param _value Not used for an RFT
+ //
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 tokenId) public {
+ require(false, stub_error);
+ to;
+ tokenId;
+ dummy = 0;
+ }
+
+ // @notice Burns a specific ERC721 token.
+ // @dev Throws unless `msg.sender` is the current owner or an authorized
+ // operator for this RFT. Throws if `from` is not the current owner. Throws
+ // if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
+ // Throws if RFT pieces have multiple owners.
+ // @param from The current owner of the RFT
+ // @param tokenId The RFT to transfer
+ // @param _value Not used for an RFT
+ //
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) public {
+ require(false, stub_error);
+ from;
+ tokenId;
+ dummy = 0;
+ }
+
+ // @notice Returns next free RFT ID.
+ //
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+
+ // @notice Function to mint multiple tokens.
+ // @dev `tokenIds` should be an array of consecutive numbers and first number
+ // should be obtained with `nextTokenId` method
+ // @param to The new owner
+ // @param tokenIds IDs of the minted RFTs
+ //
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokenIds;
+ dummy = 0;
+ return false;
+ }
+
+ // @notice Function to mint multiple tokens with the given tokenUris.
+ // @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ // numbers and first number should be obtained with `nextTokenId` method
+ // @param to The new owner
+ // @param tokens array of pairs of token ID and token URI for minted tokens
+ //
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ to;
+ tokens;
+ dummy = 0;
+ return false;
+ }
+
+ // Returns EVM address for refungible token
+ //
+ // @param token ID of the token
+ //
+ // Selector: tokenContractAddress(uint256) ab76fac6
+ function tokenContractAddress(uint256 token) public view returns (address) {
+ require(false, stub_error);
+ token;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
+
+// Selector: aa7d570d
contract Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -636,88 +729,29 @@
function setCollectionMintMode(bool mode) public {
require(false, stub_error);
mode;
- dummy = 0;
- }
-}
-
-// Selector: d74d154f
-contract ERC721UniqueExtensions is Dummy, ERC165 {
- // @notice Transfer ownership of an RFT
- // @dev Throws unless `msg.sender` is the current owner. Throws if `to`
- // is the zero address. Throws if `tokenId` is not a valid RFT.
- // Throws if RFT pieces have multiple owners.
- // @param to The new owner
- // @param tokenId The RFT to transfer
- // @param _value Not used for an RFT
- //
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 tokenId) public {
- require(false, stub_error);
- to;
- tokenId;
- dummy = 0;
- }
-
- // @notice Burns a specific ERC721 token.
- // @dev Throws unless `msg.sender` is the current owner or an authorized
- // operator for this RFT. Throws if `from` is not the current owner. Throws
- // if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
- // Throws if RFT pieces have multiple owners.
- // @param from The current owner of the RFT
- // @param tokenId The RFT to transfer
- // @param _value Not used for an RFT
- //
- // Selector: burnFrom(address,uint256) 79cc6790
- function burnFrom(address from, uint256 tokenId) public {
- require(false, stub_error);
- from;
- tokenId;
dummy = 0;
}
- // @notice Returns next free RFT ID.
+ // Check that account is the owner or admin of the collection
//
- // Selector: nextTokenId() 75794a3c
- function nextTokenId() public view returns (uint256) {
- require(false, stub_error);
- dummy;
- return 0;
- }
-
- // @notice Function to mint multiple tokens.
- // @dev `tokenIds` should be an array of consecutive numbers and first number
- // should be obtained with `nextTokenId` method
- // @param to The new owner
- // @param tokenIds IDs of the minted RFTs
+ // @return "true" if account is the owner or admin
//
- // Selector: mintBulk(address,uint256[]) 44a9945e
- function mintBulk(address to, uint256[] memory tokenIds)
- public
- returns (bool)
- {
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() public returns (bool) {
require(false, stub_error);
- to;
- tokenIds;
dummy = 0;
return false;
}
- // @notice Function to mint multiple tokens with the given tokenUris.
- // @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
- // numbers and first number should be obtained with `nextTokenId` method
- // @param to The new owner
- // @param tokens array of pairs of token ID and token URI for minted tokens
+ // Returns collection type
//
- // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
- public
- returns (bool)
- {
+ // @return `Fungible` or `NFT` or `ReFungible`
+ //
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() public returns (string memory) {
require(false, stub_error);
- to;
- tokens;
dummy = 0;
- return false;
+ return "";
}
}
pallets/refungible/src/stubs/UniqueRefungibleToken.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungibleToken.sol
@@ -31,6 +31,38 @@
);
}
+// Selector: 042f1106
+contract ERC1633UniqueExtensions is Dummy, ERC165 {
+ // Selector: setParentNFT(address,uint256) 042f1106
+ function setParentNFT(address collection, uint256 nftId)
+ public
+ returns (bool)
+ {
+ require(false, stub_error);
+ collection;
+ nftId;
+ dummy = 0;
+ return false;
+ }
+}
+
+// Selector: 5755c3f2
+contract ERC1633 is Dummy, ERC165 {
+ // Selector: parentToken() 80a54001
+ function parentToken() public view returns (address) {
+ require(false, stub_error);
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+
+ // Selector: parentTokenId() d7f083f3
+ function parentTokenId() public view returns (uint256) {
+ require(false, stub_error);
+ dummy;
+ return 0;
+ }
+}
+
// Selector: 942e8b22
contract ERC20 is Dummy, ERC165, ERC20Events {
// @return the name of the token.
@@ -178,4 +210,11 @@
}
}
-contract UniqueRefungibleToken is Dummy, ERC165, ERC20, ERC20UniqueExtensions {}
+contract UniqueRefungibleToken is
+ Dummy,
+ ERC165,
+ ERC20,
+ ERC20UniqueExtensions,
+ ERC1633,
+ ERC1633UniqueExtensions
+{}
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -3,7 +3,7 @@
//! Autogenerated weights for pallet_refungible
//!
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-07-20, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-08-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
// Executed Command:
@@ -53,6 +53,8 @@
fn set_token_properties(b: u32, ) -> Weight;
fn delete_token_properties(b: u32, ) -> Weight;
fn repartition_item() -> Weight;
+ fn set_parent_nft_unchecked() -> Weight;
+ fn token_owner() -> Weight;
}
/// Weights for pallet_refungible using the Substrate node and recommended hardware.
@@ -65,7 +67,7 @@
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (21_310_000 as Weight)
+ (25_197_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
@@ -76,9 +78,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (9_552_000 as Weight)
+ (10_852_000 as Weight)
// Standard Error: 2_000
- .saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((8_087_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -90,9 +92,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
- (4_857_000 as Weight)
+ (9_978_000 as Weight)
// Standard Error: 2_000
- .saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((10_848_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
@@ -105,9 +107,9 @@
// Storage: Refungible Balance (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
- (11_335_000 as Weight)
+ (15_419_000 as Weight)
// Standard Error: 2_000
- .saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((7_813_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
@@ -118,7 +120,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn burn_item_partial() -> Weight {
- (21_239_000 as Weight)
+ (25_578_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -130,13 +132,13 @@
// Storage: Refungible Owned (r:0 w:1)
// Storage: Refungible TokenProperties (r:0 w:1)
fn burn_item_fully() -> Weight {
- (29_426_000 as Weight)
+ (33_593_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
- (17_743_000 as Weight)
+ (21_049_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
@@ -144,7 +146,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_creating() -> Weight {
- (20_699_000 as Weight)
+ (24_646_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -152,7 +154,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_removing() -> Weight {
- (22_833_000 as Weight)
+ (26_570_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(4 as Weight))
}
@@ -160,21 +162,21 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_creating_removing() -> Weight {
- (24_936_000 as Weight)
+ (28_906_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(6 as Weight))
}
// Storage: Refungible Balance (r:1 w:0)
// Storage: Refungible Allowance (r:0 w:1)
fn approve() -> Weight {
- (13_446_000 as Weight)
+ (16_451_000 as Weight)
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible Balance (r:2 w:2)
fn transfer_from_normal() -> Weight {
- (24_777_000 as Weight)
+ (29_545_000 as Weight)
.saturating_add(T::DbWeight::get().reads(3 as Weight))
.saturating_add(T::DbWeight::get().writes(3 as Weight))
}
@@ -183,7 +185,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_creating() -> Weight {
- (28_483_000 as Weight)
+ (33_392_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -192,7 +194,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_removing() -> Weight {
- (29_896_000 as Weight)
+ (35_446_000 as Weight)
.saturating_add(T::DbWeight::get().reads(4 as Weight))
.saturating_add(T::DbWeight::get().writes(5 as Weight))
}
@@ -201,7 +203,7 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_from_creating_removing() -> Weight {
- (32_070_000 as Weight)
+ (37_762_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(7 as Weight))
}
@@ -214,15 +216,15 @@
// Storage: Refungible Owned (r:0 w:1)
// Storage: Refungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (36_789_000 as Weight)
+ (42_620_000 as Weight)
.saturating_add(T::DbWeight::get().reads(5 as Weight))
.saturating_add(T::DbWeight::get().writes(8 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:1)
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 62_000
- .saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 65_000
+ .saturating_add((16_513_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(1 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -230,8 +232,8 @@
// Storage: Refungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_668_000
- .saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_583_000
+ .saturating_add((291_392_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
@@ -239,18 +241,31 @@
// Storage: Refungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_619_000
- .saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_699_000
+ .saturating_add((293_270_000 as Weight).saturating_mul(b as Weight))
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(1 as Weight))
}
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
fn repartition_item() -> Weight {
- (8_325_000 as Weight)
+ (19_206_000 as Weight)
.saturating_add(T::DbWeight::get().reads(2 as Weight))
.saturating_add(T::DbWeight::get().writes(2 as Weight))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible TotalSupply (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn set_parent_nft_unchecked() -> Weight {
+ (10_189_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(3 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:0)
+ fn token_owner() -> Weight {
+ (8_205_000 as Weight)
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ }
}
// For backwards compatibility and tests
@@ -262,7 +277,7 @@
// Storage: Refungible TokenData (r:0 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn create_item() -> Weight {
- (21_310_000 as Weight)
+ (25_197_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
@@ -273,9 +288,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items(b: u32, ) -> Weight {
- (9_552_000 as Weight)
+ (10_852_000 as Weight)
// Standard Error: 2_000
- .saturating_add((7_056_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((8_087_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(b as Weight)))
@@ -287,9 +302,9 @@
// Storage: Refungible TokenData (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_items(b: u32, ) -> Weight {
- (4_857_000 as Weight)
+ (9_978_000 as Weight)
// Standard Error: 2_000
- .saturating_add((9_838_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((10_848_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
@@ -302,9 +317,9 @@
// Storage: Refungible Balance (r:0 w:4)
// Storage: Refungible Owned (r:0 w:4)
fn create_multiple_items_ex_multiple_owners(b: u32, ) -> Weight {
- (11_335_000 as Weight)
+ (15_419_000 as Weight)
// Standard Error: 2_000
- .saturating_add((6_784_000 as Weight).saturating_mul(b as Weight))
+ .saturating_add((7_813_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(b as Weight)))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
@@ -315,7 +330,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn burn_item_partial() -> Weight {
- (21_239_000 as Weight)
+ (25_578_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -327,13 +342,13 @@
// Storage: Refungible Owned (r:0 w:1)
// Storage: Refungible TokenProperties (r:0 w:1)
fn burn_item_fully() -> Weight {
- (29_426_000 as Weight)
+ (33_593_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
// Storage: Refungible Balance (r:2 w:2)
fn transfer_normal() -> Weight {
- (17_743_000 as Weight)
+ (21_049_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
@@ -341,7 +356,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_creating() -> Weight {
- (20_699_000 as Weight)
+ (24_646_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -349,7 +364,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_removing() -> Weight {
- (22_833_000 as Weight)
+ (26_570_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(4 as Weight))
}
@@ -357,21 +372,21 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_creating_removing() -> Weight {
- (24_936_000 as Weight)
+ (28_906_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(6 as Weight))
}
// Storage: Refungible Balance (r:1 w:0)
// Storage: Refungible Allowance (r:0 w:1)
fn approve() -> Weight {
- (13_446_000 as Weight)
+ (16_451_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible Balance (r:2 w:2)
fn transfer_from_normal() -> Weight {
- (24_777_000 as Weight)
+ (29_545_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(3 as Weight))
.saturating_add(RocksDbWeight::get().writes(3 as Weight))
}
@@ -380,7 +395,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_creating() -> Weight {
- (28_483_000 as Weight)
+ (33_392_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -389,7 +404,7 @@
// Storage: Refungible AccountBalance (r:1 w:1)
// Storage: Refungible Owned (r:0 w:1)
fn transfer_from_removing() -> Weight {
- (29_896_000 as Weight)
+ (35_446_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(4 as Weight))
.saturating_add(RocksDbWeight::get().writes(5 as Weight))
}
@@ -398,7 +413,7 @@
// Storage: Refungible AccountBalance (r:2 w:2)
// Storage: Refungible Owned (r:0 w:2)
fn transfer_from_creating_removing() -> Weight {
- (32_070_000 as Weight)
+ (37_762_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(7 as Weight))
}
@@ -411,15 +426,15 @@
// Storage: Refungible Owned (r:0 w:1)
// Storage: Refungible TokenProperties (r:0 w:1)
fn burn_from() -> Weight {
- (36_789_000 as Weight)
+ (42_620_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(5 as Weight))
.saturating_add(RocksDbWeight::get().writes(8 as Weight))
}
// Storage: Common CollectionPropertyPermissions (r:1 w:1)
fn set_token_property_permissions(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 62_000
- .saturating_add((15_803_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 65_000
+ .saturating_add((16_513_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(1 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -427,8 +442,8 @@
// Storage: Refungible TokenProperties (r:1 w:1)
fn set_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_668_000
- .saturating_add((302_308_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_583_000
+ .saturating_add((291_392_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
@@ -436,16 +451,29 @@
// Storage: Refungible TokenProperties (r:1 w:1)
fn delete_token_properties(b: u32, ) -> Weight {
(0 as Weight)
- // Standard Error: 1_619_000
- .saturating_add((294_574_000 as Weight).saturating_mul(b as Weight))
+ // Standard Error: 1_699_000
+ .saturating_add((293_270_000 as Weight).saturating_mul(b as Weight))
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(1 as Weight))
}
// Storage: Refungible TotalSupply (r:1 w:1)
// Storage: Refungible Balance (r:1 w:1)
fn repartition_item() -> Weight {
- (8_325_000 as Weight)
+ (19_206_000 as Weight)
.saturating_add(RocksDbWeight::get().reads(2 as Weight))
.saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible TotalSupply (r:1 w:0)
+ // Storage: Refungible TokenProperties (r:1 w:1)
+ fn set_parent_nft_unchecked() -> Weight {
+ (10_189_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(3 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Refungible Balance (r:2 w:0)
+ fn token_owner() -> Weight {
+ (8_205_000 as Weight)
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ }
}
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -17,26 +17,29 @@
//! Implementation of CollectionHelpers contract.
use core::marker::PhantomData;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
use ethereum as _;
-use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, PrecompileHandle};
-use up_data_structs::{
- CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
- CollectionMode, PropertyValue,
-};
+use evm_coder::{execution::*, generate_stubgen, solidity_interface, solidity, weight, types::*};
use frame_support::traits::Get;
use pallet_common::{
- CollectionById,
+ CollectionById, CollectionHandle,
+ dispatch::CollectionDispatch,
erc::{
+ CollectionHelpersEvents,
static_property::{key, value as property_value},
- CollectionHelpersEvents,
},
- dispatch::CollectionDispatch,
+ Pallet as PalletCommon,
};
-use crate::{SelfWeightOf, Config, weights::WeightInfo};
+use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
+use pallet_evm::{account::CrossAccountId, OnMethodCall, PrecompileHandle, PrecompileResult};
+use pallet_evm_coder_substrate::dispatch_to_evm;
+use up_data_structs::{
+ CollectionName, CollectionDescription, CollectionTokenPrefix, CreateCollectionData,
+ CollectionMode, PropertyKeyPermission, PropertyPermission, PropertyScope, PropertyValue,
+};
+
+use crate::{Config, SelfWeightOf, weights::WeightInfo};
-use sp_std::vec::Vec;
+use sp_std::{vec, vec::Vec};
use alloc::format;
/// See [`CollectionHelpersCall`]
@@ -151,6 +154,54 @@
Ok(data)
}
+fn parent_nft_property_permissions() -> PropertyKeyPermission {
+ PropertyKeyPermission {
+ key: key::parent_nft(),
+ permission: PropertyPermission {
+ mutable: false,
+ collection_admin: false,
+ token_owner: true,
+ },
+ }
+}
+
+fn create_refungible_collection_internal<
+ T: Config + pallet_nonfungible::Config + pallet_refungible::Config,
+>(
+ caller: caller,
+ name: string,
+ description: string,
+ token_prefix: string,
+ base_uri: string,
+ add_properties: bool,
+) -> Result<address> {
+ let (caller, name, description, token_prefix, base_uri_value) =
+ convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
+ let data = make_data::<T>(
+ name,
+ CollectionMode::ReFungible,
+ description,
+ token_prefix,
+ base_uri_value,
+ add_properties,
+ )?;
+
+ let collection_id = T::CollectionDispatch::create(caller.clone(), data)
+ .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+
+ let handle = <CollectionHandle<T>>::try_get(collection_id).map_err(dispatch_to_evm::<T>)?;
+ <PalletCommon<T>>::set_scoped_token_property_permissions(
+ &handle,
+ &caller,
+ PropertyScope::Eth,
+ vec![parent_nft_property_permissions()],
+ )
+ .map_err(dispatch_to_evm::<T>)?;
+
+ let address = pallet_common::eth::collection_id_to_address(collection_id);
+ Ok(address)
+}
+
/// @title Contract, which allows users to operate with collections
#[solidity_interface(name = "CollectionHelpers", events(CollectionHelpersEvents))]
impl<T> EvmCollectionHelpers<T>
@@ -216,27 +267,20 @@
#[weight(<SelfWeightOf<T>>::create_collection())]
fn create_refungible_collection(
- &self,
+ &mut self,
caller: caller,
name: string,
description: string,
token_prefix: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, _base_uri) =
- convert_data::<T>(caller, name, description, token_prefix, "".into())?;
- let data = make_data::<T>(
+ create_refungible_collection_internal::<T>(
+ caller,
name,
- CollectionMode::ReFungible,
description,
token_prefix,
Default::default(),
false,
- )?;
- let collection_id = T::CollectionDispatch::create(caller, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
- let address = pallet_common::eth::collection_id_to_address(collection_id);
- Ok(address)
+ )
}
#[weight(<SelfWeightOf<T>>::create_collection())]
@@ -249,21 +293,14 @@
token_prefix: string,
base_uri: string,
) -> Result<address> {
- let (caller, name, description, token_prefix, base_uri_value) =
- convert_data::<T>(caller, name, description, token_prefix, base_uri)?;
- let data = make_data::<T>(
+ create_refungible_collection_internal::<T>(
+ caller,
name,
- CollectionMode::NFT,
description,
token_prefix,
- base_uri_value,
+ base_uri,
true,
- )?;
- let collection_id = T::CollectionDispatch::create(caller, data)
- .map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
-
- let address = pallet_common::eth::collection_id_to_address(collection_id);
- Ok(address)
+ )
}
/// Check if a collection exists
pallets/unique/src/eth/stubs/CollectionHelpers.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/CollectionHelpers.sol
+++ b/pallets/unique/src/eth/stubs/CollectionHelpers.sol
@@ -72,12 +72,12 @@
string memory name,
string memory description,
string memory tokenPrefix
- ) public view returns (address) {
+ ) public returns (address) {
require(false, stub_error);
name;
description;
tokenPrefix;
- dummy;
+ dummy = 0;
return 0x0000000000000000000000000000000000000000;
}
@@ -96,7 +96,7 @@
dummy = 0;
return 0x0000000000000000000000000000000000000000;
}
-
+
// Check if a collection exists
// @param collection_address Address of the collection in question
// @return bool Does the collection exist?
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -1050,6 +1050,7 @@
pub enum PropertyScope {
None,
Rmrk,
+ Eth,
}
impl PropertyScope {
@@ -1058,6 +1059,7 @@
let scope_str: &[u8] = match self {
Self::None => return Ok(key),
Self::Rmrk => b"rmrk",
+ Self::Eth => b"eth",
};
[scope_str, b":", key.as_slice()]
runtime/common/src/weights.rsdiffbeforeafterboth--- a/runtime/common/src/weights.rs
+++ b/runtime/common/src/weights.rs
@@ -99,6 +99,10 @@
fn burn_recursively_breadth_raw(amount: u32) -> Weight {
max_weight_of!(burn_recursively_breadth_raw(amount))
}
+
+ fn token_owner() -> Weight {
+ max_weight_of!(token_owner())
+ }
}
impl<T> RefungibleExtensionsWeightInfo for CommonWeights<T>
tests/src/eth/api/CollectionHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/CollectionHelpers.sol
+++ b/tests/src/eth/api/CollectionHelpers.sol
@@ -48,7 +48,7 @@
string memory name,
string memory description,
string memory tokenPrefix
- ) external view returns (address);
+ ) external returns (address);
// Selector: createERC721MetadataCompatibleRFTCollection(string,string,string,string) a5596388
function createERC721MetadataCompatibleRFTCollection(
@@ -57,7 +57,7 @@
string memory tokenPrefix,
string memory baseUri
) external returns (address);
-
+
// Check if a collection exists
// @param collection_address Address of the collection in question
// @return bool Does the collection exist?
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -28,7 +28,44 @@
function burnFrom(address from, uint256 amount) external returns (bool);
}
-// Selector: 7d9262e6
+// Selector: 942e8b22
+interface ERC20 is Dummy, ERC165, ERC20Events {
+ // Selector: name() 06fdde03
+ function name() external view returns (string memory);
+
+ // Selector: symbol() 95d89b41
+ function symbol() external view returns (string memory);
+
+ // Selector: totalSupply() 18160ddd
+ function totalSupply() external view returns (uint256);
+
+ // Selector: decimals() 313ce567
+ function decimals() external view returns (uint8);
+
+ // Selector: balanceOf(address) 70a08231
+ function balanceOf(address owner) external view returns (uint256);
+
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 amount) external returns (bool);
+
+ // Selector: transferFrom(address,address,uint256) 23b872dd
+ function transferFrom(
+ address from,
+ address to,
+ uint256 amount
+ ) external returns (bool);
+
+ // Selector: approve(address,uint256) 095ea7b3
+ function approve(address spender, uint256 amount) external returns (bool);
+
+ // Selector: allowance(address,address) dd62ed3e
+ function allowance(address owner, address spender)
+ external
+ view
+ returns (uint256);
+}
+
+// Selector: aa7d570d
interface Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -174,43 +211,16 @@
//
// Selector: setCollectionMintMode(bool) 00018e84
function setCollectionMintMode(bool mode) external;
-}
-// Selector: 942e8b22
-interface ERC20 is Dummy, ERC165, ERC20Events {
- // Selector: name() 06fdde03
- function name() external view returns (string memory);
-
- // Selector: symbol() 95d89b41
- function symbol() external view returns (string memory);
-
- // Selector: totalSupply() 18160ddd
- function totalSupply() external view returns (uint256);
-
- // Selector: decimals() 313ce567
- function decimals() external view returns (uint8);
-
- // Selector: balanceOf(address) 70a08231
- function balanceOf(address owner) external view returns (uint256);
-
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 amount) external returns (bool);
-
- // Selector: transferFrom(address,address,uint256) 23b872dd
- function transferFrom(
- address from,
- address to,
- uint256 amount
- ) external returns (bool);
+ // Check that account is the owner or admin of the collection
+ //
+ // @return "true" if account is the owner or admin
+ //
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() external returns (bool);
- // Selector: approve(address,uint256) 095ea7b3
- function approve(address spender, uint256 amount) external returns (bool);
-
- // Selector: allowance(address,address) dd62ed3e
- function allowance(address owner, address spender)
- external
- view
- returns (uint256);
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() external returns (string memory);
}
interface UniqueFungible is
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -276,7 +276,7 @@
function totalSupply() external view returns (uint256);
}
-// Selector: 7d9262e6
+// Selector: aa7d570d
interface Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -422,6 +422,16 @@
//
// Selector: setCollectionMintMode(bool) 00018e84
function setCollectionMintMode(bool mode) external;
+
+ // Check that account is the owner or admin of the collection
+ //
+ // @return "true" if account is the owner or admin
+ //
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() external returns (bool);
+
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() external returns (string memory);
}
// Selector: d74d154f
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -274,7 +274,70 @@
function totalSupply() external view returns (uint256);
}
-// Selector: 7d9262e6
+// Selector: 7c3bef89
+interface ERC721UniqueExtensions is Dummy, ERC165 {
+ // @notice Transfer ownership of an RFT
+ // @dev Throws unless `msg.sender` is the current owner. Throws if `to`
+ // is the zero address. Throws if `tokenId` is not a valid RFT.
+ // Throws if RFT pieces have multiple owners.
+ // @param to The new owner
+ // @param tokenId The RFT to transfer
+ // @param _value Not used for an RFT
+ //
+ // Selector: transfer(address,uint256) a9059cbb
+ function transfer(address to, uint256 tokenId) external;
+
+ // @notice Burns a specific ERC721 token.
+ // @dev Throws unless `msg.sender` is the current owner or an authorized
+ // operator for this RFT. Throws if `from` is not the current owner. Throws
+ // if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
+ // Throws if RFT pieces have multiple owners.
+ // @param from The current owner of the RFT
+ // @param tokenId The RFT to transfer
+ // @param _value Not used for an RFT
+ //
+ // Selector: burnFrom(address,uint256) 79cc6790
+ function burnFrom(address from, uint256 tokenId) external;
+
+ // @notice Returns next free RFT ID.
+ //
+ // Selector: nextTokenId() 75794a3c
+ function nextTokenId() external view returns (uint256);
+
+ // @notice Function to mint multiple tokens.
+ // @dev `tokenIds` should be an array of consecutive numbers and first number
+ // should be obtained with `nextTokenId` method
+ // @param to The new owner
+ // @param tokenIds IDs of the minted RFTs
+ //
+ // Selector: mintBulk(address,uint256[]) 44a9945e
+ function mintBulk(address to, uint256[] memory tokenIds)
+ external
+ returns (bool);
+
+ // @notice Function to mint multiple tokens with the given tokenUris.
+ // @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
+ // numbers and first number should be obtained with `nextTokenId` method
+ // @param to The new owner
+ // @param tokens array of pairs of token ID and token URI for minted tokens
+ //
+ // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
+ function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
+ external
+ returns (bool);
+
+ // Returns EVM address for refungible token
+ //
+ // @param token ID of the token
+ //
+ // Selector: tokenContractAddress(uint256) ab76fac6
+ function tokenContractAddress(uint256 token)
+ external
+ view
+ returns (address);
+}
+
+// Selector: aa7d570d
interface Collection is Dummy, ERC165 {
// Set collection property.
//
@@ -420,59 +483,20 @@
//
// Selector: setCollectionMintMode(bool) 00018e84
function setCollectionMintMode(bool mode) external;
-}
-// Selector: d74d154f
-interface ERC721UniqueExtensions is Dummy, ERC165 {
- // @notice Transfer ownership of an RFT
- // @dev Throws unless `msg.sender` is the current owner. Throws if `to`
- // is the zero address. Throws if `tokenId` is not a valid RFT.
- // Throws if RFT pieces have multiple owners.
- // @param to The new owner
- // @param tokenId The RFT to transfer
- // @param _value Not used for an RFT
+ // Check that account is the owner or admin of the collection
//
- // Selector: transfer(address,uint256) a9059cbb
- function transfer(address to, uint256 tokenId) external;
-
- // @notice Burns a specific ERC721 token.
- // @dev Throws unless `msg.sender` is the current owner or an authorized
- // operator for this RFT. Throws if `from` is not the current owner. Throws
- // if `to` is the zero address. Throws if `tokenId` is not a valid RFT.
- // Throws if RFT pieces have multiple owners.
- // @param from The current owner of the RFT
- // @param tokenId The RFT to transfer
- // @param _value Not used for an RFT
+ // @return "true" if account is the owner or admin
//
- // Selector: burnFrom(address,uint256) 79cc6790
- function burnFrom(address from, uint256 tokenId) external;
+ // Selector: verifyOwnerOrAdmin() 04a46053
+ function verifyOwnerOrAdmin() external returns (bool);
- // @notice Returns next free RFT ID.
+ // Returns collection type
//
- // Selector: nextTokenId() 75794a3c
- function nextTokenId() external view returns (uint256);
-
- // @notice Function to mint multiple tokens.
- // @dev `tokenIds` should be an array of consecutive numbers and first number
- // should be obtained with `nextTokenId` method
- // @param to The new owner
- // @param tokenIds IDs of the minted RFTs
+ // @return `Fungible` or `NFT` or `ReFungible`
//
- // Selector: mintBulk(address,uint256[]) 44a9945e
- function mintBulk(address to, uint256[] memory tokenIds)
- external
- returns (bool);
-
- // @notice Function to mint multiple tokens with the given tokenUris.
- // @dev `tokenIds` is array of pairs of token ID and token URI. Token IDs should be consecutive
- // numbers and first number should be obtained with `nextTokenId` method
- // @param to The new owner
- // @param tokens array of pairs of token ID and token URI for minted tokens
- //
- // Selector: mintBulkWithTokenURI(address,(uint256,string)[]) 36543006
- function mintBulkWithTokenURI(address to, Tuple0[] memory tokens)
- external
- returns (bool);
+ // Selector: uniqueCollectionType() d34b55b8
+ function uniqueCollectionType() external returns (string memory);
}
interface UniqueRefungible is
tests/src/eth/api/UniqueRefungibleToken.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungibleToken.sol
+++ b/tests/src/eth/api/UniqueRefungibleToken.sol
@@ -22,6 +22,23 @@
);
}
+// Selector: 042f1106
+interface ERC1633UniqueExtensions is Dummy, ERC165 {
+ // Selector: setParentNFT(address,uint256) 042f1106
+ function setParentNFT(address collection, uint256 nftId)
+ external
+ returns (bool);
+}
+
+// Selector: 5755c3f2
+interface ERC1633 is Dummy, ERC165 {
+ // Selector: parentToken() 80a54001
+ function parentToken() external view returns (address);
+
+ // Selector: parentTokenId() d7f083f3
+ function parentTokenId() external view returns (uint256);
+}
+
// Selector: 942e8b22
interface ERC20 is Dummy, ERC165, ERC20Events {
// @return the name of the token.
@@ -115,5 +132,7 @@
Dummy,
ERC165,
ERC20,
- ERC20UniqueExtensions
+ ERC20UniqueExtensions,
+ ERC1633,
+ ERC1633UniqueExtensions
{}
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -482,6 +482,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "token", "type": "uint256" }
+ ],
+ "name": "tokenContractAddress",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "uint256", "name": "index", "type": "uint256" }
],
@@ -526,5 +535,19 @@
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "uniqueCollectionType",
+ "outputs": [{ "internalType": "string", "name": "", "type": "string" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "verifyOwnerOrAdmin",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
}
]
tests/src/eth/reFungibleToken.test.tsdiffbeforeafterboth--- a/tests/src/eth/reFungibleToken.test.ts
+++ b/tests/src/eth/reFungibleToken.test.ts
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {approve, createCollection, createRefungibleToken, transfer, transferFrom, UNIQUE} from '../util/helpers';
-import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth} from './util/helpers';
+import {collectionIdFromAddress, collectionIdToAddress, createEthAccount, createEthAccountWithBalance, createNonfungibleCollection, createRefungibleCollection, evmCollection, evmCollectionHelpers, GAS_ARGS, getCollectionAddressFromResult, itWeb3, normalizeEvents, recordEthFee, recordEvents, subToEth, tokenIdToAddress, transferBalanceToEth, uniqueNFT, uniqueRefungible, uniqueRefungibleToken} from './util/helpers';
import reFungibleTokenAbi from './reFungibleTokenAbi.json';
import chai from 'chai';
@@ -630,3 +630,31 @@
]);
});
});
+
+describe('ERC 1633 implementation', () => {
+ itWeb3('Parent NFT token address and id', async ({api, web3, privateKeyWrapper}) => {
+ const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
+
+ const {collectionIdAddress: nftCollectionAddress} = await createNonfungibleCollection(api, web3, owner);
+ const nftContract = uniqueNFT(web3, nftCollectionAddress, owner);
+ const nftTokenId = await nftContract.methods.nextTokenId().call();
+ await nftContract.methods.mint(owner, nftTokenId).send();
+ const nftCollectionId = collectionIdFromAddress(nftCollectionAddress);
+
+ const {collectionIdAddress, collectionId} = await createRefungibleCollection(api, web3, owner);
+ const refungibleContract = uniqueRefungible(web3, collectionIdAddress, owner);
+ const refungibleTokenId = await refungibleContract.methods.nextTokenId().call();
+ await refungibleContract.methods.mint(owner, refungibleTokenId).send();
+
+ const rftTokenAddress = tokenIdToAddress(collectionId, refungibleTokenId);
+ const refungibleTokenContract = uniqueRefungibleToken(web3, rftTokenAddress, owner);
+ await refungibleTokenContract.methods.setParentNFT(nftCollectionAddress, nftTokenId).send();
+
+ const tokenAddress = await refungibleTokenContract.methods.parentToken().call();
+ const tokenId = await refungibleTokenContract.methods.parentTokenId().call();
+ const nftTokenAddress = tokenIdToAddress(nftCollectionId, nftTokenId);
+ expect(tokenAddress).to.be.equal(nftTokenAddress);
+ expect(tokenId).to.be.equal(nftTokenId);
+ });
+});
+
tests/src/eth/reFungibleTokenAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleTokenAbi.json
+++ b/tests/src/eth/reFungibleTokenAbi.json
@@ -103,6 +103,20 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "parentToken",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [],
+ "name": "parentTokenId",
+ "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
@@ -113,6 +127,16 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "collection", "type": "address" },
+ { "internalType": "uint256", "name": "nftId", "type": "uint256" }
+ ],
+ "name": "setParentNFT",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
],
"name": "supportsInterface",