difftreelog
Merge pull request #780 from UniqueNetwork/feature/properties-for-ft-collections
in: master
5 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -1222,7 +1222,8 @@
Ok(())
}
- /// Set scouped collection property.
+ /// Set a scoped collection property, where the scope is a special prefix
+ /// prohibiting a user to change the property.
///
/// * `collection_id` - ID of the collection for which the property is being set.
/// * `scope` - Property scope.
@@ -1240,7 +1241,8 @@
Ok(())
}
- /// Set scouped collection properties.
+ /// Set scoped collection properties, where the scope is a special prefix
+ /// prohibiting a user to change the properties.
///
/// * `collection_id` - ID of the collection for which the properties is being set.
/// * `scope` - Property scope.
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -18,7 +18,10 @@
use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, traits::Get};
use up_data_structs::{TokenId, CollectionId, CreateItemExData, budget::Budget, CreateItemData};
-use pallet_common::{CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight};
+use pallet_common::{
+ CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
+ weights::WeightInfo as _,
+};
use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
use sp_std::{vec::Vec, vec};
@@ -53,14 +56,12 @@
<SelfWeightOf<T>>::burn_item()
}
- fn set_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn set_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::set_collection_properties(amount)
}
- fn delete_collection_properties(_amount: u32) -> Weight {
- // Error
- Weight::zero()
+ fn delete_collection_properties(amount: u32) -> Weight {
+ <pallet_common::SelfWeightOf<T>>::delete_collection_properties(amount)
}
fn set_token_properties(_amount: u32) -> Weight {
@@ -294,18 +295,28 @@
fn set_collection_properties(
&self,
- _sender: T::CrossAccountId,
- _property: Vec<Property>,
+ sender: T::CrossAccountId,
+ properties: Vec<Property>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::set_collection_properties(self, &sender, properties),
+ weight,
+ )
}
fn delete_collection_properties(
&self,
- _sender: &T::CrossAccountId,
- _property_keys: Vec<PropertyKey>,
+ sender: &T::CrossAccountId,
+ property_keys: Vec<PropertyKey>,
) -> DispatchResultWithPostInfo {
- fail!(<Error<T>>::SettingPropertiesNotAllowed)
+ let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);
+
+ with_weight(
+ <Pallet<T>>::delete_collection_properties(self, sender, property_keys),
+ weight,
+ )
}
fn set_token_properties(
pallets/fungible/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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::{ensure};84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86 AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, budget::Budget,88};89use pallet_common::{90 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91 eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115 use up_data_structs::CollectionId;116 use super::weights::WeightInfo;117118 #[pallet::error]119 pub enum Error<T> {120 /// Not Fungible item data used to mint in Fungible collection.121 NotFungibleDataUsedToMintFungibleCollectionToken,122 /// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123 FungibleItemsHaveNoId,124 /// Tried to set data for fungible item.125 FungibleItemsDontHaveData,126 /// Fungible token does not support nesting.127 FungibleDisallowsNesting,128 /// Setting item properties is not allowed.129 SettingPropertiesNotAllowed,130 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 /// Only a fungible collection could be possibly broken; any fungible token is valid.133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 /// Total amount of fungible tokens inside a collection.148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 /// Amount of tokens owned by an account inside a collection.153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 /// Storage for assets delegated to a limited extent to other users.164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)222 }223224 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225 pub fn init_foreign_collection(226 owner: T::CrossAccountId,227 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 /// Destroys a collection.243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 // =========254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 ///Checks if collection has tokens. Return `true` if it has.264 fn collection_has_tokens(collection_id: CollectionId) -> bool {265 <TotalSupply<T>>::get(collection_id) != 0266 }267268 /// Burns the specified amount of the token. If the token balance269 /// or total supply is less than the given value,270 /// it will return [DispatchError].271 pub fn burn(272 collection: &FungibleHandle<T>,273 owner: &T::CrossAccountId,274 amount: u128,275 ) -> DispatchResult {276 let total_supply = <TotalSupply<T>>::get(collection.id)277 .checked_sub(amount)278 .ok_or(<CommonError<T>>::TokenValueTooLow)?;279280 let balance = <Balance<T>>::get((collection.id, owner))281 .checked_sub(amount)282 .ok_or(<CommonError<T>>::TokenValueTooLow)?;283284 // Foreign collection check285 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);286287 if collection.permissions.access() == AccessMode::AllowList {288 collection.check_allowlist(owner)?;289 }290291 // =========292293 if balance == 0 {294 <Balance<T>>::remove((collection.id, owner));295 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());296 } else {297 <Balance<T>>::insert((collection.id, owner), balance);298 }299 <TotalSupply<T>>::insert(collection.id, total_supply);300301 <PalletEvm<T>>::deposit_log(302 ERC20Events::Transfer {303 from: *owner.as_eth(),304 to: H160::default(),305 value: amount.into(),306 }307 .to_log(collection_id_to_address(collection.id)),308 );309 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(310 collection.id,311 TokenId::default(),312 owner.clone(),313 amount,314 ));315 Ok(())316 }317318 /// Burns the specified amount of the token.319 pub fn burn_foreign(320 collection: &FungibleHandle<T>,321 owner: &T::CrossAccountId,322 amount: u128,323 ) -> DispatchResult {324 let total_supply = <TotalSupply<T>>::get(collection.id)325 .checked_sub(amount)326 .ok_or(<CommonError<T>>::TokenValueTooLow)?;327328 let balance = <Balance<T>>::get((collection.id, owner))329 .checked_sub(amount)330 .ok_or(<CommonError<T>>::TokenValueTooLow)?;331 // =========332333 if balance == 0 {334 <Balance<T>>::remove((collection.id, owner));335 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());336 } else {337 <Balance<T>>::insert((collection.id, owner), balance);338 }339 <TotalSupply<T>>::insert(collection.id, total_supply);340341 <PalletEvm<T>>::deposit_log(342 ERC20Events::Transfer {343 from: *owner.as_eth(),344 to: H160::default(),345 value: amount.into(),346 }347 .to_log(collection_id_to_address(collection.id)),348 );349 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(350 collection.id,351 TokenId::default(),352 owner.clone(),353 amount,354 ));355 Ok(())356 }357358 /// Transfers the specified amount of tokens. Will check that359 /// the transfer is allowed for the token.360 ///361 /// - `from`: Owner of tokens to transfer.362 /// - `to`: Recepient of transfered tokens.363 /// - `amount`: Amount of tokens to transfer.364 /// - `collection`: Collection that contains the token365 pub fn transfer(366 collection: &FungibleHandle<T>,367 from: &T::CrossAccountId,368 to: &T::CrossAccountId,369 amount: u128,370 nesting_budget: &dyn Budget,371 ) -> DispatchResult {372 ensure!(373 collection.limits.transfers_enabled(),374 <CommonError<T>>::TransferNotAllowed,375 );376377 if collection.permissions.access() == AccessMode::AllowList {378 collection.check_allowlist(from)?;379 collection.check_allowlist(to)?;380 }381 <PalletCommon<T>>::ensure_correct_receiver(to)?;382383 let balance_from = <Balance<T>>::get((collection.id, from))384 .checked_sub(amount)385 .ok_or(<CommonError<T>>::TokenValueTooLow)?;386 let balance_to = if from != to && amount != 0 {387 Some(388 <Balance<T>>::get((collection.id, to))389 .checked_add(amount)390 .ok_or(ArithmeticError::Overflow)?,391 )392 } else {393 None394 };395396 // =========397398 if let Some(balance_to) = balance_to {399 // from != to && amount != 0400401 <PalletStructure<T>>::nest_if_sent_to_token(402 from.clone(),403 to,404 collection.id,405 TokenId::default(),406 nesting_budget,407 )?;408409 if balance_from == 0 {410 <Balance<T>>::remove((collection.id, from));411 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());412 } else {413 <Balance<T>>::insert((collection.id, from), balance_from);414 }415 <Balance<T>>::insert((collection.id, to), balance_to);416 }417418 <PalletEvm<T>>::deposit_log(419 ERC20Events::Transfer {420 from: *from.as_eth(),421 to: *to.as_eth(),422 value: amount.into(),423 }424 .to_log(collection_id_to_address(collection.id)),425 );426 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(427 collection.id,428 TokenId::default(),429 from.clone(),430 to.clone(),431 amount,432 ));433 Ok(())434 }435436 /// Minting tokens for multiple IDs.437 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]438 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]439 pub fn create_multiple_items_common(440 collection: &FungibleHandle<T>,441 sender: &T::CrossAccountId,442 data: BTreeMap<T::CrossAccountId, u128>,443 nesting_budget: &dyn Budget,444 ) -> DispatchResult {445 let total_supply = data446 .iter()447 .map(|(_, v)| *v)448 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {449 acc.checked_add(v)450 })451 .ok_or(ArithmeticError::Overflow)?;452453 for (to, _) in data.iter() {454 <PalletStructure<T>>::check_nesting(455 sender.clone(),456 to,457 collection.id,458 TokenId::default(),459 nesting_budget,460 )?;461 }462463 let updated_balances = data464 .into_iter()465 .map(|(user, amount)| {466 let updated_balance = <Balance<T>>::get((collection.id, &user))467 .checked_add(amount)468 .ok_or(ArithmeticError::Overflow)?;469 Ok((user, amount, updated_balance))470 })471 .collect::<Result<Vec<_>, DispatchError>>()?;472473 // =========474475 <TotalSupply<T>>::insert(collection.id, total_supply);476 for (user, amount, updated_balance) in updated_balances {477 <Balance<T>>::insert((collection.id, &user), updated_balance);478 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(479 &user,480 collection.id,481 TokenId::default(),482 );483 <PalletEvm<T>>::deposit_log(484 ERC20Events::Transfer {485 from: H160::default(),486 to: *user.as_eth(),487 value: amount.into(),488 }489 .to_log(collection_id_to_address(collection.id)),490 );491 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(492 collection.id,493 TokenId::default(),494 user.clone(),495 amount,496 ));497 }498499 Ok(())500 }501502 /// Minting tokens for multiple IDs.503 /// See [`create_item`][`Pallet::create_item`] for more details.504 pub fn create_multiple_items(505 collection: &FungibleHandle<T>,506 sender: &T::CrossAccountId,507 data: BTreeMap<T::CrossAccountId, u128>,508 nesting_budget: &dyn Budget,509 ) -> DispatchResult {510 // Foreign collection check511 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);512513 if !collection.is_owner_or_admin(sender) {514 ensure!(515 collection.permissions.mint_mode(),516 <CommonError<T>>::PublicMintingNotAllowed517 );518 collection.check_allowlist(sender)?;519520 for (owner, _) in data.iter() {521 collection.check_allowlist(owner)?;522 }523 }524525 Self::create_multiple_items_common(collection, sender, data, nesting_budget)526 }527528 /// Minting tokens for multiple IDs.529 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.530 pub fn create_multiple_items_foreign(531 collection: &FungibleHandle<T>,532 sender: &T::CrossAccountId,533 data: BTreeMap<T::CrossAccountId, u128>,534 nesting_budget: &dyn Budget,535 ) -> DispatchResult {536 Self::create_multiple_items_common(collection, sender, data, nesting_budget)537 }538539 fn set_allowance_unchecked(540 collection: &FungibleHandle<T>,541 owner: &T::CrossAccountId,542 spender: &T::CrossAccountId,543 amount: u128,544 ) {545 if amount == 0 {546 <Allowance<T>>::remove((collection.id, owner, spender));547 } else {548 <Allowance<T>>::insert((collection.id, owner, spender), amount);549 }550551 <PalletEvm<T>>::deposit_log(552 ERC20Events::Approval {553 owner: *owner.as_eth(),554 spender: *spender.as_eth(),555 value: amount.into(),556 }557 .to_log(collection_id_to_address(collection.id)),558 );559 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(560 collection.id,561 TokenId(0),562 owner.clone(),563 spender.clone(),564 amount,565 ));566 }567568 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.569 ///570 /// - `collection`: Collection that contains the token571 /// - `owner`: Owner of tokens that sets the allowance.572 /// - `spender`: Recipient of the allowance rights.573 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.574 pub fn set_allowance(575 collection: &FungibleHandle<T>,576 owner: &T::CrossAccountId,577 spender: &T::CrossAccountId,578 amount: u128,579 ) -> DispatchResult {580 if collection.permissions.access() == AccessMode::AllowList {581 collection.check_allowlist(owner)?;582 collection.check_allowlist(spender)?;583 }584585 if <Balance<T>>::get((collection.id, owner)) < amount {586 ensure!(587 collection.ignores_owned_amount(owner),588 <CommonError<T>>::CantApproveMoreThanOwned589 );590 }591592 // =========593594 Self::set_allowance_unchecked(collection, owner, spender, amount);595 Ok(())596 }597598 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.599 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.600 ///601 /// - `collection`: Collection that contains the token.602 /// - `spender`: CrossAccountId who has the allowance rights.603 /// - `from`: The owner of the tokens who sets the allowance.604 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.605 fn check_allowed(606 collection: &FungibleHandle<T>,607 spender: &T::CrossAccountId,608 from: &T::CrossAccountId,609 amount: u128,610 nesting_budget: &dyn Budget,611 ) -> Result<Option<u128>, DispatchError> {612 if spender.conv_eq(from) {613 return Ok(None);614 }615 if collection.permissions.access() == AccessMode::AllowList {616 // `from`, `to` checked in [`transfer`]617 collection.check_allowlist(spender)?;618 }619 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {620 // TODO: should collection owner be allowed to perform this transfer?621 ensure!(622 <PalletStructure<T>>::check_indirectly_owned(623 spender.clone(),624 source.0,625 source.1,626 None,627 nesting_budget628 )?,629 <CommonError<T>>::ApprovedValueTooLow,630 );631 return Ok(None);632 }633 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);634 if allowance.is_none() {635 ensure!(636 collection.ignores_allowance(spender),637 <CommonError<T>>::ApprovedValueTooLow638 );639 }640641 Ok(allowance)642 }643644 /// Transfer fungible tokens from one account to another.645 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.646 /// The owner should set allowance for the spender to transfer pieces.647 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.648649 pub fn transfer_from(650 collection: &FungibleHandle<T>,651 spender: &T::CrossAccountId,652 from: &T::CrossAccountId,653 to: &T::CrossAccountId,654 amount: u128,655 nesting_budget: &dyn Budget,656 ) -> DispatchResult {657 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;658659 // =========660661 Self::transfer(collection, from, to, amount, nesting_budget)?;662 if let Some(allowance) = allowance {663 Self::set_allowance_unchecked(collection, from, spender, allowance);664 }665 Ok(())666 }667668 /// Burn fungible tokens from the account.669 ///670 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should671 /// set allowance for the spender to burn tokens.672 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.673 pub fn burn_from(674 collection: &FungibleHandle<T>,675 spender: &T::CrossAccountId,676 from: &T::CrossAccountId,677 amount: u128,678 nesting_budget: &dyn Budget,679 ) -> DispatchResult {680 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;681682 // =========683684 Self::burn(collection, from, amount)?;685 if let Some(allowance) = allowance {686 Self::set_allowance_unchecked(collection, from, spender, allowance);687 }688 Ok(())689 }690691 /// Creates fungible token.692 ///693 /// The sender should be the owner/admin of the collection or collection should be configured694 /// to allow public minting.695 ///696 /// - `data`: Contains user who will become the owners of the tokens and amount697 /// of tokens he will receive.698 pub fn create_item(699 collection: &FungibleHandle<T>,700 sender: &T::CrossAccountId,701 data: CreateItemData<T>,702 nesting_budget: &dyn Budget,703 ) -> DispatchResult {704 Self::create_multiple_items(705 collection,706 sender,707 [(data.0, data.1)].into_iter().collect(),708 nesting_budget,709 )710 }711712 /// Creates fungible token.713 ///714 /// - `data`: Contains user who will become the owners of the tokens and amount715 /// of tokens he will receive.716 pub fn create_item_foreign(717 collection: &FungibleHandle<T>,718 sender: &T::CrossAccountId,719 data: CreateItemData<T>,720 nesting_budget: &dyn Budget,721 ) -> DispatchResult {722 Self::create_multiple_items_foreign(723 collection,724 sender,725 [(data.0, data.1)].into_iter().collect(),726 nesting_budget,727 )728 }729730 /// Returns 10 tokens owners in no particular order731 ///732 /// There is no direct way to get token holders in ascending order,733 /// since `iter_prefix` returns values in no particular order.734 /// Therefore, getting the 10 largest holders with a large value of holders735 /// can lead to impact memory allocation + sorting with `n * log (n)`.736 pub fn token_owners(737 collection: CollectionId,738 _token: TokenId,739 ) -> Option<Vec<T::CrossAccountId>> {740 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))741 .map(|(owner, _amount)| owner)742 .take(10)743 .collect();744745 if res.is_empty() {746 None747 } else {748 Some(res)749 }750 }751}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//! # Fungible Pallet18//!19//! The Fungible pallet provides functionality for dealing with fungible assets.20//!21//! - [`CreateItemData`]22//! - [`Config`]23//! - [`FungibleHandle`]24//! - [`Pallet`]25//! - [`TotalSupply`]26//! - [`Balance`]27//! - [`Allowance`]28//! - [`Error`]29//!30//! ## Fungible tokens31//!32//! Fungible tokens or assets are divisible and non-unique. For instance,33//! fiat currencies like the dollar are fungible: A $1 bill34//! in New York City has the same value as a $1 bill in Miami.35//! A fungible token can also be a cryptocurrency like Bitcoin: 1 BTC is worth 1 BTC,36//! no matter where it is issued. Thus, the fungibility refers to a specific currency’s37//! ability to maintain one standard value. As well, it needs to have uniform acceptance.38//! This means that a currency’s history should not be able to affect its value,39//! and this is due to the fact that each piece that is a part of the currency is equal40//! in value when compared to every other piece of that exact same currency.41//! In the world of cryptocurrencies, this is essentially a coin or a token42//! that can be replaced by another identical coin or token, and they are43//! both mutually interchangeable. A popular implementation of fungible tokens is44//! the ERC-20 token standard.45//!46//! ### ERC-2047//!48//! The [ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015,49//! is a Token Standard that implements an API for tokens within Smart Contracts.50//!51//! Example functionalities ERC-20 provides:52//!53//! * transfer tokens from one account to another54//! * get the current token balance of an account55//! * get the total supply of the token available on the network56//! * approve whether an amount of token from an account can be spent by a third-party account57//!58//! ## Overview59//!60//! The module provides functionality for asset management of fungible asset, supports ERC-20 standart, includes:61//!62//! * Asset Issuance63//! * Asset Transferal64//! * Asset Destruction65//! * Delegated Asset Transfers66//!67//! **NOTE:** The created fungible asset always has `token_id` = 0.68//! So `tokenA` and `tokenB` will have different `collection_id`.69//!70//! ### Implementations71//!72//! The Fungible pallet provides implementations for the following traits.73//!74//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support75//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections76//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight77//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls7879#![cfg_attr(not(feature = "std"), no_std)]8081use core::ops::Deref;82use evm_coder::ToLog;83use frame_support::ensure;84use pallet_evm::account::CrossAccountId;85use up_data_structs::{86 AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,87 mapping::TokenAddressMapping, budget::Budget, PropertyKey, Property,88};89use pallet_common::{90 Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,91 eth::collection_id_to_address,92};93use pallet_evm::Pallet as PalletEvm;94use pallet_structure::Pallet as PalletStructure;95use pallet_evm_coder_substrate::WithRecorder;96use sp_core::H160;97use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};98use sp_std::{collections::btree_map::BTreeMap, vec::Vec};99100pub use pallet::*;101102use crate::erc::ERC20Events;103#[cfg(feature = "runtime-benchmarks")]104pub mod benchmarking;105pub mod common;106pub mod erc;107pub mod weights;108109pub type CreateItemData<T> = (<T as pallet_evm::Config>::CrossAccountId, u128);110pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;111112#[frame_support::pallet]113pub mod pallet {114 use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};115 use up_data_structs::CollectionId;116 use super::weights::WeightInfo;117118 #[pallet::error]119 pub enum Error<T> {120 /// Not Fungible item data used to mint in Fungible collection.121 NotFungibleDataUsedToMintFungibleCollectionToken,122 /// Fungible tokens hold no ID, and the default value of TokenId for Fungible collection is 0.123 FungibleItemsHaveNoId,124 /// Tried to set data for fungible item.125 FungibleItemsDontHaveData,126 /// Fungible token does not support nesting.127 FungibleDisallowsNesting,128 /// Setting item properties is not allowed.129 SettingPropertiesNotAllowed,130 /// Setting allowance for all is not allowed.131 SettingAllowanceForAllNotAllowed,132 /// Only a fungible collection could be possibly broken; any fungible token is valid.133 FungibleTokensAreAlwaysValid,134 }135136 #[pallet::config]137 pub trait Config:138 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config139 {140 type WeightInfo: WeightInfo;141 }142143 #[pallet::pallet]144 #[pallet::generate_store(pub(super) trait Store)]145 pub struct Pallet<T>(_);146147 /// Total amount of fungible tokens inside a collection.148 #[pallet::storage]149 pub type TotalSupply<T: Config> =150 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u128, QueryKind = ValueQuery>;151152 /// Amount of tokens owned by an account inside a collection.153 #[pallet::storage]154 pub type Balance<T: Config> = StorageNMap<155 Key = (156 Key<Twox64Concat, CollectionId>,157 Key<Blake2_128Concat, T::CrossAccountId>,158 ),159 Value = u128,160 QueryKind = ValueQuery,161 >;162163 /// Storage for assets delegated to a limited extent to other users.164 #[pallet::storage]165 pub type Allowance<T: Config> = StorageNMap<166 Key = (167 Key<Twox64Concat, CollectionId>,168 Key<Blake2_128, T::CrossAccountId>,169 Key<Blake2_128Concat, T::CrossAccountId>,170 ),171 Value = u128,172 QueryKind = ValueQuery,173 >;174}175176/// Wrapper around untyped collection handle, asserting inner collection is of fungible type.177/// Required for interaction with Fungible collections, type safety and implementation [`solidity_interface`][`evm_coder::solidity_interface`].178pub struct FungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);179180/// Implementation of methods required for dispatching during runtime.181impl<T: Config> FungibleHandle<T> {182 /// Casts [`CollectionHandle`][`pallet_common::CollectionHandle`] into [`FungibleHandle`].183 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {184 Self(inner)185 }186187 /// Casts [`FungibleHandle`] into [`CollectionHandle`][`pallet_common::CollectionHandle`].188 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {189 self.0190 }191 /// Returns a mutable reference to the internal [`CollectionHandle`][`pallet_common::CollectionHandle`].192 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {193 &mut self.0194 }195}196impl<T: Config> WithRecorder<T> for FungibleHandle<T> {197 fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {198 self.0.recorder()199 }200 fn into_recorder(self) -> pallet_evm_coder_substrate::SubstrateRecorder<T> {201 self.0.into_recorder()202 }203}204impl<T: Config> Deref for FungibleHandle<T> {205 type Target = pallet_common::CollectionHandle<T>;206207 fn deref(&self) -> &Self::Target {208 &self.0209 }210}211212/// Pallet implementation for fungible assets213impl<T: Config> Pallet<T> {214 /// Initializes the collection. Returns [CollectionId] on success, [DispatchError] otherwise.215 pub fn init_collection(216 owner: T::CrossAccountId,217 payer: T::CrossAccountId,218 data: CreateCollectionData<T::AccountId>,219 flags: CollectionFlags,220 ) -> Result<CollectionId, DispatchError> {221 <PalletCommon<T>>::init_collection(owner, payer, data, flags)222 }223224 /// Initializes the collection with ForeignCollection flag. Returns [CollectionId] on success, [DispatchError] otherwise.225 pub fn init_foreign_collection(226 owner: T::CrossAccountId,227 payer: T::CrossAccountId,228 data: CreateCollectionData<T::AccountId>,229 ) -> Result<CollectionId, DispatchError> {230 let id = <PalletCommon<T>>::init_collection(231 owner,232 payer,233 data,234 CollectionFlags {235 foreign: true,236 ..Default::default()237 },238 )?;239 Ok(id)240 }241242 /// Destroys a collection.243 pub fn destroy_collection(244 collection: FungibleHandle<T>,245 sender: &T::CrossAccountId,246 ) -> DispatchResult {247 let id = collection.id;248249 if Self::collection_has_tokens(id) {250 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());251 }252253 // =========254255 PalletCommon::destroy_collection(collection.0, sender)?;256257 <TotalSupply<T>>::remove(id);258 let _ = <Balance<T>>::clear_prefix((id,), u32::MAX, None);259 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);260 Ok(())261 }262263 /// Add properties to the collection.264 pub fn set_collection_properties(265 collection: &FungibleHandle<T>,266 sender: &T::CrossAccountId,267 properties: Vec<Property>,268 ) -> DispatchResult {269 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)270 }271272 /// Delete properties of the collection, associated with the provided keys.273 pub fn delete_collection_properties(274 collection: &FungibleHandle<T>,275 sender: &T::CrossAccountId,276 property_keys: Vec<PropertyKey>,277 ) -> DispatchResult {278 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)279 }280281 /// Checks if collection has tokens. Return `true` if it has.282 fn collection_has_tokens(collection_id: CollectionId) -> bool {283 <TotalSupply<T>>::get(collection_id) != 0284 }285286 /// Burns the specified amount of the token. If the token balance287 /// or total supply is less than the given value,288 /// it will return [DispatchError].289 pub fn burn(290 collection: &FungibleHandle<T>,291 owner: &T::CrossAccountId,292 amount: u128,293 ) -> DispatchResult {294 let total_supply = <TotalSupply<T>>::get(collection.id)295 .checked_sub(amount)296 .ok_or(<CommonError<T>>::TokenValueTooLow)?;297298 let balance = <Balance<T>>::get((collection.id, owner))299 .checked_sub(amount)300 .ok_or(<CommonError<T>>::TokenValueTooLow)?;301302 // Foreign collection check303 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);304305 if collection.permissions.access() == AccessMode::AllowList {306 collection.check_allowlist(owner)?;307 }308309 // =========310311 if balance == 0 {312 <Balance<T>>::remove((collection.id, owner));313 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());314 } else {315 <Balance<T>>::insert((collection.id, owner), balance);316 }317 <TotalSupply<T>>::insert(collection.id, total_supply);318319 <PalletEvm<T>>::deposit_log(320 ERC20Events::Transfer {321 from: *owner.as_eth(),322 to: H160::default(),323 value: amount.into(),324 }325 .to_log(collection_id_to_address(collection.id)),326 );327 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(328 collection.id,329 TokenId::default(),330 owner.clone(),331 amount,332 ));333 Ok(())334 }335336 /// Burns the specified amount of the token.337 pub fn burn_foreign(338 collection: &FungibleHandle<T>,339 owner: &T::CrossAccountId,340 amount: u128,341 ) -> DispatchResult {342 let total_supply = <TotalSupply<T>>::get(collection.id)343 .checked_sub(amount)344 .ok_or(<CommonError<T>>::TokenValueTooLow)?;345346 let balance = <Balance<T>>::get((collection.id, owner))347 .checked_sub(amount)348 .ok_or(<CommonError<T>>::TokenValueTooLow)?;349 // =========350351 if balance == 0 {352 <Balance<T>>::remove((collection.id, owner));353 <PalletStructure<T>>::unnest_if_nested(owner, collection.id, TokenId::default());354 } else {355 <Balance<T>>::insert((collection.id, owner), balance);356 }357 <TotalSupply<T>>::insert(collection.id, total_supply);358359 <PalletEvm<T>>::deposit_log(360 ERC20Events::Transfer {361 from: *owner.as_eth(),362 to: H160::default(),363 value: amount.into(),364 }365 .to_log(collection_id_to_address(collection.id)),366 );367 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(368 collection.id,369 TokenId::default(),370 owner.clone(),371 amount,372 ));373 Ok(())374 }375376 /// Transfers the specified amount of tokens. Will check that377 /// the transfer is allowed for the token.378 ///379 /// - `from`: Owner of tokens to transfer.380 /// - `to`: Recepient of transfered tokens.381 /// - `amount`: Amount of tokens to transfer.382 /// - `collection`: Collection that contains the token383 pub fn transfer(384 collection: &FungibleHandle<T>,385 from: &T::CrossAccountId,386 to: &T::CrossAccountId,387 amount: u128,388 nesting_budget: &dyn Budget,389 ) -> DispatchResult {390 ensure!(391 collection.limits.transfers_enabled(),392 <CommonError<T>>::TransferNotAllowed,393 );394395 if collection.permissions.access() == AccessMode::AllowList {396 collection.check_allowlist(from)?;397 collection.check_allowlist(to)?;398 }399 <PalletCommon<T>>::ensure_correct_receiver(to)?;400401 let balance_from = <Balance<T>>::get((collection.id, from))402 .checked_sub(amount)403 .ok_or(<CommonError<T>>::TokenValueTooLow)?;404 let balance_to = if from != to && amount != 0 {405 Some(406 <Balance<T>>::get((collection.id, to))407 .checked_add(amount)408 .ok_or(ArithmeticError::Overflow)?,409 )410 } else {411 None412 };413414 // =========415416 if let Some(balance_to) = balance_to {417 // from != to && amount != 0418419 <PalletStructure<T>>::nest_if_sent_to_token(420 from.clone(),421 to,422 collection.id,423 TokenId::default(),424 nesting_budget,425 )?;426427 if balance_from == 0 {428 <Balance<T>>::remove((collection.id, from));429 <PalletStructure<T>>::unnest_if_nested(from, collection.id, TokenId::default());430 } else {431 <Balance<T>>::insert((collection.id, from), balance_from);432 }433 <Balance<T>>::insert((collection.id, to), balance_to);434 }435436 <PalletEvm<T>>::deposit_log(437 ERC20Events::Transfer {438 from: *from.as_eth(),439 to: *to.as_eth(),440 value: amount.into(),441 }442 .to_log(collection_id_to_address(collection.id)),443 );444 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(445 collection.id,446 TokenId::default(),447 from.clone(),448 to.clone(),449 amount,450 ));451 Ok(())452 }453454 /// Minting tokens for multiple IDs.455 /// It is a utility function used in [`create_multiple_items`][`Pallet::create_multiple_items`]456 /// and [`create_multiple_items_foreign`][`Pallet::create_multiple_items_foreign`]457 pub fn create_multiple_items_common(458 collection: &FungibleHandle<T>,459 sender: &T::CrossAccountId,460 data: BTreeMap<T::CrossAccountId, u128>,461 nesting_budget: &dyn Budget,462 ) -> DispatchResult {463 let total_supply = data464 .iter()465 .map(|(_, v)| *v)466 .try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {467 acc.checked_add(v)468 })469 .ok_or(ArithmeticError::Overflow)?;470471 for (to, _) in data.iter() {472 <PalletStructure<T>>::check_nesting(473 sender.clone(),474 to,475 collection.id,476 TokenId::default(),477 nesting_budget,478 )?;479 }480481 let updated_balances = data482 .into_iter()483 .map(|(user, amount)| {484 let updated_balance = <Balance<T>>::get((collection.id, &user))485 .checked_add(amount)486 .ok_or(ArithmeticError::Overflow)?;487 Ok((user, amount, updated_balance))488 })489 .collect::<Result<Vec<_>, DispatchError>>()?;490491 // =========492493 <TotalSupply<T>>::insert(collection.id, total_supply);494 for (user, amount, updated_balance) in updated_balances {495 <Balance<T>>::insert((collection.id, &user), updated_balance);496 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(497 &user,498 collection.id,499 TokenId::default(),500 );501 <PalletEvm<T>>::deposit_log(502 ERC20Events::Transfer {503 from: H160::default(),504 to: *user.as_eth(),505 value: amount.into(),506 }507 .to_log(collection_id_to_address(collection.id)),508 );509 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(510 collection.id,511 TokenId::default(),512 user.clone(),513 amount,514 ));515 }516517 Ok(())518 }519520 /// Minting tokens for multiple IDs.521 /// See [`create_item`][`Pallet::create_item`] for more details.522 pub fn create_multiple_items(523 collection: &FungibleHandle<T>,524 sender: &T::CrossAccountId,525 data: BTreeMap<T::CrossAccountId, u128>,526 nesting_budget: &dyn Budget,527 ) -> DispatchResult {528 // Foreign collection check529 ensure!(!collection.flags.foreign, <CommonError<T>>::NoPermission);530531 if !collection.is_owner_or_admin(sender) {532 ensure!(533 collection.permissions.mint_mode(),534 <CommonError<T>>::PublicMintingNotAllowed535 );536 collection.check_allowlist(sender)?;537538 for (owner, _) in data.iter() {539 collection.check_allowlist(owner)?;540 }541 }542543 Self::create_multiple_items_common(collection, sender, data, nesting_budget)544 }545546 /// Minting tokens for multiple IDs.547 /// See [`create_item_foreign`][`Pallet::create_item_foreign`] for more details.548 pub fn create_multiple_items_foreign(549 collection: &FungibleHandle<T>,550 sender: &T::CrossAccountId,551 data: BTreeMap<T::CrossAccountId, u128>,552 nesting_budget: &dyn Budget,553 ) -> DispatchResult {554 Self::create_multiple_items_common(collection, sender, data, nesting_budget)555 }556557 fn set_allowance_unchecked(558 collection: &FungibleHandle<T>,559 owner: &T::CrossAccountId,560 spender: &T::CrossAccountId,561 amount: u128,562 ) {563 if amount == 0 {564 <Allowance<T>>::remove((collection.id, owner, spender));565 } else {566 <Allowance<T>>::insert((collection.id, owner, spender), amount);567 }568569 <PalletEvm<T>>::deposit_log(570 ERC20Events::Approval {571 owner: *owner.as_eth(),572 spender: *spender.as_eth(),573 value: amount.into(),574 }575 .to_log(collection_id_to_address(collection.id)),576 );577 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(578 collection.id,579 TokenId(0),580 owner.clone(),581 spender.clone(),582 amount,583 ));584 }585586 /// Set allowance for the spender to `transfer` or `burn` owner's tokens.587 ///588 /// - `collection`: Collection that contains the token589 /// - `owner`: Owner of tokens that sets the allowance.590 /// - `spender`: Recipient of the allowance rights.591 /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.592 pub fn set_allowance(593 collection: &FungibleHandle<T>,594 owner: &T::CrossAccountId,595 spender: &T::CrossAccountId,596 amount: u128,597 ) -> DispatchResult {598 if collection.permissions.access() == AccessMode::AllowList {599 collection.check_allowlist(owner)?;600 collection.check_allowlist(spender)?;601 }602603 if <Balance<T>>::get((collection.id, owner)) < amount {604 ensure!(605 collection.ignores_owned_amount(owner),606 <CommonError<T>>::CantApproveMoreThanOwned607 );608 }609610 // =========611612 Self::set_allowance_unchecked(collection, owner, spender, amount);613 Ok(())614 }615616 /// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.617 /// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.618 ///619 /// - `collection`: Collection that contains the token.620 /// - `spender`: CrossAccountId who has the allowance rights.621 /// - `from`: The owner of the tokens who sets the allowance.622 /// - `amount`: Amount of tokens by which the allowance sholud be reduced.623 fn check_allowed(624 collection: &FungibleHandle<T>,625 spender: &T::CrossAccountId,626 from: &T::CrossAccountId,627 amount: u128,628 nesting_budget: &dyn Budget,629 ) -> Result<Option<u128>, DispatchError> {630 if spender.conv_eq(from) {631 return Ok(None);632 }633 if collection.permissions.access() == AccessMode::AllowList {634 // `from`, `to` checked in [`transfer`]635 collection.check_allowlist(spender)?;636 }637 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {638 // TODO: should collection owner be allowed to perform this transfer?639 ensure!(640 <PalletStructure<T>>::check_indirectly_owned(641 spender.clone(),642 source.0,643 source.1,644 None,645 nesting_budget646 )?,647 <CommonError<T>>::ApprovedValueTooLow,648 );649 return Ok(None);650 }651 let allowance = <Allowance<T>>::get((collection.id, from, spender)).checked_sub(amount);652 if allowance.is_none() {653 ensure!(654 collection.ignores_allowance(spender),655 <CommonError<T>>::ApprovedValueTooLow656 );657 }658659 Ok(allowance)660 }661662 /// Transfer fungible tokens from one account to another.663 /// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.664 /// The owner should set allowance for the spender to transfer pieces.665 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.666667 pub fn transfer_from(668 collection: &FungibleHandle<T>,669 spender: &T::CrossAccountId,670 from: &T::CrossAccountId,671 to: &T::CrossAccountId,672 amount: u128,673 nesting_budget: &dyn Budget,674 ) -> DispatchResult {675 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;676677 // =========678679 Self::transfer(collection, from, to, amount, nesting_budget)?;680 if let Some(allowance) = allowance {681 Self::set_allowance_unchecked(collection, from, spender, allowance);682 }683 Ok(())684 }685686 /// Burn fungible tokens from the account.687 ///688 /// Same as the [`burn`][`Pallet::burn`] but spender doesn't need to be an owner of the tokens. The `from` should689 /// set allowance for the spender to burn tokens.690 /// See [`set_allowance`][`Pallet::set_allowance`] for more details.691 pub fn burn_from(692 collection: &FungibleHandle<T>,693 spender: &T::CrossAccountId,694 from: &T::CrossAccountId,695 amount: u128,696 nesting_budget: &dyn Budget,697 ) -> DispatchResult {698 let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;699700 // =========701702 Self::burn(collection, from, amount)?;703 if let Some(allowance) = allowance {704 Self::set_allowance_unchecked(collection, from, spender, allowance);705 }706 Ok(())707 }708709 /// Creates fungible token.710 ///711 /// The sender should be the owner/admin of the collection or collection should be configured712 /// to allow public minting.713 ///714 /// - `data`: Contains user who will become the owners of the tokens and amount715 /// of tokens he will receive.716 pub fn create_item(717 collection: &FungibleHandle<T>,718 sender: &T::CrossAccountId,719 data: CreateItemData<T>,720 nesting_budget: &dyn Budget,721 ) -> DispatchResult {722 Self::create_multiple_items(723 collection,724 sender,725 [(data.0, data.1)].into_iter().collect(),726 nesting_budget,727 )728 }729730 /// Creates fungible token.731 ///732 /// - `data`: Contains user who will become the owners of the tokens and amount733 /// of tokens he will receive.734 pub fn create_item_foreign(735 collection: &FungibleHandle<T>,736 sender: &T::CrossAccountId,737 data: CreateItemData<T>,738 nesting_budget: &dyn Budget,739 ) -> DispatchResult {740 Self::create_multiple_items_foreign(741 collection,742 sender,743 [(data.0, data.1)].into_iter().collect(),744 nesting_budget,745 )746 }747748 /// Returns 10 tokens owners in no particular order749 ///750 /// There is no direct way to get token holders in ascending order,751 /// since `iter_prefix` returns values in no particular order.752 /// Therefore, getting the 10 largest holders with a large value of holders753 /// can lead to impact memory allocation + sorting with `n * log (n)`.754 pub fn token_owners(755 collection: CollectionId,756 _token: TokenId,757 ) -> Option<Vec<T::CrossAccountId>> {758 let res: Vec<T::CrossAccountId> = <Balance<T>>::iter_prefix((collection,))759 .map(|(owner, _amount)| owner)760 .take(10)761 .collect();762763 if res.is_empty() {764 None765 } else {766 Some(res)767 }768 }769}tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -45,6 +45,7 @@
"testNesting": "mocha --timeout 9999999 -r ts-node/register ./**/nest.test.ts",
"testUnnesting": "mocha --timeout 9999999 -r ts-node/register ./**/unnest.test.ts",
"testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts ./**/tokenProperties.test.ts ./**/getPropertiesRpc.test.ts",
+ "testCollectionProperties": "mocha --timeout 9999999 -r ts-node/register ./**/collectionProperties.test.ts",
"testMigration": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
tests/src/nesting/collectionProperties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/collectionProperties.test.ts
+++ b/tests/src/nesting/collectionProperties.test.ts
@@ -15,8 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, Pallets, usingPlaygrounds, expect} from '../util';
-import {UniqueBaseCollection} from '../util/playgrounds/unique';
+import {itSub, Pallets, usingPlaygrounds, expect, requirePalletsOrSkip} from '../util';
describe('Integration Test: Collection Properties', () => {
let alice: IKeyringPair;
@@ -32,116 +31,98 @@
itSub('Properties are initially empty', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
expect(await collection.getProperties()).to.be.empty;
- });
-
- async function testSetsPropertiesForCollection(collection: UniqueBaseCollection) {
- // As owner
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
-
- await collection.addAdmin(alice, {Substrate: bob.address});
-
- // As administrator
- await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: ''},
- ]);
- }
-
- itSub('Sets properties for a NFT collection', async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Sets properties for a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
});
-
- async function testCheckValidNames(collection: UniqueBaseCollection) {
- // alpha symbols
- await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
-
- // numeric symbols
- await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
-
- // underscore symbol
- await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
-
- // dash symbol
- await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
-
- // dot symbol
- await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'answer', value: ''},
- {key: '451', value: ''},
- {key: 'black_hole', value: ''},
- {key: '-', value: ''},
- {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
- ]);
- }
-
- itSub('Check valid names for NFT collection properties keys', async ({helper}) => {
- await testCheckValidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Check valid names for ReFungible collection properties keys', [Pallets.ReFungible], async ({helper}) => {
- await testCheckValidNames(await helper.rft.mintCollection(alice));
- });
-
- async function testChangesProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
-
- // Mutate the properties
- await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- const properties = await collection.getProperties();
- expect(properties).to.include.deep.members([
- {key: 'electron', value: 'come bond'},
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Changes properties of a NFT collection', async ({helper}) => {
- await testChangesProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Changes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testChangesProperties(await helper.rft.mintCollection(alice));
- });
-
- async function testDeleteProperties(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
-
- await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
-
- const properties = await collection.getProperties(['black_hole', 'electron']);
- expect(properties).to.be.deep.equal([
- {key: 'black_hole', value: 'LIGO'},
- ]);
- }
-
- itSub('Deletes properties of a NFT collection', async ({helper}) => {
- await testDeleteProperties(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Deletes properties of a ReFungible collection', [Pallets.ReFungible], async ({helper}) => {
- await testDeleteProperties(await helper.rft.mintCollection(alice));
- });
[
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
{mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
{mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Allows modifying a collection property multiple times with the same size (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
+
+ itSub('Sets properties for a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // As owner
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
+
+ await collection.addAdmin(alice, {Substrate: bob.address});
+
+ // As administrator
+ await expect(collection.setProperties(bob, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: ''},
+ ]);
+ });
+
+ itSub('Check valid names for collection properties keys', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ // alpha symbols
+ await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
+
+ // numeric symbols
+ await expect(collection.setProperties(alice, [{key: '451'}])).to.be.fulfilled;
+
+ // underscore symbol
+ await expect(collection.setProperties(alice, [{key: 'black_hole'}])).to.be.fulfilled;
+
+ // dash symbol
+ await expect(collection.setProperties(alice, [{key: '-'}])).to.be.fulfilled;
+
+ // dot symbol
+ await expect(collection.setProperties(alice, [{key: 'once.in.a.long.long.while...', value: 'you get a little lost'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'answer', value: ''},
+ {key: '451', value: ''},
+ {key: 'black_hole', value: ''},
+ {key: '-', value: ''},
+ {key: 'once.in.a.long.long.while...', value: 'you get a little lost'},
+ ]);
+ });
+
+ itSub('Changes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
+
+ // Mutate the properties
+ await expect(collection.setProperties(alice, [{key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ const properties = await collection.getProperties();
+ expect(properties).to.include.deep.members([
+ {key: 'electron', value: 'come bond'},
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Deletes properties of a collection', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
+
+ await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
+
+ const properties = await collection.getProperties(['black_hole', 'electron']);
+ expect(properties).to.be.deep.equal([
+ {key: 'black_hole', value: 'LIGO'},
+ ]);
+ });
+
+ itSub('Allows modifying a collection property multiple times with the same size', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const maxCollectionPropertiesSize = 40960;
@@ -166,18 +147,12 @@
const consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
}
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Adding then removing a collection property doesn't change the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Adding then removing a collection property doesn\'t change the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const propDataSize = 4096;
@@ -190,18 +165,12 @@
await collection.deleteProperties(alice, [propKey]);
consumedSpace = await collection.getPropertiesConsumedSpace();
expect(consumedSpace).to.be.equal(originalSpace);
- }));
+ });
- [
- // TODO enable properties for FT collection in Substrate (release 040)
- // {mode: 'ft' as const, requiredPallets: []},
- {mode: 'nft' as const, requiredPallets: []},
- {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
- ].map(testCase =>
- itSub.ifWithPallets(`Modifying a collection property with different sizes correctly changes the consumed space (${testCase.mode})`, testCase.requiredPallets, async({helper}) => {
+ itSub('Modifying a collection property with different sizes correctly changes the consumed space', async({helper}) => {
const propKey = 'tok-prop';
- const collection = await helper[testCase.mode].mintCollection(alice);
+ const collection = await helper[testSuite.mode].mintCollection(alice);
const originalSpace = await collection.getPropertiesConsumedSpace();
const initPropDataSize = 4096;
@@ -229,7 +198,8 @@
consumedSpace = await collection.getPropertiesConsumedSpace();
expectedConsumedSpaceDiff = biggerPropDataSize - smallerPropDataSize;
expect(consumedSpace).to.be.equal(biggerPropDataSize - expectedConsumedSpaceDiff);
- }));
+ });
+ }));
});
describe('Negative Integration Test: Collection Properties', () => {
@@ -242,119 +212,108 @@
[alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
+
+ [
+ {mode: 'nft' as const, requiredPallets: []},
+ {mode: 'ft' as const, requiredPallets: []},
+ {mode: 'rft' as const, requiredPallets: [Pallets.ReFungible]},
+ ].map(testSuite => describe(`${testSuite.mode.toUpperCase()}`, () => {
+ before(async function() {
+ // eslint-disable-next-line require-await
+ await usingPlaygrounds(async helper => {
+ requirePalletsOrSkip(this, helper, testSuite.requiredPallets);
+ });
+ });
- async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueBaseCollection) {
- await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
- .to.be.rejectedWith(/common\.NoPermission/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set properties in a NFT collection if not its onwer/administrator', async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties in a ReFungible collection if not its onwer/administrator', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));
- });
+ itSub('Fails to set properties in a collection if not its onwer/administrator', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
+ .to.be.rejectedWith(/common\.NoPermission/);
- async function testFailsSetPropertiesThatExeedLimits(collection: UniqueBaseCollection) {
- const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+ expect(await collection.getProperties()).to.be.empty;
+ });
- // Mute the general tx parsing error, too many bytes to process
- {
- console.error = () => {};
+ itSub('Fails to set properties that exceed the limits', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
+
+ // Mute the general tx parsing error, too many bytes to process
+ {
+ console.error = () => {};
+ await expect(collection.setProperties(alice, [
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
+ ])).to.be.rejected;
+ }
+
+ expect(await collection.getProperties(['electron'])).to.be.empty;
+
await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 9))},
- ])).to.be.rejected;
- }
-
- expect(await collection.getProperties(['electron'])).to.be.empty;
-
- await expect(collection.setProperties(alice, [
- {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
- {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
- ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
-
- expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
- }
-
- itSub('Fails to set properties that exceed the limits (NFT)', async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties that exceed the limits (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));
- });
+ {key: 'electron', value: 'low high '.repeat(Math.ceil(spaceLimit! / 18))},
+ {key: 'black_hole', value: '0'.repeat(Math.ceil(spaceLimit! / 2))},
+ ])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
- async function testFailsSetMorePropertiesThanAllowed(collection: UniqueBaseCollection) {
- const propertiesToBeSet = [];
- for (let i = 0; i < 65; i++) {
- propertiesToBeSet.push({
- key: 'electron_' + i,
- value: Math.random() > 0.5 ? 'high' : 'low',
- });
- }
-
- await expect(collection.setProperties(alice, propertiesToBeSet)).
- to.be.rejectedWith(/common\.PropertyLimitReached/);
-
- expect(await collection.getProperties()).to.be.empty;
- }
-
- itSub('Fails to set more properties than it is allowed (NFT)', async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set more properties than it is allowed (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));
- });
+ expect(await collection.getProperties(['electron', 'black_hole'])).to.be.empty;
+ });
+
+ itSub('Fails to set more properties than it is allowed', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const propertiesToBeSet = [];
+ for (let i = 0; i < 65; i++) {
+ propertiesToBeSet.push({
+ key: 'electron_' + i,
+ value: Math.random() > 0.5 ? 'high' : 'low',
+ });
+ }
+
+ await expect(collection.setProperties(alice, propertiesToBeSet)).
+ to.be.rejectedWith(/common\.PropertyLimitReached/);
+
+ expect(await collection.getProperties()).to.be.empty;
+ });
+
+ itSub('Fails to set properties with invalid names', async ({helper}) => {
+ const collection = await helper[testSuite.mode].mintCollection(alice);
+
+ const invalidProperties = [
+ [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
+ [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
+ [{key: 'déjà vu', value: 'hmm...'}],
+ ];
- async function testFailsSetPropertiesWithInvalidNames(collection: UniqueBaseCollection) {
- const invalidProperties = [
- [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
- [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
- [{key: 'déjà vu', value: 'hmm...'}],
- ];
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.setProperties(alice, invalidProperties[i]),
+ `on rejecting the new badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+
await expect(
- collection.setProperties(alice, invalidProperties[i]),
- `on rejecting the new badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
-
- await expect(
- collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
- 'on rejecting an unnamed property',
- ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
-
- await expect(
- collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
- 'on setting the correctly-but-still-badly-named property',
- ).to.be.fulfilled;
-
- const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
-
- const properties = await collection.getProperties(keys);
- expect(properties).to.be.deep.equal([
- {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
- ]);
-
- for (let i = 0; i < invalidProperties.length; i++) {
+ collection.setProperties(alice, [{key: '', value: 'nothing must not exist'}]),
+ 'on rejecting an unnamed property',
+ ).to.be.rejectedWith(/common\.EmptyPropertyKey/);
+
await expect(
- collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
- `on trying to delete the non-existent badly-named property #${i}`,
- ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
- }
- }
-
- itSub('Fails to set properties with invalid names (NFT)', async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.nft.mintCollection(alice));
- });
-
- itSub.ifWithPallets('Fails to set properties with invalid names (ReFungible)', [Pallets.ReFungible], async ({helper}) => {
- await testFailsSetPropertiesWithInvalidNames(await helper.rft.mintCollection(alice));
- });
+ collection.setProperties(alice, [{key: 'CRISPR-Cas9', value: 'rewriting nature!'}]),
+ 'on setting the correctly-but-still-badly-named property',
+ ).to.be.fulfilled;
+
+ const keys = invalidProperties.flatMap(propertySet => propertySet.map(property => property.key)).concat('CRISPR-Cas9').concat('');
+
+ const properties = await collection.getProperties(keys);
+ expect(properties).to.be.deep.equal([
+ {key: 'CRISPR-Cas9', value: 'rewriting nature!'},
+ ]);
+
+ for (let i = 0; i < invalidProperties.length; i++) {
+ await expect(
+ collection.deleteProperties(alice, invalidProperties[i].map(propertySet => propertySet.key)),
+ `on trying to delete the non-existent badly-named property #${i}`,
+ ).to.be.rejectedWith(/common\.InvalidCharacterInPropertyKey/);
+ }
+ });
+ }));
});
\ No newline at end of file