difftreelog
Merge pull request #574 from UniqueNetwork/feature/eth_passthrought
in: master
Feature/eth passthrought
19 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -20,6 +20,7 @@
solidity_interface, solidity, ToLog,
types::*,
execution::{Result, Error},
+ weight,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
@@ -31,8 +32,12 @@
use alloc::format;
use crate::{
- Pallet, CollectionHandle, Config, CollectionProperties,
- eth::{convert_cross_account_to_uint256, convert_uint256_to_cross_account},
+ Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
+ eth::{
+ convert_cross_account_to_uint256, convert_uint256_to_cross_account,
+ convert_cross_account_to_tuple,
+ },
+ weights::WeightInfo,
};
/// Events for ethereum collection helper.
@@ -69,6 +74,7 @@
///
/// @param key Property key.
/// @param value Propery value.
+ #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]
fn set_collection_property(
&mut self,
caller: caller,
@@ -88,7 +94,10 @@
/// Delete collection property.
///
/// @param key Property key.
+ #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let key = <Vec<u8>>::from(key)
.try_into()
@@ -120,6 +129,8 @@
///
/// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let sponsor = T::CrossAccountId::from_eth(sponsor);
@@ -138,6 +149,8 @@
caller: caller,
sponsor: uint256,
) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
@@ -146,7 +159,7 @@
save(self)
}
- // /// Whether there is a pending sponsor.
+ /// Whether there is a pending sponsor.
fn has_collection_pending_sponsor(&self) -> Result<bool> {
Ok(matches!(
self.collection.sponsorship,
@@ -158,6 +171,8 @@
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
if !self
.confirm_sponsorship(caller.as_sub())
@@ -170,6 +185,7 @@
/// Remove collection sponsor.
fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
check_is_owner_or_admin(caller, self)?;
self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;
save(self)
@@ -206,6 +222,8 @@
/// @param value Value of the limit.
#[solidity(rename_selector = "setCollectionLimit")]
fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut limits = self.limits.clone();
@@ -249,6 +267,8 @@
/// @param value Value of the limit.
#[solidity(rename_selector = "setCollectionLimit")]
fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut limits = self.limits.clone();
@@ -275,7 +295,7 @@
}
/// Get contract address.
- fn contract_address(&self, _caller: caller) -> Result<address> {
+ fn contract_address(&self) -> Result<address> {
Ok(crate::eth::collection_id_to_address(self.id))
}
@@ -286,6 +306,8 @@
caller: caller,
new_admin: uint256,
) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
@@ -299,6 +321,8 @@
caller: caller,
admin: uint256,
) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let admin = convert_uint256_to_cross_account::<T>(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
@@ -308,6 +332,8 @@
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
fn add_collection_admin(&mut self, caller: caller, new_admin: address) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_admin = T::CrossAccountId::from_eth(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
@@ -318,6 +344,8 @@
///
/// @param admin Address of the removed administrator.
fn remove_collection_admin(&mut self, caller: caller, admin: address) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let admin = T::CrossAccountId::from_eth(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
@@ -329,6 +357,8 @@
/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
#[solidity(rename_selector = "setCollectionNesting")]
fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut permissions = self.collection.permissions.clone();
@@ -358,6 +388,8 @@
enable: bool,
collections: Vec<address>,
) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
if collections.is_empty() {
return Err("no addresses provided".into());
}
@@ -401,6 +433,8 @@
/// 0 for Normal
/// 1 for AllowList
fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let permissions = CollectionPermissions {
access: Some(match mode {
@@ -420,30 +454,78 @@
save(self)
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ fn allowed(&self, user: address) -> Result<bool> {
+ Ok(Pallet::<T>::allowed(
+ self.id,
+ T::CrossAccountId::from_eth(user),
+ ))
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
fn add_to_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
<Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ fn add_to_collection_allow_list_substrate(
+ &mut self,
+ caller: caller,
+ user: uint256,
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_uint256_to_cross_account::<T>(user);
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
fn remove_from_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
<Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ fn remove_from_collection_allow_list_substrate(
+ &mut self,
+ caller: caller,
+ user: uint256,
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_uint256_to_cross_account::<T>(user);
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let permissions = CollectionPermissions {
mint_mode: Some(mode),
@@ -481,7 +563,7 @@
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
- fn unique_collection_type(&mut self) -> Result<string> {
+ fn unique_collection_type(&self) -> Result<string> {
let mode = match self.collection.mode {
CollectionMode::Fungible(_) => "Fungible",
CollectionMode::NFT => "NFT",
@@ -490,11 +572,23 @@
Ok(mode.into())
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ fn collection_owner(&self) -> Result<(address, uint256)> {
+ Ok(convert_cross_account_to_tuple::<T>(
+ &T::CrossAccountId::from_sub(self.owner.clone()),
+ ))
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_owner = T::CrossAccountId::from_eth(new_owner);
self.set_owner_internal(caller, new_owner)
@@ -506,13 +600,25 @@
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner substrate account
fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
self.set_owner_internal(caller, new_owner)
.map_err(dispatch_to_evm::<T>)
}
+
+ // TODO: need implement AbiWriter for &Vec<T>
+ // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
+ // let result = pallet_common::IsAdmin::<T>::iter_prefix((self.id,))
+ // .map(|(admin, _)| pallet_common::eth::convert_cross_account_to_tuple::<T>(&admin))
+ // .collect();
+ // Ok(result)
+ // }
}
+/// ### Note
+/// Do not forget to add: `self.consume_store_reads(1)?;`
fn check_is_owner_or_admin<T: Config>(
caller: caller,
collection: &CollectionHandle<T>,
@@ -524,9 +630,9 @@
Ok(caller)
}
+/// ### Note
+/// Do not forget to add: `self.consume_store_writes(1)?;`
fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {
- // TODO possibly delete for the lack of transaction
- collection.consume_store_writes(1)?;
collection
.check_is_internal()
.map_err(dispatch_to_evm::<T>)?;
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -16,7 +16,7 @@
//! The module contains a number of functions for converting and checking ethereum identifiers.
-use evm_coder::types::uint256;
+use evm_coder::types::{uint256, address};
pub use pallet_evm::account::{Config, CrossAccountId};
use sp_core::H160;
use up_data_structs::CollectionId;
@@ -69,3 +69,19 @@
let account_id = T::AccountId::from(new_admin_arr);
T::CrossAccountId::from_sub(account_id)
}
+
+/// Convert `CrossAccountId` to `(address, uint256)`.
+pub fn convert_cross_account_to_tuple<T: Config>(
+ cross_account_id: &T::CrossAccountId,
+) -> (address, uint256)
+where
+ T::AccountId: AsRef<[u8; 32]>,
+{
+ if cross_account_id.is_canonical_substrate() {
+ let sub = convert_cross_account_to_uint256::<T>(cross_account_id);
+ (Default::default(), sub)
+ } else {
+ let eth = *cross_account_id.as_eth();
+ (eth, Default::default())
+ }
+}
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 /// Remove collection sponsor.235 pub fn remove_sponsor(&mut self) -> DispatchResult {236 self.collection.sponsorship = SponsorshipState::Disabled;237 Ok(())238 }239240 /// Checks that the collection was created with, and must be operated upon through **Unique API**.241 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.242 pub fn check_is_internal(&self) -> DispatchResult {243 if self.external_collection {244 return Err(<Error<T>>::CollectionIsExternal)?;245 }246247 Ok(())248 }249250 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.251 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.252 pub fn check_is_external(&self) -> DispatchResult {253 if !self.external_collection {254 return Err(<Error<T>>::CollectionIsInternal)?;255 }256257 Ok(())258 }259}260261impl<T: Config> Deref for CollectionHandle<T> {262 type Target = Collection<T::AccountId>;263264 fn deref(&self) -> &Self::Target {265 &self.collection266 }267}268269impl<T: Config> DerefMut for CollectionHandle<T> {270 fn deref_mut(&mut self) -> &mut Self::Target {271 &mut self.collection272 }273}274275impl<T: Config> CollectionHandle<T> {276 /// Checks if the `user` is the owner of the collection.277 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {278 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);279 Ok(())280 }281282 /// Returns **true** if the `user` is the owner or administrator of the collection.283 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {284 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))285 }286287 /// Checks if the `user` is the owner or administrator of the collection.288 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {289 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);290 Ok(())291 }292293 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.294 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {295 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)296 }297298 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.299 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {300 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)301 }302303 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.304 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {305 ensure!(306 <Allowlist<T>>::get((self.id, user)),307 <Error<T>>::AddressNotInAllowlist308 );309 Ok(())310 }311312 /// Changes collection owner to another account313 fn set_owner_internal(314 &mut self,315 caller: T::CrossAccountId,316 new_owner: T::CrossAccountId,317 ) -> DispatchResult {318 self.check_is_owner(&caller)?;319 self.collection.owner = new_owner.as_sub().clone();320 self.save()321 }322}323324#[frame_support::pallet]325pub mod pallet {326 use super::*;327 use pallet_evm::account;328 use dispatch::CollectionDispatch;329 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};330 use frame_system::pallet_prelude::*;331 use frame_support::traits::Currency;332 use up_data_structs::{TokenId, mapping::TokenAddressMapping};333 use scale_info::TypeInfo;334 use weights::WeightInfo;335336 #[pallet::config]337 pub trait Config:338 frame_system::Config339 + pallet_evm_coder_substrate::Config340 + pallet_evm::Config341 + TypeInfo342 + account::Config343 {344 /// Weight information for functions of this pallet.345 type WeightInfo: WeightInfo;346347 /// Events compatible with [`frame_system::Config::Event`].348 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;349350 /// Handler of accounts and payment.351 type Currency: Currency<Self::AccountId>;352353 /// Set price to create a collection.354 #[pallet::constant]355 type CollectionCreationPrice: Get<356 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,357 >;358359 /// Dispatcher of operations on collections.360 type CollectionDispatch: CollectionDispatch<Self>;361362 /// Account which holds the chain's treasury.363 type TreasuryAccountId: Get<Self::AccountId>;364365 /// Address under which the CollectionHelper contract would be available.366 type ContractAddress: Get<H160>;367368 /// Mapper for token addresses to Ethereum addresses.369 type EvmTokenAddressMapping: TokenAddressMapping<H160>;370371 /// Mapper for token addresses to [`CrossAccountId`].372 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;373 }374375 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);376377 #[pallet::pallet]378 #[pallet::storage_version(STORAGE_VERSION)]379 #[pallet::generate_store(pub(super) trait Store)]380 pub struct Pallet<T>(_);381382 #[pallet::extra_constants]383 impl<T: Config> Pallet<T> {384 /// Maximum admins per collection.385 pub fn collection_admins_limit() -> u32 {386 COLLECTION_ADMINS_LIMIT387 }388 }389390 #[pallet::event]391 #[pallet::generate_deposit(pub fn deposit_event)]392 pub enum Event<T: Config> {393 /// New collection was created394 CollectionCreated(395 /// Globally unique identifier of newly created collection.396 CollectionId,397 /// [`CollectionMode`] converted into _u8_.398 u8,399 /// Collection owner.400 T::AccountId,401 ),402403 /// New collection was destroyed404 CollectionDestroyed(405 /// Globally unique identifier of collection.406 CollectionId,407 ),408409 /// New item was created.410 ItemCreated(411 /// Id of the collection where item was created.412 CollectionId,413 /// Id of an item. Unique within the collection.414 TokenId,415 /// Owner of newly created item416 T::CrossAccountId,417 /// Always 1 for NFT418 u128,419 ),420421 /// Collection item was burned.422 ItemDestroyed(423 /// Id of the collection where item was destroyed.424 CollectionId,425 /// Identifier of burned NFT.426 TokenId,427 /// Which user has destroyed its tokens.428 T::CrossAccountId,429 /// Amount of token pieces destroed. Always 1 for NFT.430 u128,431 ),432433 /// Item was transferred434 Transfer(435 /// Id of collection to which item is belong.436 CollectionId,437 /// Id of an item.438 TokenId,439 /// Original owner of item.440 T::CrossAccountId,441 /// New owner of item.442 T::CrossAccountId,443 /// Amount of token pieces transfered. Always 1 for NFT.444 u128,445 ),446447 /// Amount pieces of token owned by `sender` was approved for `spender`.448 Approved(449 /// Id of collection to which item is belong.450 CollectionId,451 /// Id of an item.452 TokenId,453 /// Original owner of item.454 T::CrossAccountId,455 /// Id for which the approval was granted.456 T::CrossAccountId,457 /// Amount of token pieces transfered. Always 1 for NFT.458 u128,459 ),460461 /// The colletion property has been added or edited.462 CollectionPropertySet(463 /// Id of collection to which property has been set.464 CollectionId,465 /// The property that was set.466 PropertyKey,467 ),468469 /// The property has been deleted.470 CollectionPropertyDeleted(471 /// Id of collection to which property has been deleted.472 CollectionId,473 /// The property that was deleted.474 PropertyKey,475 ),476477 /// The token property has been added or edited.478 TokenPropertySet(479 /// Identifier of the collection whose token has the property set.480 CollectionId,481 /// The token for which the property was set.482 TokenId,483 /// The property that was set.484 PropertyKey,485 ),486487 /// The token property has been deleted.488 TokenPropertyDeleted(489 /// Identifier of the collection whose token has the property deleted.490 CollectionId,491 /// The token for which the property was deleted.492 TokenId,493 /// The property that was deleted.494 PropertyKey,495 ),496497 /// The token property permission of a collection has been set.498 PropertyPermissionSet(499 /// ID of collection to which property permission has been set.500 CollectionId,501 /// The property permission that was set.502 PropertyKey,503 ),504 }505506 #[pallet::error]507 pub enum Error<T> {508 /// This collection does not exist.509 CollectionNotFound,510 /// Sender parameter and item owner must be equal.511 MustBeTokenOwner,512 /// No permission to perform action513 NoPermission,514 /// Destroying only empty collections is allowed515 CantDestroyNotEmptyCollection,516 /// Collection is not in mint mode.517 PublicMintingNotAllowed,518 /// Address is not in allow list.519 AddressNotInAllowlist,520521 /// Collection name can not be longer than 63 char.522 CollectionNameLimitExceeded,523 /// Collection description can not be longer than 255 char.524 CollectionDescriptionLimitExceeded,525 /// Token prefix can not be longer than 15 char.526 CollectionTokenPrefixLimitExceeded,527 /// Total collections bound exceeded.528 TotalCollectionsLimitExceeded,529 /// Exceeded max admin count530 CollectionAdminCountExceeded,531 /// Collection limit bounds per collection exceeded532 CollectionLimitBoundsExceeded,533 /// Tried to enable permissions which are only permitted to be disabled534 OwnerPermissionsCantBeReverted,535 /// Collection settings not allowing items transferring536 TransferNotAllowed,537 /// Account token limit exceeded per collection538 AccountTokenLimitExceeded,539 /// Collection token limit exceeded540 CollectionTokenLimitExceeded,541 /// Metadata flag frozen542 MetadataFlagFrozen,543544 /// Item does not exist545 TokenNotFound,546 /// Item is balance not enough547 TokenValueTooLow,548 /// Requested value is more than the approved549 ApprovedValueTooLow,550 /// Tried to approve more than owned551 CantApproveMoreThanOwned,552553 /// Can't transfer tokens to ethereum zero address554 AddressIsZero,555556 /// The operation is not supported557 UnsupportedOperation,558559 /// Insufficient funds to perform an action560 NotSufficientFounds,561562 /// User does not satisfy the nesting rule563 UserIsNotAllowedToNest,564 /// Only tokens from specific collections may nest tokens under this one565 SourceCollectionIsNotAllowedToNest,566567 /// Tried to store more data than allowed in collection field568 CollectionFieldSizeExceeded,569570 /// Tried to store more property data than allowed571 NoSpaceForProperty,572573 /// Tried to store more property keys than allowed574 PropertyLimitReached,575576 /// Property key is too long577 PropertyKeyIsTooLong,578579 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed580 InvalidCharacterInPropertyKey,581582 /// Empty property keys are forbidden583 EmptyPropertyKey,584585 /// Tried to access an external collection with an internal API586 CollectionIsExternal,587588 /// Tried to access an internal collection with an external API589 CollectionIsInternal,590 }591592 /// Storage of the count of created collections. Essentially contains the last collection ID.593 #[pallet::storage]594 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;595596 /// Storage of the count of deleted collections.597 #[pallet::storage]598 pub type DestroyedCollectionCount<T> =599 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;600601 /// Storage of collection info.602 #[pallet::storage]603 pub type CollectionById<T> = StorageMap<604 Hasher = Blake2_128Concat,605 Key = CollectionId,606 Value = Collection<<T as frame_system::Config>::AccountId>,607 QueryKind = OptionQuery,608 >;609610 /// Storage of collection properties.611 #[pallet::storage]612 #[pallet::getter(fn collection_properties)]613 pub type CollectionProperties<T> = StorageMap<614 Hasher = Blake2_128Concat,615 Key = CollectionId,616 Value = Properties,617 QueryKind = ValueQuery,618 OnEmpty = up_data_structs::CollectionProperties,619 >;620621 /// Storage of token property permissions of a collection.622 #[pallet::storage]623 #[pallet::getter(fn property_permissions)]624 pub type CollectionPropertyPermissions<T> = StorageMap<625 Hasher = Blake2_128Concat,626 Key = CollectionId,627 Value = PropertiesPermissionMap,628 QueryKind = ValueQuery,629 >;630631 /// Storage of the amount of collection admins.632 #[pallet::storage]633 pub type AdminAmount<T> = StorageMap<634 Hasher = Blake2_128Concat,635 Key = CollectionId,636 Value = u32,637 QueryKind = ValueQuery,638 >;639640 /// List of collection admins.641 #[pallet::storage]642 pub type IsAdmin<T: Config> = StorageNMap<643 Key = (644 Key<Blake2_128Concat, CollectionId>,645 Key<Blake2_128Concat, T::CrossAccountId>,646 ),647 Value = bool,648 QueryKind = ValueQuery,649 >;650651 /// Allowlisted collection users.652 #[pallet::storage]653 pub type Allowlist<T: Config> = StorageNMap<654 Key = (655 Key<Blake2_128Concat, CollectionId>,656 Key<Blake2_128Concat, T::CrossAccountId>,657 ),658 Value = bool,659 QueryKind = ValueQuery,660 >;661662 /// Not used by code, exists only to provide some types to metadata.663 #[pallet::storage]664 pub type DummyStorageValue<T: Config> = StorageValue<665 Value = (666 CollectionStats,667 CollectionId,668 TokenId,669 TokenChild,670 PhantomType<(671 TokenData<T::CrossAccountId>,672 RpcCollection<T::AccountId>,673 // RMRK674 RmrkCollectionInfo<T::AccountId>,675 RmrkInstanceInfo<T::AccountId>,676 RmrkResourceInfo,677 RmrkPropertyInfo,678 RmrkBaseInfo<T::AccountId>,679 RmrkPartType,680 RmrkBoundedTheme,681 RmrkNftChild,682 )>,683 ),684 QueryKind = OptionQuery,685 >;686687 #[pallet::hooks]688 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {689 fn on_runtime_upgrade() -> Weight {690 StorageVersion::new(1).put::<Pallet<T>>();691692 0693 }694 }695}696697impl<T: Config> Pallet<T> {698 /// Enshure that receiver address is correct.699 ///700 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.701 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {702 ensure!(703 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,704 <Error<T>>::AddressIsZero705 );706 Ok(())707 }708709 /// Get a vector of collection admins.710 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {711 <IsAdmin<T>>::iter_prefix((collection,))712 .map(|(a, _)| a)713 .collect()714 }715716 /// Get a vector of users allowed to mint tokens.717 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {718 <Allowlist<T>>::iter_prefix((collection,))719 .map(|(a, _)| a)720 .collect()721 }722723 /// Is `user` allowed to mint token in `collection`.724 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {725 <Allowlist<T>>::get((collection, user))726 }727728 /// Get statistics of collections.729 pub fn collection_stats() -> CollectionStats {730 let created = <CreatedCollectionCount<T>>::get();731 let destroyed = <DestroyedCollectionCount<T>>::get();732 CollectionStats {733 created: created.0,734 destroyed: destroyed.0,735 alive: created.0 - destroyed.0,736 }737 }738739 /// Get the effective limits for the collection.740 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {741 let collection = <CollectionById<T>>::get(collection)?;742 let limits = collection.limits;743 let effective_limits = CollectionLimits {744 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),745 sponsored_data_size: Some(limits.sponsored_data_size()),746 sponsored_data_rate_limit: Some(747 limits748 .sponsored_data_rate_limit749 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),750 ),751 token_limit: Some(limits.token_limit()),752 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(753 match collection.mode {754 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,755 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,756 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,757 },758 )),759 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),760 owner_can_transfer: Some(limits.owner_can_transfer()),761 owner_can_destroy: Some(limits.owner_can_destroy()),762 transfers_enabled: Some(limits.transfers_enabled()),763 };764765 Some(effective_limits)766 }767768 /// Returns information about the `collection` adapted for rpc.769 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {770 let Collection {771 name,772 description,773 owner,774 mode,775 token_prefix,776 sponsorship,777 limits,778 permissions,779 external_collection,780 } = <CollectionById<T>>::get(collection)?;781782 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)783 .into_iter()784 .map(|(key, permission)| PropertyKeyPermission { key, permission })785 .collect();786787 let properties = <CollectionProperties<T>>::get(collection)788 .into_iter()789 .map(|(key, value)| Property { key, value })790 .collect();791792 let permissions = CollectionPermissions {793 access: Some(permissions.access()),794 mint_mode: Some(permissions.mint_mode()),795 nesting: Some(permissions.nesting().clone()),796 };797798 Some(RpcCollection {799 name: name.into_inner(),800 description: description.into_inner(),801 owner,802 mode,803 token_prefix: token_prefix.into_inner(),804 sponsorship,805 limits,806 permissions,807 token_property_permissions,808 properties,809 read_only: external_collection,810 })811 }812}813814macro_rules! limit_default {815 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{816 $(817 if let Some($new) = $new.$field {818 let $old = $old.$field($($arg)?);819 let _ = $new;820 let _ = $old;821 $check822 } else {823 $new.$field = $old.$field824 }825 )*826 }};827}828macro_rules! limit_default_clone {829 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{830 $(831 if let Some($new) = $new.$field.clone() {832 let $old = $old.$field($($arg)?);833 let _ = $new;834 let _ = $old;835 $check836 } else {837 $new.$field = $old.$field.clone()838 }839 )*840 }};841}842843impl<T: Config> Pallet<T> {844 /// Create new collection.845 ///846 /// * `owner` - The owner of the collection.847 /// * `data` - Description of the created collection.848 /// * `is_external` - Marks that collection managet by not "Unique network".849 pub fn init_collection(850 owner: T::CrossAccountId,851 data: CreateCollectionData<T::AccountId>,852 is_external: bool,853 ) -> Result<CollectionId, DispatchError> {854 {855 ensure!(856 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,857 Error::<T>::CollectionTokenPrefixLimitExceeded858 );859 }860861 let created_count = <CreatedCollectionCount<T>>::get()862 .0863 .checked_add(1)864 .ok_or(ArithmeticError::Overflow)?;865 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;866 let id = CollectionId(created_count);867868 // bound Total number of collections869 ensure!(870 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,871 <Error<T>>::TotalCollectionsLimitExceeded872 );873874 // =========875876 let collection = Collection {877 owner: owner.as_sub().clone(),878 name: data.name,879 mode: data.mode.clone(),880 description: data.description,881 token_prefix: data.token_prefix,882 sponsorship: data883 .pending_sponsor884 .map(SponsorshipState::Unconfirmed)885 .unwrap_or_default(),886 limits: data887 .limits888 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))889 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,890 permissions: data891 .permissions892 .map(|permissions| {893 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)894 })895 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,896 external_collection: is_external,897 };898899 let mut collection_properties = up_data_structs::CollectionProperties::get();900 collection_properties901 .try_set_from_iter(data.properties.into_iter())902 .map_err(<Error<T>>::from)?;903904 CollectionProperties::<T>::insert(id, collection_properties);905906 let mut token_props_permissions = PropertiesPermissionMap::new();907 token_props_permissions908 .try_set_from_iter(data.token_property_permissions.into_iter())909 .map_err(<Error<T>>::from)?;910911 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);912913 // Take a (non-refundable) deposit of collection creation914 {915 let mut imbalance =916 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();917 imbalance.subsume(918 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(919 &T::TreasuryAccountId::get(),920 T::CollectionCreationPrice::get(),921 ),922 );923 <T as Config>::Currency::settle(924 owner.as_sub(),925 imbalance,926 WithdrawReasons::TRANSFER,927 ExistenceRequirement::KeepAlive,928 )929 .map_err(|_| Error::<T>::NotSufficientFounds)?;930 }931932 <CreatedCollectionCount<T>>::put(created_count);933 <Pallet<T>>::deposit_event(Event::CollectionCreated(934 id,935 data.mode.id(),936 owner.as_sub().clone(),937 ));938 <PalletEvm<T>>::deposit_log(939 erc::CollectionHelpersEvents::CollectionCreated {940 owner: *owner.as_eth(),941 collection_id: eth::collection_id_to_address(id),942 }943 .to_log(T::ContractAddress::get()),944 );945 <CollectionById<T>>::insert(id, collection);946 Ok(id)947 }948949 /// Destroy collection.950 ///951 /// * `collection` - Collection handler.952 /// * `sender` - The owner or administrator of the collection.953 pub fn destroy_collection(954 collection: CollectionHandle<T>,955 sender: &T::CrossAccountId,956 ) -> DispatchResult {957 ensure!(958 collection.limits.owner_can_destroy(),959 <Error<T>>::NoPermission,960 );961 collection.check_is_owner(sender)?;962963 let destroyed_collections = <DestroyedCollectionCount<T>>::get()964 .0965 .checked_add(1)966 .ok_or(ArithmeticError::Overflow)?;967968 // =========969970 <DestroyedCollectionCount<T>>::put(destroyed_collections);971 <CollectionById<T>>::remove(collection.id);972 <AdminAmount<T>>::remove(collection.id);973 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);974 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);975 <CollectionProperties<T>>::remove(collection.id);976977 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));978 Ok(())979 }980981 /// Set collection property.982 ///983 /// * `collection` - Collection handler.984 /// * `sender` - The owner or administrator of the collection.985 /// * `property` - The property to set.986 pub fn set_collection_property(987 collection: &CollectionHandle<T>,988 sender: &T::CrossAccountId,989 property: Property,990 ) -> DispatchResult {991 collection.check_is_owner_or_admin(sender)?;992993 CollectionProperties::<T>::try_mutate(collection.id, |properties| {994 let property = property.clone();995 properties.try_set(property.key, property.value)996 })997 .map_err(<Error<T>>::from)?;998999 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10001001 Ok(())1002 }10031004 /// Set scouped collection property.1005 ///1006 /// * `collection_id` - ID of the collection for which the property is being set.1007 /// * `scope` - Property scope.1008 /// * `property` - The property to set.1009 pub fn set_scoped_collection_property(1010 collection_id: CollectionId,1011 scope: PropertyScope,1012 property: Property,1013 ) -> DispatchResult {1014 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1015 properties.try_scoped_set(scope, property.key, property.value)1016 })1017 .map_err(<Error<T>>::from)?;10181019 Ok(())1020 }10211022 /// Set scouped collection properties.1023 ///1024 /// * `collection_id` - ID of the collection for which the properties is being set.1025 /// * `scope` - Property scope.1026 /// * `properties` - The properties to set.1027 pub fn set_scoped_collection_properties(1028 collection_id: CollectionId,1029 scope: PropertyScope,1030 properties: impl Iterator<Item = Property>,1031 ) -> DispatchResult {1032 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1033 stored_properties.try_scoped_set_from_iter(scope, properties)1034 })1035 .map_err(<Error<T>>::from)?;10361037 Ok(())1038 }10391040 /// Set collection properties.1041 ///1042 /// * `collection` - Collection handler.1043 /// * `sender` - The owner or administrator of the collection.1044 /// * `properties` - The properties to set.1045 #[transactional]1046 pub fn set_collection_properties(1047 collection: &CollectionHandle<T>,1048 sender: &T::CrossAccountId,1049 properties: Vec<Property>,1050 ) -> DispatchResult {1051 for property in properties {1052 Self::set_collection_property(collection, sender, property)?;1053 }10541055 Ok(())1056 }10571058 /// Delete collection property.1059 ///1060 /// * `collection` - Collection handler.1061 /// * `sender` - The owner or administrator of the collection.1062 /// * `property` - The property to delete.1063 pub fn delete_collection_property(1064 collection: &CollectionHandle<T>,1065 sender: &T::CrossAccountId,1066 property_key: PropertyKey,1067 ) -> DispatchResult {1068 collection.check_is_owner_or_admin(sender)?;10691070 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1071 properties.remove(&property_key)1072 })1073 .map_err(<Error<T>>::from)?;10741075 Self::deposit_event(Event::CollectionPropertyDeleted(1076 collection.id,1077 property_key,1078 ));10791080 Ok(())1081 }10821083 /// Delete collection properties.1084 ///1085 /// * `collection` - Collection handler.1086 /// * `sender` - The owner or administrator of the collection.1087 /// * `properties` - The properties to delete.1088 #[transactional]1089 pub fn delete_collection_properties(1090 collection: &CollectionHandle<T>,1091 sender: &T::CrossAccountId,1092 property_keys: Vec<PropertyKey>,1093 ) -> DispatchResult {1094 for key in property_keys {1095 Self::delete_collection_property(collection, sender, key)?;1096 }10971098 Ok(())1099 }11001101 /// Set collection propetry permission without any checks.1102 ///1103 /// Used for migrations.1104 ///1105 /// * `collection` - Collection handler.1106 /// * `property_permissions` - Property permissions.1107 pub fn set_property_permission_unchecked(1108 collection: CollectionId,1109 property_permission: PropertyKeyPermission,1110 ) -> DispatchResult {1111 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1112 permissions.try_set(property_permission.key, property_permission.permission)1113 })1114 .map_err(<Error<T>>::from)?;1115 Ok(())1116 }11171118 /// Set collection property permission.1119 ///1120 /// * `collection` - Collection handler.1121 /// * `sender` - The owner or administrator of the collection.1122 /// * `property_permission` - Property permission.1123 pub fn set_property_permission(1124 collection: &CollectionHandle<T>,1125 sender: &T::CrossAccountId,1126 property_permission: PropertyKeyPermission,1127 ) -> DispatchResult {1128 Self::set_scoped_property_permission(1129 collection,1130 sender,1131 PropertyScope::None,1132 property_permission,1133 )1134 }11351136 /// Set collection property permission with scope.1137 ///1138 /// * `collection` - Collection handler.1139 /// * `sender` - The owner or administrator of the collection.1140 /// * `scope` - Property scope.1141 /// * `property_permission` - Property permission.1142 pub fn set_scoped_property_permission(1143 collection: &CollectionHandle<T>,1144 sender: &T::CrossAccountId,1145 scope: PropertyScope,1146 property_permission: PropertyKeyPermission,1147 ) -> DispatchResult {1148 collection.check_is_owner_or_admin(sender)?;11491150 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1151 let current_permission = all_permissions.get(&property_permission.key);1152 if matches![1153 current_permission,1154 Some(PropertyPermission { mutable: false, .. })1155 ] {1156 return Err(<Error<T>>::NoPermission.into());1157 }11581159 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1160 let property_permission = property_permission.clone();1161 permissions.try_scoped_set(1162 scope,1163 property_permission.key,1164 property_permission.permission,1165 )1166 })1167 .map_err(<Error<T>>::from)?;11681169 Self::deposit_event(Event::PropertyPermissionSet(1170 collection.id,1171 property_permission.key,1172 ));11731174 Ok(())1175 }11761177 /// Set token property permission.1178 ///1179 /// * `collection` - Collection handler.1180 /// * `sender` - The owner or administrator of the collection.1181 /// * `property_permissions` - Property permissions.1182 #[transactional]1183 pub fn set_token_property_permissions(1184 collection: &CollectionHandle<T>,1185 sender: &T::CrossAccountId,1186 property_permissions: Vec<PropertyKeyPermission>,1187 ) -> DispatchResult {1188 Self::set_scoped_token_property_permissions(1189 collection,1190 sender,1191 PropertyScope::None,1192 property_permissions,1193 )1194 }11951196 /// Set token property permission with scope.1197 ///1198 /// * `collection` - Collection handler.1199 /// * `sender` - The owner or administrator of the collection.1200 /// * `scope` - Property scope.1201 /// * `property_permissions` - Property permissions.1202 #[transactional]1203 pub fn set_scoped_token_property_permissions(1204 collection: &CollectionHandle<T>,1205 sender: &T::CrossAccountId,1206 scope: PropertyScope,1207 property_permissions: Vec<PropertyKeyPermission>,1208 ) -> DispatchResult {1209 for prop_pemission in property_permissions {1210 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1211 }12121213 Ok(())1214 }12151216 /// Get collection property.1217 pub fn get_collection_property(1218 collection_id: CollectionId,1219 key: &PropertyKey,1220 ) -> Option<PropertyValue> {1221 Self::collection_properties(collection_id).get(key).cloned()1222 }12231224 /// Convert byte vector to property key vector.1225 pub fn bytes_keys_to_property_keys(1226 keys: Vec<Vec<u8>>,1227 ) -> Result<Vec<PropertyKey>, DispatchError> {1228 keys.into_iter()1229 .map(|key| -> Result<PropertyKey, DispatchError> {1230 key.try_into()1231 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1232 })1233 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1234 }12351236 /// Get properties according to given keys.1237 pub fn filter_collection_properties(1238 collection_id: CollectionId,1239 keys: Option<Vec<PropertyKey>>,1240 ) -> Result<Vec<Property>, DispatchError> {1241 let properties = Self::collection_properties(collection_id);12421243 let properties = keys1244 .map(|keys| {1245 keys.into_iter()1246 .filter_map(|key| {1247 properties.get(&key).map(|value| Property {1248 key,1249 value: value.clone(),1250 })1251 })1252 .collect()1253 })1254 .unwrap_or_else(|| {1255 properties1256 .into_iter()1257 .map(|(key, value)| Property { key, value })1258 .collect()1259 });12601261 Ok(properties)1262 }12631264 /// Get property permissions according to given keys.1265 pub fn filter_property_permissions(1266 collection_id: CollectionId,1267 keys: Option<Vec<PropertyKey>>,1268 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1269 let permissions = Self::property_permissions(collection_id);12701271 let key_permissions = keys1272 .map(|keys| {1273 keys.into_iter()1274 .filter_map(|key| {1275 permissions1276 .get(&key)1277 .map(|permission| PropertyKeyPermission {1278 key,1279 permission: permission.clone(),1280 })1281 })1282 .collect()1283 })1284 .unwrap_or_else(|| {1285 permissions1286 .into_iter()1287 .map(|(key, permission)| PropertyKeyPermission { key, permission })1288 .collect()1289 });12901291 Ok(key_permissions)1292 }12931294 /// Toggle `user` participation in the `collection`'s allow list.1295 pub fn toggle_allowlist(1296 collection: &CollectionHandle<T>,1297 sender: &T::CrossAccountId,1298 user: &T::CrossAccountId,1299 allowed: bool,1300 ) -> DispatchResult {1301 collection.check_is_owner_or_admin(sender)?;13021303 // =========13041305 if allowed {1306 <Allowlist<T>>::insert((collection.id, user), true);1307 } else {1308 <Allowlist<T>>::remove((collection.id, user));1309 }13101311 Ok(())1312 }13131314 /// Toggle `user` participation in the `collection`'s admin list.1315 pub fn toggle_admin(1316 collection: &CollectionHandle<T>,1317 sender: &T::CrossAccountId,1318 user: &T::CrossAccountId,1319 admin: bool,1320 ) -> DispatchResult {1321 collection.check_is_owner(sender)?;13221323 let was_admin = <IsAdmin<T>>::get((collection.id, user));1324 if was_admin == admin {1325 return Ok(());1326 }1327 let amount = <AdminAmount<T>>::get(collection.id);13281329 if admin {1330 let amount = amount1331 .checked_add(1)1332 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1333 ensure!(1334 amount <= Self::collection_admins_limit(),1335 <Error<T>>::CollectionAdminCountExceeded,1336 );13371338 // =========13391340 <AdminAmount<T>>::insert(collection.id, amount);1341 <IsAdmin<T>>::insert((collection.id, user), true);1342 } else {1343 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1344 <IsAdmin<T>>::remove((collection.id, user));1345 }13461347 Ok(())1348 }13491350 /// Merge set fields from `new_limit` to `old_limit`.1351 pub fn clamp_limits(1352 mode: CollectionMode,1353 old_limit: &CollectionLimits,1354 mut new_limit: CollectionLimits,1355 ) -> Result<CollectionLimits, DispatchError> {1356 let limits = old_limit;1357 limit_default!(old_limit, new_limit,1358 account_token_ownership_limit => ensure!(1359 new_limit <= MAX_TOKEN_OWNERSHIP,1360 <Error<T>>::CollectionLimitBoundsExceeded,1361 ),1362 sponsored_data_size => ensure!(1363 new_limit <= CUSTOM_DATA_LIMIT,1364 <Error<T>>::CollectionLimitBoundsExceeded,1365 ),13661367 sponsored_data_rate_limit => {},1368 token_limit => ensure!(1369 old_limit >= new_limit && new_limit > 0,1370 <Error<T>>::CollectionTokenLimitExceeded1371 ),13721373 sponsor_transfer_timeout(match mode {1374 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1375 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1376 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1377 }) => ensure!(1378 new_limit <= MAX_SPONSOR_TIMEOUT,1379 <Error<T>>::CollectionLimitBoundsExceeded,1380 ),1381 sponsor_approve_timeout => {},1382 owner_can_transfer => ensure!(1383 !limits.owner_can_transfer_instaled() ||1384 old_limit || !new_limit,1385 <Error<T>>::OwnerPermissionsCantBeReverted,1386 ),1387 owner_can_destroy => ensure!(1388 old_limit || !new_limit,1389 <Error<T>>::OwnerPermissionsCantBeReverted,1390 ),1391 transfers_enabled => {},1392 );1393 Ok(new_limit)1394 }13951396 /// Merge set fields from `new_permission` to `old_permission`.1397 pub fn clamp_permissions(1398 _mode: CollectionMode,1399 old_permission: &CollectionPermissions,1400 mut new_permission: CollectionPermissions,1401 ) -> Result<CollectionPermissions, DispatchError> {1402 limit_default_clone!(old_permission, new_permission,1403 access => {},1404 mint_mode => {},1405 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1406 );1407 Ok(new_permission)1408 }1409}14101411/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1412#[macro_export]1413macro_rules! unsupported {1414 ($runtime:path) => {1415 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1416 };1417}14181419/// Return weights for various worst-case operations.1420pub trait CommonWeightInfo<CrossAccountId> {1421 /// Weight of item creation.1422 fn create_item() -> Weight;14231424 /// Weight of items creation.1425 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14261427 /// Weight of items creation.1428 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14291430 /// The weight of the burning item.1431 fn burn_item() -> Weight;14321433 /// Property setting weight.1434 ///1435 /// * `amount`- The number of properties to set.1436 fn set_collection_properties(amount: u32) -> Weight;14371438 /// Collection property deletion weight.1439 ///1440 /// * `amount`- The number of properties to set.1441 fn delete_collection_properties(amount: u32) -> Weight;14421443 /// Token property setting weight.1444 ///1445 /// * `amount`- The number of properties to set.1446 fn set_token_properties(amount: u32) -> Weight;14471448 /// Token property deletion weight.1449 ///1450 /// * `amount`- The number of properties to delete.1451 fn delete_token_properties(amount: u32) -> Weight;14521453 /// Token property permissions set weight.1454 ///1455 /// * `amount`- The number of property permissions to set.1456 fn set_token_property_permissions(amount: u32) -> Weight;14571458 /// Transfer price of the token or its parts.1459 fn transfer() -> Weight;14601461 /// The price of setting the permission of the operation from another user.1462 fn approve() -> Weight;14631464 /// Transfer price from another user.1465 fn transfer_from() -> Weight;14661467 /// The price of burning a token from another user.1468 fn burn_from() -> Weight;14691470 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1471 /// whole users's balance.1472 ///1473 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1474 fn burn_recursively_self_raw() -> Weight;14751476 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1477 ///1478 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1479 fn burn_recursively_breadth_raw(amount: u32) -> Weight;14801481 /// The price of recursive burning a token.1482 ///1483 /// `max_selfs` - The maximum burning weight of the token itself.1484 /// `max_breadth` - The maximum number of nested tokens to burn.1485 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1486 Self::burn_recursively_self_raw()1487 .saturating_mul(max_selfs.max(1) as u64)1488 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1489 }14901491 /// The price of retrieving token owner1492 fn token_owner() -> Weight;1493}14941495/// Weight info extension trait for refungible pallet.1496pub trait RefungibleExtensionsWeightInfo {1497 /// Weight of token repartition.1498 fn repartition() -> Weight;1499}15001501/// Common collection operations.1502///1503/// It wraps methods in Fungible, Nonfungible and Refungible pallets1504/// and adds weight info.1505pub trait CommonCollectionOperations<T: Config> {1506 /// Create token.1507 ///1508 /// * `sender` - The user who mint the token and pays for the transaction.1509 /// * `to` - The user who will own the token.1510 /// * `data` - Token data.1511 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1512 fn create_item(1513 &self,1514 sender: T::CrossAccountId,1515 to: T::CrossAccountId,1516 data: CreateItemData,1517 nesting_budget: &dyn Budget,1518 ) -> DispatchResultWithPostInfo;15191520 /// Create multiple tokens.1521 ///1522 /// * `sender` - The user who mint the token and pays for the transaction.1523 /// * `to` - The user who will own the token.1524 /// * `data` - Token data.1525 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1526 fn create_multiple_items(1527 &self,1528 sender: T::CrossAccountId,1529 to: T::CrossAccountId,1530 data: Vec<CreateItemData>,1531 nesting_budget: &dyn Budget,1532 ) -> DispatchResultWithPostInfo;15331534 /// Create multiple tokens.1535 ///1536 /// * `sender` - The user who mint the token and pays for the transaction.1537 /// * `to` - The user who will own the token.1538 /// * `data` - Token data.1539 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1540 fn create_multiple_items_ex(1541 &self,1542 sender: T::CrossAccountId,1543 data: CreateItemExData<T::CrossAccountId>,1544 nesting_budget: &dyn Budget,1545 ) -> DispatchResultWithPostInfo;15461547 /// Burn token.1548 ///1549 /// * `sender` - The user who owns the token.1550 /// * `token` - Token id that will burned.1551 /// * `amount` - The number of parts of the token that will be burned.1552 fn burn_item(1553 &self,1554 sender: T::CrossAccountId,1555 token: TokenId,1556 amount: u128,1557 ) -> DispatchResultWithPostInfo;15581559 /// Burn token and all nested tokens recursievly.1560 ///1561 /// * `sender` - The user who owns the token.1562 /// * `token` - Token id that will burned.1563 /// * `self_budget` - The budget that can be spent on burning tokens.1564 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1565 fn burn_item_recursively(1566 &self,1567 sender: T::CrossAccountId,1568 token: TokenId,1569 self_budget: &dyn Budget,1570 breadth_budget: &dyn Budget,1571 ) -> DispatchResultWithPostInfo;15721573 /// Set collection properties.1574 ///1575 /// * `sender` - Must be either the owner of the collection or its admin.1576 /// * `properties` - Properties to be set.1577 fn set_collection_properties(1578 &self,1579 sender: T::CrossAccountId,1580 properties: Vec<Property>,1581 ) -> DispatchResultWithPostInfo;15821583 /// Delete collection properties.1584 ///1585 /// * `sender` - Must be either the owner of the collection or its admin.1586 /// * `properties` - The properties to be removed.1587 fn delete_collection_properties(1588 &self,1589 sender: &T::CrossAccountId,1590 property_keys: Vec<PropertyKey>,1591 ) -> DispatchResultWithPostInfo;15921593 /// Set token properties.1594 ///1595 /// The appropriate [`PropertyPermission`] for the token property1596 /// must be set with [`Self::set_token_property_permissions`].1597 ///1598 /// * `sender` - Must be either the owner of the token or its admin.1599 /// * `token_id` - The token for which the properties are being set.1600 /// * `properties` - Properties to be set.1601 /// * `budget` - Budget for setting properties.1602 fn set_token_properties(1603 &self,1604 sender: T::CrossAccountId,1605 token_id: TokenId,1606 properties: Vec<Property>,1607 budget: &dyn Budget,1608 ) -> DispatchResultWithPostInfo;16091610 /// Remove token properties.1611 ///1612 /// The appropriate [`PropertyPermission`] for the token property1613 /// must be set with [`Self::set_token_property_permissions`].1614 ///1615 /// * `sender` - Must be either the owner of the token or its admin.1616 /// * `token_id` - The token for which the properties are being remove.1617 /// * `property_keys` - Keys to remove corresponding properties.1618 /// * `budget` - Budget for removing properties.1619 fn delete_token_properties(1620 &self,1621 sender: T::CrossAccountId,1622 token_id: TokenId,1623 property_keys: Vec<PropertyKey>,1624 budget: &dyn Budget,1625 ) -> DispatchResultWithPostInfo;16261627 /// Set token property permissions.1628 ///1629 /// * `sender` - Must be either the owner of the token or its admin.1630 /// * `token_id` - The token for which the properties are being set.1631 /// * `property_permissions` - Property permissions to be set.1632 /// * `budget` - Budget for setting properties.1633 fn set_token_property_permissions(1634 &self,1635 sender: &T::CrossAccountId,1636 property_permissions: Vec<PropertyKeyPermission>,1637 ) -> DispatchResultWithPostInfo;16381639 /// Transfer amount of token pieces.1640 ///1641 /// * `sender` - Donor user.1642 /// * `to` - Recepient user.1643 /// * `token` - The token of which parts are being sent.1644 /// * `amount` - The number of parts of the token that will be transferred.1645 /// * `budget` - The maximum budget that can be spent on the transfer.1646 fn transfer(1647 &self,1648 sender: T::CrossAccountId,1649 to: T::CrossAccountId,1650 token: TokenId,1651 amount: u128,1652 budget: &dyn Budget,1653 ) -> DispatchResultWithPostInfo;16541655 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1656 ///1657 /// * `sender` - The user who grants access to the token.1658 /// * `spender` - The user to whom the rights are granted.1659 /// * `token` - The token to which access is granted.1660 /// * `amount` - The amount of pieces that another user can dispose of.1661 fn approve(1662 &self,1663 sender: T::CrossAccountId,1664 spender: T::CrossAccountId,1665 token: TokenId,1666 amount: u128,1667 ) -> DispatchResultWithPostInfo;16681669 /// Send parts of a token owned by another user.1670 ///1671 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1672 ///1673 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1674 /// * `from` - The user who owns the token.1675 /// * `to` - Recepient user.1676 /// * `token` - The token of which parts are being sent.1677 /// * `amount` - The number of parts of the token that will be transferred.1678 /// * `budget` - The maximum budget that can be spent on the transfer.1679 fn transfer_from(1680 &self,1681 sender: T::CrossAccountId,1682 from: T::CrossAccountId,1683 to: T::CrossAccountId,1684 token: TokenId,1685 amount: u128,1686 budget: &dyn Budget,1687 ) -> DispatchResultWithPostInfo;16881689 /// Burn parts of a token owned by another user.1690 ///1691 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1692 ///1693 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1694 /// * `from` - The user who owns the token.1695 /// * `token` - The token of which parts are being sent.1696 /// * `amount` - The number of parts of the token that will be transferred.1697 /// * `budget` - The maximum budget that can be spent on the burn.1698 fn burn_from(1699 &self,1700 sender: T::CrossAccountId,1701 from: T::CrossAccountId,1702 token: TokenId,1703 amount: u128,1704 budget: &dyn Budget,1705 ) -> DispatchResultWithPostInfo;17061707 /// Check permission to nest token.1708 ///1709 /// * `sender` - The user who initiated the check.1710 /// * `from` - The token that is checked for embedding.1711 /// * `under` - Token under which to check.1712 /// * `budget` - The maximum budget that can be spent on the check.1713 fn check_nesting(1714 &self,1715 sender: T::CrossAccountId,1716 from: (CollectionId, TokenId),1717 under: TokenId,1718 budget: &dyn Budget,1719 ) -> DispatchResult;17201721 /// Nest one token into another.1722 ///1723 /// * `under` - Token holder.1724 /// * `to_nest` - Nested token.1725 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17261727 /// Unnest token.1728 ///1729 /// * `under` - Token holder.1730 /// * `to_nest` - Token to unnest.1731 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17321733 /// Get all user tokens.1734 ///1735 /// * `account` - Account for which you need to get tokens.1736 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17371738 /// Get all the tokens in the collection.1739 fn collection_tokens(&self) -> Vec<TokenId>;17401741 /// Check if the token exists.1742 ///1743 /// * `token` - Id token to check.1744 fn token_exists(&self, token: TokenId) -> bool;17451746 /// Get the id of the last minted token.1747 fn last_token_id(&self) -> TokenId;17481749 /// Get the owner of the token.1750 ///1751 /// * `token` - The token for which you need to find out the owner.1752 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17531754 /// Returns 10 tokens owners in no particular order.1755 ///1756 /// * `token` - The token for which you need to find out the owners.1757 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17581759 /// Get the value of the token property by key.1760 ///1761 /// * `token` - Token with the property to get.1762 /// * `key` - Property name.1763 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17641765 /// Get a set of token properties by key vector.1766 ///1767 /// * `token` - Token with the property to get.1768 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1769 /// then all properties are returned.1770 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17711772 /// Amount of unique collection tokens1773 fn total_supply(&self) -> u32;17741775 /// Amount of different tokens account has.1776 ///1777 /// * `account` - The account for which need to get the balance.1778 fn account_balance(&self, account: T::CrossAccountId) -> u32;17791780 /// Amount of specific token account have.1781 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;17821783 /// Amount of token pieces1784 fn total_pieces(&self, token: TokenId) -> Option<u128>;17851786 /// Get the number of parts of the token that a trusted user can manage.1787 ///1788 /// * `sender` - Trusted user.1789 /// * `spender` - Owner of the token.1790 /// * `token` - The token for which to get the value.1791 fn allowance(1792 &self,1793 sender: T::CrossAccountId,1794 spender: T::CrossAccountId,1795 token: TokenId,1796 ) -> u128;17971798 /// Get extension for RFT collection.1799 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1800}18011802/// Extension for RFT collection.1803pub trait RefungibleExtensions<T>1804where1805 T: Config,1806{1807 /// Change the number of parts of the token.1808 ///1809 /// When the value changes down, this function is equivalent to burning parts of the token.1810 ///1811 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1812 /// * `token` - The token for which you want to change the number of parts.1813 /// * `amount` - The new value of the parts of the token.1814 fn repartition(1815 &self,1816 sender: &T::CrossAccountId,1817 token: TokenId,1818 amount: u128,1819 ) -> DispatchResultWithPostInfo;1820}18211822/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1823///1824/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1825pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1826 let post_info = PostDispatchInfo {1827 actual_weight: Some(weight),1828 pays_fee: Pays::Yes,1829 };1830 match res {1831 Ok(()) => Ok(post_info),1832 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1833 }1834}18351836impl<T: Config> From<PropertiesError> for Error<T> {1837 fn from(error: PropertiesError) -> Self {1838 match error {1839 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1840 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1841 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1842 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1843 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1844 }1845 }1846}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};116117pub use pallet::*;118use sp_core::H160;119use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};120#[cfg(feature = "runtime-benchmarks")]121pub mod benchmarking;122pub mod dispatch;123pub mod erc;124pub mod eth;125pub mod weights;126127/// Weight info.128pub type SelfWeightOf<T> = <T as Config>::WeightInfo;129130/// Collection handle contains information about collection data and id.131/// Also provides functionality to count consumed gas.132///133/// CollectionHandle is used as a generic wrapper for collections of all types.134/// It allows to perform common operations and queries on any collection type,135/// both completely general for all, as well as their respective implementations of [`CommonCollectionOperations`].136#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]137pub struct CollectionHandle<T: Config> {138 /// Collection id139 pub id: CollectionId,140 collection: Collection<T::AccountId>,141 /// Substrate recorder for counting consumed gas142 pub recorder: SubstrateRecorder<T>,143}144145impl<T: Config> WithRecorder<T> for CollectionHandle<T> {146 fn recorder(&self) -> &SubstrateRecorder<T> {147 &self.recorder148 }149 fn into_recorder(self) -> SubstrateRecorder<T> {150 self.recorder151 }152}153154impl<T: Config> CollectionHandle<T> {155 /// Same as [CollectionHandle::new] but with an explicit gas limit.156 pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {157 <CollectionById<T>>::get(id).map(|collection| Self {158 id,159 collection,160 recorder: SubstrateRecorder::new(gas_limit),161 })162 }163164 /// Same as [CollectionHandle::new] but with an existed [`SubstrateRecorder`].165 pub fn new_with_recorder(id: CollectionId, recorder: SubstrateRecorder<T>) -> Option<Self> {166 <CollectionById<T>>::get(id).map(|collection| Self {167 id,168 collection,169 recorder,170 })171 }172173 /// Retrives collection data from storage and creates collection handle with default parameters.174 /// If collection not found return `None`175 pub fn new(id: CollectionId) -> Option<Self> {176 Self::new_with_gas_limit(id, u64::MAX)177 }178179 /// Same as [`CollectionHandle::new`] but if collection not found [CollectionNotFound](Error::CollectionNotFound) returned.180 pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {181 Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)182 }183184 /// Consume gas for reading.185 pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {186 self.recorder187 .consume_gas(T::GasWeightMapping::weight_to_gas(188 <T as frame_system::Config>::DbWeight::get()189 .read190 .saturating_mul(reads),191 ))192 }193194 /// Consume gas for writing.195 pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {196 self.recorder197 .consume_gas(T::GasWeightMapping::weight_to_gas(198 <T as frame_system::Config>::DbWeight::get()199 .write200 .saturating_mul(writes),201 ))202 }203204 /// Consume gas for reading and writing.205 pub fn consume_store_reads_and_writes(206 &self,207 reads: u64,208 writes: u64,209 ) -> evm_coder::execution::Result<()> {210 let weight = <T as frame_system::Config>::DbWeight::get();211 let reads = weight.read.saturating_mul(reads);212 let writes = weight.read.saturating_mul(writes);213 self.recorder214 .consume_gas(T::GasWeightMapping::weight_to_gas(215 reads.saturating_add(writes),216 ))217 }218219 /// Save collection to storage.220 pub fn save(&self) -> DispatchResult {221 <CollectionById<T>>::insert(self.id, &self.collection);222 Ok(())223 }224225 /// Set collection sponsor.226 ///227 /// Unique collections allows sponsoring for certain actions.228 /// This method allows you to set the sponsor of the collection.229 /// In order for sponsorship to become active, it must be confirmed through [`Self::confirm_sponsorship`].230 pub fn set_sponsor(&mut self, sponsor: T::AccountId) -> DispatchResult {231 self.collection.sponsorship = SponsorshipState::Unconfirmed(sponsor);232 Ok(())233 }234235 /// Confirm sponsorship236 ///237 /// In order for the sponsorship to become active, the user set as the sponsor must confirm their participation.238 /// Before confirming sponsorship, the user must be specified as the sponsor of the collection via [`Self::set_sponsor`].239 pub fn confirm_sponsorship(&mut self, sender: &T::AccountId) -> Result<bool, DispatchError> {240 if self.collection.sponsorship.pending_sponsor() != Some(sender) {241 return Ok(false);242 }243244 self.collection.sponsorship = SponsorshipState::Confirmed(sender.clone());245 Ok(true)246 }247248 /// Remove collection sponsor.249 pub fn remove_sponsor(&mut self) -> DispatchResult {250 self.collection.sponsorship = SponsorshipState::Disabled;251 Ok(())252 }253254 /// Checks that the collection was created with, and must be operated upon through **Unique API**.255 /// Now check only the `external_collection` flag and if it's **true**, then return [`Error::CollectionIsExternal`] error.256 pub fn check_is_internal(&self) -> DispatchResult {257 if self.external_collection {258 return Err(<Error<T>>::CollectionIsExternal)?;259 }260261 Ok(())262 }263264 /// Checks that the collection was created with, and must be operated upon through an **assimilated API**.265 /// Now check only the `external_collection` flag and if it's **false**, then return [`Error::CollectionIsInternal`] error.266 pub fn check_is_external(&self) -> DispatchResult {267 if !self.external_collection {268 return Err(<Error<T>>::CollectionIsInternal)?;269 }270271 Ok(())272 }273}274275impl<T: Config> Deref for CollectionHandle<T> {276 type Target = Collection<T::AccountId>;277278 fn deref(&self) -> &Self::Target {279 &self.collection280 }281}282283impl<T: Config> DerefMut for CollectionHandle<T> {284 fn deref_mut(&mut self) -> &mut Self::Target {285 &mut self.collection286 }287}288289impl<T: Config> CollectionHandle<T> {290 /// Checks if the `user` is the owner of the collection.291 pub fn check_is_owner(&self, user: &T::CrossAccountId) -> DispatchResult {292 ensure!(*user.as_sub() == self.owner, <Error<T>>::NoPermission);293 Ok(())294 }295296 /// Returns **true** if the `user` is the owner or administrator of the collection.297 pub fn is_owner_or_admin(&self, user: &T::CrossAccountId) -> bool {298 *user.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, user))299 }300301 /// Checks if the `user` is the owner or administrator of the collection.302 pub fn check_is_owner_or_admin(&self, user: &T::CrossAccountId) -> DispatchResult {303 ensure!(self.is_owner_or_admin(user), <Error<T>>::NoPermission);304 Ok(())305 }306307 /// Return **true** if `user` was not allowed to have tokens, and he can ignore such restrictions.308 pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {309 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)310 }311312 /// Return **true** if `user` does not have enough token parts, and he can ignore such restrictions.313 pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {314 self.limits.owner_can_transfer() && self.is_owner_or_admin(user)315 }316317 /// Checks if the user is in the allow list. If not [Error::AddressNotInAllowlist] returns.318 pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {319 ensure!(320 <Allowlist<T>>::get((self.id, user)),321 <Error<T>>::AddressNotInAllowlist322 );323 Ok(())324 }325326 /// Changes collection owner to another account327 /// #### Store read/writes328 /// 1 writes329 fn set_owner_internal(330 &mut self,331 caller: T::CrossAccountId,332 new_owner: T::CrossAccountId,333 ) -> DispatchResult {334 self.check_is_owner(&caller)?;335 self.collection.owner = new_owner.as_sub().clone();336 self.save()337 }338}339340#[frame_support::pallet]341pub mod pallet {342 use super::*;343 use pallet_evm::account;344 use dispatch::CollectionDispatch;345 use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};346 use frame_system::pallet_prelude::*;347 use frame_support::traits::Currency;348 use up_data_structs::{TokenId, mapping::TokenAddressMapping};349 use scale_info::TypeInfo;350 use weights::WeightInfo;351352 #[pallet::config]353 pub trait Config:354 frame_system::Config355 + pallet_evm_coder_substrate::Config356 + pallet_evm::Config357 + TypeInfo358 + account::Config359 {360 /// Weight information for functions of this pallet.361 type WeightInfo: WeightInfo;362363 /// Events compatible with [`frame_system::Config::Event`].364 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;365366 /// Handler of accounts and payment.367 type Currency: Currency<Self::AccountId>;368369 /// Set price to create a collection.370 #[pallet::constant]371 type CollectionCreationPrice: Get<372 <<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,373 >;374375 /// Dispatcher of operations on collections.376 type CollectionDispatch: CollectionDispatch<Self>;377378 /// Account which holds the chain's treasury.379 type TreasuryAccountId: Get<Self::AccountId>;380381 /// Address under which the CollectionHelper contract would be available.382 type ContractAddress: Get<H160>;383384 /// Mapper for token addresses to Ethereum addresses.385 type EvmTokenAddressMapping: TokenAddressMapping<H160>;386387 /// Mapper for token addresses to [`CrossAccountId`].388 type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;389 }390391 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);392393 #[pallet::pallet]394 #[pallet::storage_version(STORAGE_VERSION)]395 #[pallet::generate_store(pub(super) trait Store)]396 pub struct Pallet<T>(_);397398 #[pallet::extra_constants]399 impl<T: Config> Pallet<T> {400 /// Maximum admins per collection.401 pub fn collection_admins_limit() -> u32 {402 COLLECTION_ADMINS_LIMIT403 }404 }405406 #[pallet::event]407 #[pallet::generate_deposit(pub fn deposit_event)]408 pub enum Event<T: Config> {409 /// New collection was created410 CollectionCreated(411 /// Globally unique identifier of newly created collection.412 CollectionId,413 /// [`CollectionMode`] converted into _u8_.414 u8,415 /// Collection owner.416 T::AccountId,417 ),418419 /// New collection was destroyed420 CollectionDestroyed(421 /// Globally unique identifier of collection.422 CollectionId,423 ),424425 /// New item was created.426 ItemCreated(427 /// Id of the collection where item was created.428 CollectionId,429 /// Id of an item. Unique within the collection.430 TokenId,431 /// Owner of newly created item432 T::CrossAccountId,433 /// Always 1 for NFT434 u128,435 ),436437 /// Collection item was burned.438 ItemDestroyed(439 /// Id of the collection where item was destroyed.440 CollectionId,441 /// Identifier of burned NFT.442 TokenId,443 /// Which user has destroyed its tokens.444 T::CrossAccountId,445 /// Amount of token pieces destroed. Always 1 for NFT.446 u128,447 ),448449 /// Item was transferred450 Transfer(451 /// Id of collection to which item is belong.452 CollectionId,453 /// Id of an item.454 TokenId,455 /// Original owner of item.456 T::CrossAccountId,457 /// New owner of item.458 T::CrossAccountId,459 /// Amount of token pieces transfered. Always 1 for NFT.460 u128,461 ),462463 /// Amount pieces of token owned by `sender` was approved for `spender`.464 Approved(465 /// Id of collection to which item is belong.466 CollectionId,467 /// Id of an item.468 TokenId,469 /// Original owner of item.470 T::CrossAccountId,471 /// Id for which the approval was granted.472 T::CrossAccountId,473 /// Amount of token pieces transfered. Always 1 for NFT.474 u128,475 ),476477 /// The colletion property has been added or edited.478 CollectionPropertySet(479 /// Id of collection to which property has been set.480 CollectionId,481 /// The property that was set.482 PropertyKey,483 ),484485 /// The property has been deleted.486 CollectionPropertyDeleted(487 /// Id of collection to which property has been deleted.488 CollectionId,489 /// The property that was deleted.490 PropertyKey,491 ),492493 /// The token property has been added or edited.494 TokenPropertySet(495 /// Identifier of the collection whose token has the property set.496 CollectionId,497 /// The token for which the property was set.498 TokenId,499 /// The property that was set.500 PropertyKey,501 ),502503 /// The token property has been deleted.504 TokenPropertyDeleted(505 /// Identifier of the collection whose token has the property deleted.506 CollectionId,507 /// The token for which the property was deleted.508 TokenId,509 /// The property that was deleted.510 PropertyKey,511 ),512513 /// The token property permission of a collection has been set.514 PropertyPermissionSet(515 /// ID of collection to which property permission has been set.516 CollectionId,517 /// The property permission that was set.518 PropertyKey,519 ),520 }521522 #[pallet::error]523 pub enum Error<T> {524 /// This collection does not exist.525 CollectionNotFound,526 /// Sender parameter and item owner must be equal.527 MustBeTokenOwner,528 /// No permission to perform action529 NoPermission,530 /// Destroying only empty collections is allowed531 CantDestroyNotEmptyCollection,532 /// Collection is not in mint mode.533 PublicMintingNotAllowed,534 /// Address is not in allow list.535 AddressNotInAllowlist,536537 /// Collection name can not be longer than 63 char.538 CollectionNameLimitExceeded,539 /// Collection description can not be longer than 255 char.540 CollectionDescriptionLimitExceeded,541 /// Token prefix can not be longer than 15 char.542 CollectionTokenPrefixLimitExceeded,543 /// Total collections bound exceeded.544 TotalCollectionsLimitExceeded,545 /// Exceeded max admin count546 CollectionAdminCountExceeded,547 /// Collection limit bounds per collection exceeded548 CollectionLimitBoundsExceeded,549 /// Tried to enable permissions which are only permitted to be disabled550 OwnerPermissionsCantBeReverted,551 /// Collection settings not allowing items transferring552 TransferNotAllowed,553 /// Account token limit exceeded per collection554 AccountTokenLimitExceeded,555 /// Collection token limit exceeded556 CollectionTokenLimitExceeded,557 /// Metadata flag frozen558 MetadataFlagFrozen,559560 /// Item does not exist561 TokenNotFound,562 /// Item is balance not enough563 TokenValueTooLow,564 /// Requested value is more than the approved565 ApprovedValueTooLow,566 /// Tried to approve more than owned567 CantApproveMoreThanOwned,568569 /// Can't transfer tokens to ethereum zero address570 AddressIsZero,571572 /// The operation is not supported573 UnsupportedOperation,574575 /// Insufficient funds to perform an action576 NotSufficientFounds,577578 /// User does not satisfy the nesting rule579 UserIsNotAllowedToNest,580 /// Only tokens from specific collections may nest tokens under this one581 SourceCollectionIsNotAllowedToNest,582583 /// Tried to store more data than allowed in collection field584 CollectionFieldSizeExceeded,585586 /// Tried to store more property data than allowed587 NoSpaceForProperty,588589 /// Tried to store more property keys than allowed590 PropertyLimitReached,591592 /// Property key is too long593 PropertyKeyIsTooLong,594595 /// Only ASCII letters, digits, and symbols `_`, `-`, and `.` are allowed596 InvalidCharacterInPropertyKey,597598 /// Empty property keys are forbidden599 EmptyPropertyKey,600601 /// Tried to access an external collection with an internal API602 CollectionIsExternal,603604 /// Tried to access an internal collection with an external API605 CollectionIsInternal,606 }607608 /// Storage of the count of created collections. Essentially contains the last collection ID.609 #[pallet::storage]610 pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;611612 /// Storage of the count of deleted collections.613 #[pallet::storage]614 pub type DestroyedCollectionCount<T> =615 StorageValue<Value = CollectionId, QueryKind = ValueQuery>;616617 /// Storage of collection info.618 #[pallet::storage]619 pub type CollectionById<T> = StorageMap<620 Hasher = Blake2_128Concat,621 Key = CollectionId,622 Value = Collection<<T as frame_system::Config>::AccountId>,623 QueryKind = OptionQuery,624 >;625626 /// Storage of collection properties.627 #[pallet::storage]628 #[pallet::getter(fn collection_properties)]629 pub type CollectionProperties<T> = StorageMap<630 Hasher = Blake2_128Concat,631 Key = CollectionId,632 Value = Properties,633 QueryKind = ValueQuery,634 OnEmpty = up_data_structs::CollectionProperties,635 >;636637 /// Storage of token property permissions of a collection.638 #[pallet::storage]639 #[pallet::getter(fn property_permissions)]640 pub type CollectionPropertyPermissions<T> = StorageMap<641 Hasher = Blake2_128Concat,642 Key = CollectionId,643 Value = PropertiesPermissionMap,644 QueryKind = ValueQuery,645 >;646647 /// Storage of the amount of collection admins.648 #[pallet::storage]649 pub type AdminAmount<T> = StorageMap<650 Hasher = Blake2_128Concat,651 Key = CollectionId,652 Value = u32,653 QueryKind = ValueQuery,654 >;655656 /// List of collection admins.657 #[pallet::storage]658 pub type IsAdmin<T: Config> = StorageNMap<659 Key = (660 Key<Blake2_128Concat, CollectionId>,661 Key<Blake2_128Concat, T::CrossAccountId>,662 ),663 Value = bool,664 QueryKind = ValueQuery,665 >;666667 /// Allowlisted collection users.668 #[pallet::storage]669 pub type Allowlist<T: Config> = StorageNMap<670 Key = (671 Key<Blake2_128Concat, CollectionId>,672 Key<Blake2_128Concat, T::CrossAccountId>,673 ),674 Value = bool,675 QueryKind = ValueQuery,676 >;677678 /// Not used by code, exists only to provide some types to metadata.679 #[pallet::storage]680 pub type DummyStorageValue<T: Config> = StorageValue<681 Value = (682 CollectionStats,683 CollectionId,684 TokenId,685 TokenChild,686 PhantomType<(687 TokenData<T::CrossAccountId>,688 RpcCollection<T::AccountId>,689 // RMRK690 RmrkCollectionInfo<T::AccountId>,691 RmrkInstanceInfo<T::AccountId>,692 RmrkResourceInfo,693 RmrkPropertyInfo,694 RmrkBaseInfo<T::AccountId>,695 RmrkPartType,696 RmrkBoundedTheme,697 RmrkNftChild,698 )>,699 ),700 QueryKind = OptionQuery,701 >;702703 #[pallet::hooks]704 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {705 fn on_runtime_upgrade() -> Weight {706 StorageVersion::new(1).put::<Pallet<T>>();707708 0709 }710 }711}712713impl<T: Config> Pallet<T> {714 /// Enshure that receiver address is correct.715 ///716 /// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens.717 pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {718 ensure!(719 &T::CrossAccountId::from_eth(H160([0; 20])) != receiver,720 <Error<T>>::AddressIsZero721 );722 Ok(())723 }724725 /// Get a vector of collection admins.726 pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {727 <IsAdmin<T>>::iter_prefix((collection,))728 .map(|(a, _)| a)729 .collect()730 }731732 /// Get a vector of users allowed to mint tokens.733 pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {734 <Allowlist<T>>::iter_prefix((collection,))735 .map(|(a, _)| a)736 .collect()737 }738739 /// Is `user` allowed to mint token in `collection`.740 pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {741 <Allowlist<T>>::get((collection, user))742 }743744 /// Get statistics of collections.745 pub fn collection_stats() -> CollectionStats {746 let created = <CreatedCollectionCount<T>>::get();747 let destroyed = <DestroyedCollectionCount<T>>::get();748 CollectionStats {749 created: created.0,750 destroyed: destroyed.0,751 alive: created.0 - destroyed.0,752 }753 }754755 /// Get the effective limits for the collection.756 pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {757 let collection = <CollectionById<T>>::get(collection)?;758 let limits = collection.limits;759 let effective_limits = CollectionLimits {760 account_token_ownership_limit: Some(limits.account_token_ownership_limit()),761 sponsored_data_size: Some(limits.sponsored_data_size()),762 sponsored_data_rate_limit: Some(763 limits764 .sponsored_data_rate_limit765 .unwrap_or(SponsoringRateLimit::SponsoringDisabled),766 ),767 token_limit: Some(limits.token_limit()),768 sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(769 match collection.mode {770 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,771 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,772 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,773 },774 )),775 sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),776 owner_can_transfer: Some(limits.owner_can_transfer()),777 owner_can_destroy: Some(limits.owner_can_destroy()),778 transfers_enabled: Some(limits.transfers_enabled()),779 };780781 Some(effective_limits)782 }783784 /// Returns information about the `collection` adapted for rpc.785 pub fn rpc_collection(collection: CollectionId) -> Option<RpcCollection<T::AccountId>> {786 let Collection {787 name,788 description,789 owner,790 mode,791 token_prefix,792 sponsorship,793 limits,794 permissions,795 external_collection,796 } = <CollectionById<T>>::get(collection)?;797798 let token_property_permissions = <CollectionPropertyPermissions<T>>::get(collection)799 .into_iter()800 .map(|(key, permission)| PropertyKeyPermission { key, permission })801 .collect();802803 let properties = <CollectionProperties<T>>::get(collection)804 .into_iter()805 .map(|(key, value)| Property { key, value })806 .collect();807808 let permissions = CollectionPermissions {809 access: Some(permissions.access()),810 mint_mode: Some(permissions.mint_mode()),811 nesting: Some(permissions.nesting().clone()),812 };813814 Some(RpcCollection {815 name: name.into_inner(),816 description: description.into_inner(),817 owner,818 mode,819 token_prefix: token_prefix.into_inner(),820 sponsorship,821 limits,822 permissions,823 token_property_permissions,824 properties,825 read_only: external_collection,826 })827 }828}829830macro_rules! limit_default {831 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{832 $(833 if let Some($new) = $new.$field {834 let $old = $old.$field($($arg)?);835 let _ = $new;836 let _ = $old;837 $check838 } else {839 $new.$field = $old.$field840 }841 )*842 }};843}844macro_rules! limit_default_clone {845 ($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{846 $(847 if let Some($new) = $new.$field.clone() {848 let $old = $old.$field($($arg)?);849 let _ = $new;850 let _ = $old;851 $check852 } else {853 $new.$field = $old.$field.clone()854 }855 )*856 }};857}858859impl<T: Config> Pallet<T> {860 /// Create new collection.861 ///862 /// * `owner` - The owner of the collection.863 /// * `data` - Description of the created collection.864 /// * `is_external` - Marks that collection managet by not "Unique network".865 pub fn init_collection(866 owner: T::CrossAccountId,867 data: CreateCollectionData<T::AccountId>,868 is_external: bool,869 ) -> Result<CollectionId, DispatchError> {870 {871 ensure!(872 data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,873 Error::<T>::CollectionTokenPrefixLimitExceeded874 );875 }876877 let created_count = <CreatedCollectionCount<T>>::get()878 .0879 .checked_add(1)880 .ok_or(ArithmeticError::Overflow)?;881 let destroyed_count = <DestroyedCollectionCount<T>>::get().0;882 let id = CollectionId(created_count);883884 // bound Total number of collections885 ensure!(886 created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,887 <Error<T>>::TotalCollectionsLimitExceeded888 );889890 // =========891892 let collection = Collection {893 owner: owner.as_sub().clone(),894 name: data.name,895 mode: data.mode.clone(),896 description: data.description,897 token_prefix: data.token_prefix,898 sponsorship: data899 .pending_sponsor900 .map(SponsorshipState::Unconfirmed)901 .unwrap_or_default(),902 limits: data903 .limits904 .map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))905 .unwrap_or_else(|| Ok(CollectionLimits::default()))?,906 permissions: data907 .permissions908 .map(|permissions| {909 Self::clamp_permissions(data.mode.clone(), &Default::default(), permissions)910 })911 .unwrap_or_else(|| Ok(CollectionPermissions::default()))?,912 external_collection: is_external,913 };914915 let mut collection_properties = up_data_structs::CollectionProperties::get();916 collection_properties917 .try_set_from_iter(data.properties.into_iter())918 .map_err(<Error<T>>::from)?;919920 CollectionProperties::<T>::insert(id, collection_properties);921922 let mut token_props_permissions = PropertiesPermissionMap::new();923 token_props_permissions924 .try_set_from_iter(data.token_property_permissions.into_iter())925 .map_err(<Error<T>>::from)?;926927 CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);928929 // Take a (non-refundable) deposit of collection creation930 {931 let mut imbalance =932 <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();933 imbalance.subsume(934 <<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(935 &T::TreasuryAccountId::get(),936 T::CollectionCreationPrice::get(),937 ),938 );939 <T as Config>::Currency::settle(940 owner.as_sub(),941 imbalance,942 WithdrawReasons::TRANSFER,943 ExistenceRequirement::KeepAlive,944 )945 .map_err(|_| Error::<T>::NotSufficientFounds)?;946 }947948 <CreatedCollectionCount<T>>::put(created_count);949 <Pallet<T>>::deposit_event(Event::CollectionCreated(950 id,951 data.mode.id(),952 owner.as_sub().clone(),953 ));954 <PalletEvm<T>>::deposit_log(955 erc::CollectionHelpersEvents::CollectionCreated {956 owner: *owner.as_eth(),957 collection_id: eth::collection_id_to_address(id),958 }959 .to_log(T::ContractAddress::get()),960 );961 <CollectionById<T>>::insert(id, collection);962 Ok(id)963 }964965 /// Destroy collection.966 ///967 /// * `collection` - Collection handler.968 /// * `sender` - The owner or administrator of the collection.969 pub fn destroy_collection(970 collection: CollectionHandle<T>,971 sender: &T::CrossAccountId,972 ) -> DispatchResult {973 ensure!(974 collection.limits.owner_can_destroy(),975 <Error<T>>::NoPermission,976 );977 collection.check_is_owner(sender)?;978979 let destroyed_collections = <DestroyedCollectionCount<T>>::get()980 .0981 .checked_add(1)982 .ok_or(ArithmeticError::Overflow)?;983984 // =========985986 <DestroyedCollectionCount<T>>::put(destroyed_collections);987 <CollectionById<T>>::remove(collection.id);988 <AdminAmount<T>>::remove(collection.id);989 let _ = <IsAdmin<T>>::clear_prefix((collection.id,), u32::MAX, None);990 let _ = <Allowlist<T>>::clear_prefix((collection.id,), u32::MAX, None);991 <CollectionProperties<T>>::remove(collection.id);992993 <Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));994 Ok(())995 }996997 /// Set collection property.998 ///999 /// * `collection` - Collection handler.1000 /// * `sender` - The owner or administrator of the collection.1001 /// * `property` - The property to set.1002 pub fn set_collection_property(1003 collection: &CollectionHandle<T>,1004 sender: &T::CrossAccountId,1005 property: Property,1006 ) -> DispatchResult {1007 collection.check_is_owner_or_admin(sender)?;10081009 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1010 let property = property.clone();1011 properties.try_set(property.key, property.value)1012 })1013 .map_err(<Error<T>>::from)?;10141015 Self::deposit_event(Event::CollectionPropertySet(collection.id, property.key));10161017 Ok(())1018 }10191020 /// Set scouped collection property.1021 ///1022 /// * `collection_id` - ID of the collection for which the property is being set.1023 /// * `scope` - Property scope.1024 /// * `property` - The property to set.1025 pub fn set_scoped_collection_property(1026 collection_id: CollectionId,1027 scope: PropertyScope,1028 property: Property,1029 ) -> DispatchResult {1030 CollectionProperties::<T>::try_mutate(collection_id, |properties| {1031 properties.try_scoped_set(scope, property.key, property.value)1032 })1033 .map_err(<Error<T>>::from)?;10341035 Ok(())1036 }10371038 /// Set scouped collection properties.1039 ///1040 /// * `collection_id` - ID of the collection for which the properties is being set.1041 /// * `scope` - Property scope.1042 /// * `properties` - The properties to set.1043 pub fn set_scoped_collection_properties(1044 collection_id: CollectionId,1045 scope: PropertyScope,1046 properties: impl Iterator<Item = Property>,1047 ) -> DispatchResult {1048 CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {1049 stored_properties.try_scoped_set_from_iter(scope, properties)1050 })1051 .map_err(<Error<T>>::from)?;10521053 Ok(())1054 }10551056 /// Set collection properties.1057 ///1058 /// * `collection` - Collection handler.1059 /// * `sender` - The owner or administrator of the collection.1060 /// * `properties` - The properties to set.1061 #[transactional]1062 pub fn set_collection_properties(1063 collection: &CollectionHandle<T>,1064 sender: &T::CrossAccountId,1065 properties: Vec<Property>,1066 ) -> DispatchResult {1067 for property in properties {1068 Self::set_collection_property(collection, sender, property)?;1069 }10701071 Ok(())1072 }10731074 /// Delete collection property.1075 ///1076 /// * `collection` - Collection handler.1077 /// * `sender` - The owner or administrator of the collection.1078 /// * `property` - The property to delete.1079 pub fn delete_collection_property(1080 collection: &CollectionHandle<T>,1081 sender: &T::CrossAccountId,1082 property_key: PropertyKey,1083 ) -> DispatchResult {1084 collection.check_is_owner_or_admin(sender)?;10851086 CollectionProperties::<T>::try_mutate(collection.id, |properties| {1087 properties.remove(&property_key)1088 })1089 .map_err(<Error<T>>::from)?;10901091 Self::deposit_event(Event::CollectionPropertyDeleted(1092 collection.id,1093 property_key,1094 ));10951096 Ok(())1097 }10981099 /// Delete collection properties.1100 ///1101 /// * `collection` - Collection handler.1102 /// * `sender` - The owner or administrator of the collection.1103 /// * `properties` - The properties to delete.1104 #[transactional]1105 pub fn delete_collection_properties(1106 collection: &CollectionHandle<T>,1107 sender: &T::CrossAccountId,1108 property_keys: Vec<PropertyKey>,1109 ) -> DispatchResult {1110 for key in property_keys {1111 Self::delete_collection_property(collection, sender, key)?;1112 }11131114 Ok(())1115 }11161117 /// Set collection propetry permission without any checks.1118 ///1119 /// Used for migrations.1120 ///1121 /// * `collection` - Collection handler.1122 /// * `property_permissions` - Property permissions.1123 pub fn set_property_permission_unchecked(1124 collection: CollectionId,1125 property_permission: PropertyKeyPermission,1126 ) -> DispatchResult {1127 <CollectionPropertyPermissions<T>>::try_mutate(collection, |permissions| {1128 permissions.try_set(property_permission.key, property_permission.permission)1129 })1130 .map_err(<Error<T>>::from)?;1131 Ok(())1132 }11331134 /// Set collection property permission.1135 ///1136 /// * `collection` - Collection handler.1137 /// * `sender` - The owner or administrator of the collection.1138 /// * `property_permission` - Property permission.1139 pub fn set_property_permission(1140 collection: &CollectionHandle<T>,1141 sender: &T::CrossAccountId,1142 property_permission: PropertyKeyPermission,1143 ) -> DispatchResult {1144 Self::set_scoped_property_permission(1145 collection,1146 sender,1147 PropertyScope::None,1148 property_permission,1149 )1150 }11511152 /// Set collection property permission with scope.1153 ///1154 /// * `collection` - Collection handler.1155 /// * `sender` - The owner or administrator of the collection.1156 /// * `scope` - Property scope.1157 /// * `property_permission` - Property permission.1158 pub fn set_scoped_property_permission(1159 collection: &CollectionHandle<T>,1160 sender: &T::CrossAccountId,1161 scope: PropertyScope,1162 property_permission: PropertyKeyPermission,1163 ) -> DispatchResult {1164 collection.check_is_owner_or_admin(sender)?;11651166 let all_permissions = CollectionPropertyPermissions::<T>::get(collection.id);1167 let current_permission = all_permissions.get(&property_permission.key);1168 if matches![1169 current_permission,1170 Some(PropertyPermission { mutable: false, .. })1171 ] {1172 return Err(<Error<T>>::NoPermission.into());1173 }11741175 CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {1176 let property_permission = property_permission.clone();1177 permissions.try_scoped_set(1178 scope,1179 property_permission.key,1180 property_permission.permission,1181 )1182 })1183 .map_err(<Error<T>>::from)?;11841185 Self::deposit_event(Event::PropertyPermissionSet(1186 collection.id,1187 property_permission.key,1188 ));11891190 Ok(())1191 }11921193 /// Set token property permission.1194 ///1195 /// * `collection` - Collection handler.1196 /// * `sender` - The owner or administrator of the collection.1197 /// * `property_permissions` - Property permissions.1198 #[transactional]1199 pub fn set_token_property_permissions(1200 collection: &CollectionHandle<T>,1201 sender: &T::CrossAccountId,1202 property_permissions: Vec<PropertyKeyPermission>,1203 ) -> DispatchResult {1204 Self::set_scoped_token_property_permissions(1205 collection,1206 sender,1207 PropertyScope::None,1208 property_permissions,1209 )1210 }12111212 /// Set token property permission with scope.1213 ///1214 /// * `collection` - Collection handler.1215 /// * `sender` - The owner or administrator of the collection.1216 /// * `scope` - Property scope.1217 /// * `property_permissions` - Property permissions.1218 #[transactional]1219 pub fn set_scoped_token_property_permissions(1220 collection: &CollectionHandle<T>,1221 sender: &T::CrossAccountId,1222 scope: PropertyScope,1223 property_permissions: Vec<PropertyKeyPermission>,1224 ) -> DispatchResult {1225 for prop_pemission in property_permissions {1226 Self::set_scoped_property_permission(collection, sender, scope, prop_pemission)?;1227 }12281229 Ok(())1230 }12311232 /// Get collection property.1233 pub fn get_collection_property(1234 collection_id: CollectionId,1235 key: &PropertyKey,1236 ) -> Option<PropertyValue> {1237 Self::collection_properties(collection_id).get(key).cloned()1238 }12391240 /// Convert byte vector to property key vector.1241 pub fn bytes_keys_to_property_keys(1242 keys: Vec<Vec<u8>>,1243 ) -> Result<Vec<PropertyKey>, DispatchError> {1244 keys.into_iter()1245 .map(|key| -> Result<PropertyKey, DispatchError> {1246 key.try_into()1247 .map_err(|_| <Error<T>>::PropertyKeyIsTooLong.into())1248 })1249 .collect::<Result<Vec<PropertyKey>, DispatchError>>()1250 }12511252 /// Get properties according to given keys.1253 pub fn filter_collection_properties(1254 collection_id: CollectionId,1255 keys: Option<Vec<PropertyKey>>,1256 ) -> Result<Vec<Property>, DispatchError> {1257 let properties = Self::collection_properties(collection_id);12581259 let properties = keys1260 .map(|keys| {1261 keys.into_iter()1262 .filter_map(|key| {1263 properties.get(&key).map(|value| Property {1264 key,1265 value: value.clone(),1266 })1267 })1268 .collect()1269 })1270 .unwrap_or_else(|| {1271 properties1272 .into_iter()1273 .map(|(key, value)| Property { key, value })1274 .collect()1275 });12761277 Ok(properties)1278 }12791280 /// Get property permissions according to given keys.1281 pub fn filter_property_permissions(1282 collection_id: CollectionId,1283 keys: Option<Vec<PropertyKey>>,1284 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {1285 let permissions = Self::property_permissions(collection_id);12861287 let key_permissions = keys1288 .map(|keys| {1289 keys.into_iter()1290 .filter_map(|key| {1291 permissions1292 .get(&key)1293 .map(|permission| PropertyKeyPermission {1294 key,1295 permission: permission.clone(),1296 })1297 })1298 .collect()1299 })1300 .unwrap_or_else(|| {1301 permissions1302 .into_iter()1303 .map(|(key, permission)| PropertyKeyPermission { key, permission })1304 .collect()1305 });13061307 Ok(key_permissions)1308 }13091310 /// Toggle `user` participation in the `collection`'s allow list.1311 /// #### Store read/writes1312 /// 1 writes1313 pub fn toggle_allowlist(1314 collection: &CollectionHandle<T>,1315 sender: &T::CrossAccountId,1316 user: &T::CrossAccountId,1317 allowed: bool,1318 ) -> DispatchResult {1319 collection.check_is_owner_or_admin(sender)?;13201321 // =========13221323 if allowed {1324 <Allowlist<T>>::insert((collection.id, user), true);1325 } else {1326 <Allowlist<T>>::remove((collection.id, user));1327 }13281329 Ok(())1330 }13311332 /// Toggle `user` participation in the `collection`'s admin list.1333 /// #### Store read/writes1334 /// 2 writes1335 pub fn toggle_admin(1336 collection: &CollectionHandle<T>,1337 sender: &T::CrossAccountId,1338 user: &T::CrossAccountId,1339 admin: bool,1340 ) -> DispatchResult {1341 collection.check_is_owner(sender)?;13421343 let was_admin = <IsAdmin<T>>::get((collection.id, user));1344 if was_admin == admin {1345 return Ok(());1346 }1347 let amount = <AdminAmount<T>>::get(collection.id);13481349 if admin {1350 let amount = amount1351 .checked_add(1)1352 .ok_or(<Error<T>>::CollectionAdminCountExceeded)?;1353 ensure!(1354 amount <= Self::collection_admins_limit(),1355 <Error<T>>::CollectionAdminCountExceeded,1356 );13571358 // =========13591360 <AdminAmount<T>>::insert(collection.id, amount);1361 <IsAdmin<T>>::insert((collection.id, user), true);1362 } else {1363 <AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));1364 <IsAdmin<T>>::remove((collection.id, user));1365 }13661367 Ok(())1368 }13691370 /// Merge set fields from `new_limit` to `old_limit`.1371 pub fn clamp_limits(1372 mode: CollectionMode,1373 old_limit: &CollectionLimits,1374 mut new_limit: CollectionLimits,1375 ) -> Result<CollectionLimits, DispatchError> {1376 let limits = old_limit;1377 limit_default!(old_limit, new_limit,1378 account_token_ownership_limit => ensure!(1379 new_limit <= MAX_TOKEN_OWNERSHIP,1380 <Error<T>>::CollectionLimitBoundsExceeded,1381 ),1382 sponsored_data_size => ensure!(1383 new_limit <= CUSTOM_DATA_LIMIT,1384 <Error<T>>::CollectionLimitBoundsExceeded,1385 ),13861387 sponsored_data_rate_limit => {},1388 token_limit => ensure!(1389 old_limit >= new_limit && new_limit > 0,1390 <Error<T>>::CollectionTokenLimitExceeded1391 ),13921393 sponsor_transfer_timeout(match mode {1394 CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,1395 CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1396 CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,1397 }) => ensure!(1398 new_limit <= MAX_SPONSOR_TIMEOUT,1399 <Error<T>>::CollectionLimitBoundsExceeded,1400 ),1401 sponsor_approve_timeout => {},1402 owner_can_transfer => ensure!(1403 !limits.owner_can_transfer_instaled() ||1404 old_limit || !new_limit,1405 <Error<T>>::OwnerPermissionsCantBeReverted,1406 ),1407 owner_can_destroy => ensure!(1408 old_limit || !new_limit,1409 <Error<T>>::OwnerPermissionsCantBeReverted,1410 ),1411 transfers_enabled => {},1412 );1413 Ok(new_limit)1414 }14151416 /// Merge set fields from `new_permission` to `old_permission`.1417 pub fn clamp_permissions(1418 _mode: CollectionMode,1419 old_permission: &CollectionPermissions,1420 mut new_permission: CollectionPermissions,1421 ) -> Result<CollectionPermissions, DispatchError> {1422 limit_default_clone!(old_permission, new_permission,1423 access => {},1424 mint_mode => {},1425 nesting => { /* todo check for permissive, if only it gets out of benchmarks */ },1426 );1427 Ok(new_permission)1428 }1429}14301431/// Indicates unsupported methods by returning [Error::UnsupportedOperation].1432#[macro_export]1433macro_rules! unsupported {1434 ($runtime:path) => {1435 Err($crate::Error::<$runtime>::UnsupportedOperation.into())1436 };1437}14381439/// Return weights for various worst-case operations.1440pub trait CommonWeightInfo<CrossAccountId> {1441 /// Weight of item creation.1442 fn create_item() -> Weight;14431444 /// Weight of items creation.1445 fn create_multiple_items(amount: &[CreateItemData]) -> Weight;14461447 /// Weight of items creation.1448 fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;14491450 /// The weight of the burning item.1451 fn burn_item() -> Weight;14521453 /// Property setting weight.1454 ///1455 /// * `amount`- The number of properties to set.1456 fn set_collection_properties(amount: u32) -> Weight;14571458 /// Collection property deletion weight.1459 ///1460 /// * `amount`- The number of properties to set.1461 fn delete_collection_properties(amount: u32) -> Weight;14621463 /// Token property setting weight.1464 ///1465 /// * `amount`- The number of properties to set.1466 fn set_token_properties(amount: u32) -> Weight;14671468 /// Token property deletion weight.1469 ///1470 /// * `amount`- The number of properties to delete.1471 fn delete_token_properties(amount: u32) -> Weight;14721473 /// Token property permissions set weight.1474 ///1475 /// * `amount`- The number of property permissions to set.1476 fn set_token_property_permissions(amount: u32) -> Weight;14771478 /// Transfer price of the token or its parts.1479 fn transfer() -> Weight;14801481 /// The price of setting the permission of the operation from another user.1482 fn approve() -> Weight;14831484 /// Transfer price from another user.1485 fn transfer_from() -> Weight;14861487 /// The price of burning a token from another user.1488 fn burn_from() -> Weight;14891490 /// Differs from burn_item in case of Fungible and Refungible, as it should burn1491 /// whole users's balance.1492 ///1493 /// This method shouldn't be used directly, as it doesn't count breadth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1494 fn burn_recursively_self_raw() -> Weight;14951496 /// Cost of iterating over `amount` children while burning, without counting child burning itself.1497 ///1498 /// This method shouldn't be used directly, as it doesn't count depth price, use [burn_recursively](CommonWeightInfo::burn_recursively) instead1499 fn burn_recursively_breadth_raw(amount: u32) -> Weight;15001501 /// The price of recursive burning a token.1502 ///1503 /// `max_selfs` - The maximum burning weight of the token itself.1504 /// `max_breadth` - The maximum number of nested tokens to burn.1505 fn burn_recursively(max_selfs: u32, max_breadth: u32) -> Weight {1506 Self::burn_recursively_self_raw()1507 .saturating_mul(max_selfs.max(1) as u64)1508 .saturating_add(Self::burn_recursively_breadth_raw(max_breadth))1509 }15101511 /// The price of retrieving token owner1512 fn token_owner() -> Weight;1513}15141515/// Weight info extension trait for refungible pallet.1516pub trait RefungibleExtensionsWeightInfo {1517 /// Weight of token repartition.1518 fn repartition() -> Weight;1519}15201521/// Common collection operations.1522///1523/// It wraps methods in Fungible, Nonfungible and Refungible pallets1524/// and adds weight info.1525pub trait CommonCollectionOperations<T: Config> {1526 /// Create token.1527 ///1528 /// * `sender` - The user who mint the token and pays for the transaction.1529 /// * `to` - The user who will own the token.1530 /// * `data` - Token data.1531 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1532 fn create_item(1533 &self,1534 sender: T::CrossAccountId,1535 to: T::CrossAccountId,1536 data: CreateItemData,1537 nesting_budget: &dyn Budget,1538 ) -> DispatchResultWithPostInfo;15391540 /// Create multiple tokens.1541 ///1542 /// * `sender` - The user who mint the token and pays for the transaction.1543 /// * `to` - The user who will own the token.1544 /// * `data` - Token data.1545 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1546 fn create_multiple_items(1547 &self,1548 sender: T::CrossAccountId,1549 to: T::CrossAccountId,1550 data: Vec<CreateItemData>,1551 nesting_budget: &dyn Budget,1552 ) -> DispatchResultWithPostInfo;15531554 /// Create multiple tokens.1555 ///1556 /// * `sender` - The user who mint the token and pays for the transaction.1557 /// * `to` - The user who will own the token.1558 /// * `data` - Token data.1559 /// * `nesting_budget` - A budget that can be spent on nesting tokens.1560 fn create_multiple_items_ex(1561 &self,1562 sender: T::CrossAccountId,1563 data: CreateItemExData<T::CrossAccountId>,1564 nesting_budget: &dyn Budget,1565 ) -> DispatchResultWithPostInfo;15661567 /// Burn token.1568 ///1569 /// * `sender` - The user who owns the token.1570 /// * `token` - Token id that will burned.1571 /// * `amount` - The number of parts of the token that will be burned.1572 fn burn_item(1573 &self,1574 sender: T::CrossAccountId,1575 token: TokenId,1576 amount: u128,1577 ) -> DispatchResultWithPostInfo;15781579 /// Burn token and all nested tokens recursievly.1580 ///1581 /// * `sender` - The user who owns the token.1582 /// * `token` - Token id that will burned.1583 /// * `self_budget` - The budget that can be spent on burning tokens.1584 /// * `breadth_budget` - The budget that can be spent on burning nested tokens.1585 fn burn_item_recursively(1586 &self,1587 sender: T::CrossAccountId,1588 token: TokenId,1589 self_budget: &dyn Budget,1590 breadth_budget: &dyn Budget,1591 ) -> DispatchResultWithPostInfo;15921593 /// Set collection properties.1594 ///1595 /// * `sender` - Must be either the owner of the collection or its admin.1596 /// * `properties` - Properties to be set.1597 fn set_collection_properties(1598 &self,1599 sender: T::CrossAccountId,1600 properties: Vec<Property>,1601 ) -> DispatchResultWithPostInfo;16021603 /// Delete collection properties.1604 ///1605 /// * `sender` - Must be either the owner of the collection or its admin.1606 /// * `properties` - The properties to be removed.1607 fn delete_collection_properties(1608 &self,1609 sender: &T::CrossAccountId,1610 property_keys: Vec<PropertyKey>,1611 ) -> DispatchResultWithPostInfo;16121613 /// Set token properties.1614 ///1615 /// The appropriate [`PropertyPermission`] for the token property1616 /// must be set with [`Self::set_token_property_permissions`].1617 ///1618 /// * `sender` - Must be either the owner of the token or its admin.1619 /// * `token_id` - The token for which the properties are being set.1620 /// * `properties` - Properties to be set.1621 /// * `budget` - Budget for setting properties.1622 fn set_token_properties(1623 &self,1624 sender: T::CrossAccountId,1625 token_id: TokenId,1626 properties: Vec<Property>,1627 budget: &dyn Budget,1628 ) -> DispatchResultWithPostInfo;16291630 /// Remove token properties.1631 ///1632 /// The appropriate [`PropertyPermission`] for the token property1633 /// must be set with [`Self::set_token_property_permissions`].1634 ///1635 /// * `sender` - Must be either the owner of the token or its admin.1636 /// * `token_id` - The token for which the properties are being remove.1637 /// * `property_keys` - Keys to remove corresponding properties.1638 /// * `budget` - Budget for removing properties.1639 fn delete_token_properties(1640 &self,1641 sender: T::CrossAccountId,1642 token_id: TokenId,1643 property_keys: Vec<PropertyKey>,1644 budget: &dyn Budget,1645 ) -> DispatchResultWithPostInfo;16461647 /// Set token property permissions.1648 ///1649 /// * `sender` - Must be either the owner of the token or its admin.1650 /// * `token_id` - The token for which the properties are being set.1651 /// * `property_permissions` - Property permissions to be set.1652 /// * `budget` - Budget for setting properties.1653 fn set_token_property_permissions(1654 &self,1655 sender: &T::CrossAccountId,1656 property_permissions: Vec<PropertyKeyPermission>,1657 ) -> DispatchResultWithPostInfo;16581659 /// Transfer amount of token pieces.1660 ///1661 /// * `sender` - Donor user.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(1667 &self,1668 sender: T::CrossAccountId,1669 to: T::CrossAccountId,1670 token: TokenId,1671 amount: u128,1672 budget: &dyn Budget,1673 ) -> DispatchResultWithPostInfo;16741675 /// Grant access to another account to transfer parts of the token owned by the calling user via [Self::transfer_from].1676 ///1677 /// * `sender` - The user who grants access to the token.1678 /// * `spender` - The user to whom the rights are granted.1679 /// * `token` - The token to which access is granted.1680 /// * `amount` - The amount of pieces that another user can dispose of.1681 fn approve(1682 &self,1683 sender: T::CrossAccountId,1684 spender: T::CrossAccountId,1685 token: TokenId,1686 amount: u128,1687 ) -> DispatchResultWithPostInfo;16881689 /// Send parts of a token owned by another user.1690 ///1691 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1692 ///1693 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1694 /// * `from` - The user who owns the token.1695 /// * `to` - Recepient user.1696 /// * `token` - The token of which parts are being sent.1697 /// * `amount` - The number of parts of the token that will be transferred.1698 /// * `budget` - The maximum budget that can be spent on the transfer.1699 fn transfer_from(1700 &self,1701 sender: T::CrossAccountId,1702 from: T::CrossAccountId,1703 to: T::CrossAccountId,1704 token: TokenId,1705 amount: u128,1706 budget: &dyn Budget,1707 ) -> DispatchResultWithPostInfo;17081709 /// Burn parts of a token owned by another user.1710 ///1711 /// Before calling this method, you must grant rights to the calling user via [`Self::approve`].1712 ///1713 /// * `sender` - The user who must have access to the token (see [`Self::approve`]).1714 /// * `from` - The user who owns the token.1715 /// * `token` - The token of which parts are being sent.1716 /// * `amount` - The number of parts of the token that will be transferred.1717 /// * `budget` - The maximum budget that can be spent on the burn.1718 fn burn_from(1719 &self,1720 sender: T::CrossAccountId,1721 from: T::CrossAccountId,1722 token: TokenId,1723 amount: u128,1724 budget: &dyn Budget,1725 ) -> DispatchResultWithPostInfo;17261727 /// Check permission to nest token.1728 ///1729 /// * `sender` - The user who initiated the check.1730 /// * `from` - The token that is checked for embedding.1731 /// * `under` - Token under which to check.1732 /// * `budget` - The maximum budget that can be spent on the check.1733 fn check_nesting(1734 &self,1735 sender: T::CrossAccountId,1736 from: (CollectionId, TokenId),1737 under: TokenId,1738 budget: &dyn Budget,1739 ) -> DispatchResult;17401741 /// Nest one token into another.1742 ///1743 /// * `under` - Token holder.1744 /// * `to_nest` - Nested token.1745 fn nest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17461747 /// Unnest token.1748 ///1749 /// * `under` - Token holder.1750 /// * `to_nest` - Token to unnest.1751 fn unnest(&self, under: TokenId, to_nest: (CollectionId, TokenId));17521753 /// Get all user tokens.1754 ///1755 /// * `account` - Account for which you need to get tokens.1756 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;17571758 /// Get all the tokens in the collection.1759 fn collection_tokens(&self) -> Vec<TokenId>;17601761 /// Check if the token exists.1762 ///1763 /// * `token` - Id token to check.1764 fn token_exists(&self, token: TokenId) -> bool;17651766 /// Get the id of the last minted token.1767 fn last_token_id(&self) -> TokenId;17681769 /// Get the owner of the token.1770 ///1771 /// * `token` - The token for which you need to find out the owner.1772 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;17731774 /// Returns 10 tokens owners in no particular order.1775 ///1776 /// * `token` - The token for which you need to find out the owners.1777 fn token_owners(&self, token: TokenId) -> Vec<T::CrossAccountId>;17781779 /// Get the value of the token property by key.1780 ///1781 /// * `token` - Token with the property to get.1782 /// * `key` - Property name.1783 fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue>;17841785 /// Get a set of token properties by key vector.1786 ///1787 /// * `token` - Token with the property to get.1788 /// * `keys` - Vector of property keys. If this parameter is [None](sp_std::result::Result),1789 /// then all properties are returned.1790 fn token_properties(&self, token: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property>;17911792 /// Amount of unique collection tokens1793 fn total_supply(&self) -> u32;17941795 /// Amount of different tokens account has.1796 ///1797 /// * `account` - The account for which need to get the balance.1798 fn account_balance(&self, account: T::CrossAccountId) -> u32;17991800 /// Amount of specific token account have.1801 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;18021803 /// Amount of token pieces1804 fn total_pieces(&self, token: TokenId) -> Option<u128>;18051806 /// Get the number of parts of the token that a trusted user can manage.1807 ///1808 /// * `sender` - Trusted user.1809 /// * `spender` - Owner of the token.1810 /// * `token` - The token for which to get the value.1811 fn allowance(1812 &self,1813 sender: T::CrossAccountId,1814 spender: T::CrossAccountId,1815 token: TokenId,1816 ) -> u128;18171818 /// Get extension for RFT collection.1819 fn refungible_extensions(&self) -> Option<&dyn RefungibleExtensions<T>>;1820}18211822/// Extension for RFT collection.1823pub trait RefungibleExtensions<T>1824where1825 T: Config,1826{1827 /// Change the number of parts of the token.1828 ///1829 /// When the value changes down, this function is equivalent to burning parts of the token.1830 ///1831 /// * `sender` - The user calling the repartition operation. Must be the owner of the token.1832 /// * `token` - The token for which you want to change the number of parts.1833 /// * `amount` - The new value of the parts of the token.1834 fn repartition(1835 &self,1836 sender: &T::CrossAccountId,1837 token: TokenId,1838 amount: u128,1839 ) -> DispatchResultWithPostInfo;1840}18411842/// Merge [`DispatchResult`] with [`Weight`] into [`DispatchResultWithPostInfo`].1843///1844/// Used for [`CommonCollectionOperations`] implementations and flexible enough to do so.1845pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {1846 let post_info = PostDispatchInfo {1847 actual_weight: Some(weight),1848 pays_fee: Pays::Yes,1849 };1850 match res {1851 Ok(()) => Ok(post_info),1852 Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),1853 }1854}18551856impl<T: Config> From<PropertiesError> for Error<T> {1857 fn from(error: PropertiesError) -> Self {1858 match error {1859 PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,1860 PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,1861 PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,1862 PropertiesError::PropertyKeyIsTooLong => Self::PropertyKeyIsTooLong,1863 PropertiesError::EmptyPropertyKey => Self::EmptyPropertyKey,1864 }1865 }1866}pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -172,14 +172,9 @@
fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {
let sponsor =
Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;
- let result: (address, uint256) = if sponsor.is_canonical_substrate() {
- let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);
- (Default::default(), sponsor)
- } else {
- let sponsor = *sponsor.as_eth();
- (sponsor, Default::default())
- };
- Ok(result)
+ Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(
+ &sponsor,
+ ))
}
/// Check tat contract has confirmed sponsor.
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -22,7 +22,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -255,6 +255,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -266,6 +278,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -277,6 +300,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -325,6 +359,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple6 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -332,6 +332,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -343,6 +355,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -354,6 +377,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -402,6 +436,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
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
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -332,6 +332,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -343,6 +355,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -354,6 +377,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -402,6 +436,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -14,10 +14,22 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
-import {contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3} from './util/helpers';
+import {isAllowlisted, normalizeAccountId} from '../util/helpers';
+import {
+ contractHelpers,
+ createEthAccount,
+ createEthAccountWithBalance,
+ deployFlipper,
+ evmCollection,
+ evmCollectionHelpers,
+ getCollectionAddressFromResult,
+ itWeb3,
+} from './util/helpers';
+import {itEth, usingEthPlaygrounds} from './util/playgrounds';
-describe('EVM allowlist', () => {
+describe('EVM contract allowlist', () => {
itWeb3('Contract allowlist can be toggled', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
const flipper = await deployFlipper(web3, owner);
@@ -58,3 +70,79 @@
expect(await flipper.methods.getValue().call()).to.be.false;
});
});
+
+describe('EVM collection allowlist', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Collection allowlist can be added and removed by [eth] address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.eth.createAccount();
+
+ const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+
+ await collectionEvm.methods.removeFromCollectionAllowList(user).send({from: owner});
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ });
+
+ itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+
+ await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ });
+
+ itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.eth.createAccount();
+
+ const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await expect(collectionEvm.methods.addToCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+ await expect(collectionEvm.methods.removeFromCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+ });
+
+ itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ });
+});
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -164,6 +164,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -171,6 +178,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -178,6 +192,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -208,6 +229,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple6 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -216,6 +216,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -223,6 +230,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -230,6 +244,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -260,6 +281,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple17 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -216,6 +216,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -223,6 +230,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -230,6 +244,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -260,6 +281,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple17 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -78,6 +78,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "address", "name": "spender", "type": "address" }
],
@@ -88,6 +97,15 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "spender", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
@@ -116,6 +134,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -261,6 +296,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],
"name": "setCollectionAccess",
"outputs": [],
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -109,6 +109,24 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "approved", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -146,6 +164,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -376,6 +411,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -109,6 +109,24 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "approved", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -146,6 +164,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -376,6 +411,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -1651,7 +1651,7 @@
});
}
-export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {
+export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {
return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();
}
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -730,6 +730,18 @@
}
/**
+ * Check if user is in allow list.
+ *
+ * @param collectionId ID of collection
+ * @param user Account to check
+ * @example await getAdmins(1)
+ * @returns is user in allow list
+ */
+ async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {
+ return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();
+ }
+
+ /**
* Adds an address to allow list
* @param signer keyring of signer
* @param collectionId ID of collection