difftreelog
feat add ApproveFrom eth mirror
in: master
26 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -746,6 +746,8 @@
ApprovedValueTooLow,
/// Tried to approve more than owned
CantApproveMoreThanOwned,
+ /// Only spending from eth mirror could be approved
+ AddressIsNotEthMirror,
/// Can't transfer tokens to ethereum zero address
AddressIsZero,
@@ -1797,6 +1799,9 @@
/// The price of setting the permission of the operation from another user.
fn approve() -> Weight;
+ /// The price of setting the permission of the operation from another user for eth mirror.
+ fn approve_from() -> Weight;
+
/// Transfer price from another user.
fn transfer_from() -> Weight;
@@ -2008,6 +2013,22 @@
amount: u128,
) -> DispatchResultWithPostInfo;
+ /// Grant access to another account to transfer parts of the token owned by the calling user's eth mirror via [Self::transfer_from].
+ ///
+ /// * `sender` - The user who grants access to the token.
+ /// * `from` - Spender's eth mirror.
+ /// * `to` - The user to whom the rights are granted.
+ /// * `token` - The token to which access is granted.
+ /// * `amount` - The amount of pieces that another user can dispose of.
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo;
+
/// Send parts of a token owned by another user.
///
/// Before calling this method, you must grant rights to the calling user via [`Self::approve`].
pallets/evm-contract-helpers/src/stubs/ContractHelpers.rawdiffbeforeafterbothbinary blob — no preview
pallets/evm-contract-helpers/src/stubs/ContractHelpers.soldiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
+++ b/pallets/evm-contract-helpers/src/stubs/ContractHelpers.sol
@@ -283,8 +283,8 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -82,6 +82,16 @@
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ <Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, 100)?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -87,6 +87,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -254,6 +258,25 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(
+ token == TokenId::default(),
+ <Error<T>>::FungibleItemsHaveNoId
+ );
+
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -613,6 +613,45 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` owner's tokens from eth mirror.
+ ///
+ /// - `collection`: Collection that contains the token
+ /// - `sender`: Owner of tokens that sets the allowance.
+ /// - `from`: Owner's eth mirror.
+ /// - `to`: Recipient of the allowance rights.
+ /// - `amount`: Amount of tokens the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &FungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, amount);
+ Ok(())
+ }
+
/// Checks if a non-owner has (enough) allowance from the owner to perform operations on the tokens.
/// Returns the expected remaining allowance - it should be set manually if the transaction proceeds.
///
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -39,6 +39,7 @@
fn burn_item() -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
}
@@ -84,6 +85,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
@@ -141,6 +149,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Fungible Balance (r:1 w:0)
+ // Storage: Fungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(19_817_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Fungible Allowance (r:1 w:1)
// Storage: Fungible Balance (r:2 w:2)
fn transfer_from() -> Weight {
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -134,6 +134,15 @@
let item = create_max_item(&collection, &owner, sender.clone())?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, owner_eth.clone())?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, item, Some(&spender))?}
+
transfer_from {
bench_init!{
owner: sub; collection: collection(owner);
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -102,6 +102,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
<SelfWeightOf<T>>::transfer_from()
}
@@ -353,6 +357,26 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
+
+ with_weight(
+ if amount == 1 {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, Some(&to))
+ } else {
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, token, None)
+ },
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -1171,6 +1171,51 @@
Ok(())
}
+ /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `token`: Token the spender is allowed to `transfer` or `burn`.
+ pub fn set_allowance_for(
+ collection: &NonfungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ token: TokenId,
+ to: Option<&T::CrossAccountId>,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ if let Some(to) = to {
+ collection.check_allowlist(to)?;
+ }
+ }
+
+ if let Some(to) = to {
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+ }
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ let token_data =
+ <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
+ if token_data.owner != *from {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, token, to, false);
+ Ok(())
+ }
+
/// Checks allowance for the spender to use the token.
fn check_allowed(
collection: &NonfungibleHandle<T>,
pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -42,6 +42,7 @@
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
fn transfer() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from() -> Weight;
fn burn_from() -> Weight;
fn set_token_property_permissions(b: u32, ) -> Weight;
@@ -147,6 +148,13 @@
.saturating_add(T::DbWeight::get().reads(2 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(2 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
@@ -310,6 +318,13 @@
.saturating_add(RocksDbWeight::get().reads(2 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Nonfungible TokenData (r:1 w:0)
+ // Storage: Nonfungible Allowance (r:1 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(18_965_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(2 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Nonfungible Allowance (r:1 w:1)
// Storage: Nonfungible TokenData (r:1 w:1)
// Storage: Nonfungible AccountBalance (r:2 w:2)
pallets/refungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -163,6 +163,15 @@
let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
}: {<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?}
+ approve_from {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ let owner_eth = T::CrossAccountId::from_eth(*sender.as_eth());
+ let item = create_max_item(&collection, &owner, [(owner_eth.clone(), 200)])?;
+ }: {<Pallet<T>>::set_allowance_for(&collection, &sender, &owner_eth, &spender, item, 100)?}
+
transfer_from_normal {
bench_init!{
owner: sub; collection: collection(owner);
pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -127,6 +127,10 @@
<SelfWeightOf<T>>::approve()
}
+ fn approve_from() -> Weight {
+ <SelfWeightOf<T>>::approve_from()
+ }
+
fn transfer_from() -> Weight {
max_weight_of!(
transfer_from_normal(),
@@ -314,6 +318,20 @@
)
}
+ fn approve_from(
+ &self,
+ sender: T::CrossAccountId,
+ from: T::CrossAccountId,
+ to: T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResultWithPostInfo {
+ with_weight(
+ <Pallet<T>>::set_allowance_for(self, &sender, &from, &to, token_id, amount),
+ <CommonWeights<T>>::approve_from(),
+ )
+ }
+
fn transfer_from(
&self,
sender: T::CrossAccountId,
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1102,6 +1102,47 @@
Ok(())
}
+ /// Set allowance to spend from sender's eth mirror
+ ///
+ /// - `from`: Address of sender's eth mirror.
+ /// - `to`: Adress of spender.
+ /// - `amount`: Amount of token pieces the spender is allowed to `transfer` or `burn.
+ pub fn set_allowance_for(
+ collection: &RefungibleHandle<T>,
+ sender: &T::CrossAccountId,
+ from: &T::CrossAccountId,
+ to: &T::CrossAccountId,
+ token_id: TokenId,
+ amount: u128,
+ ) -> DispatchResult {
+ if collection.permissions.access() == AccessMode::AllowList {
+ collection.check_allowlist(sender)?;
+ collection.check_allowlist(from)?;
+ collection.check_allowlist(to)?;
+ }
+
+ <PalletCommon<T>>::ensure_correct_receiver(to)?;
+
+ ensure!(
+ *sender.as_eth() == *from.as_eth(),
+ <CommonError<T>>::AddressIsNotEthMirror
+ );
+
+ if <Balance<T>>::get((collection.id, token_id, from)) < amount {
+ ensure!(
+ collection.limits.owner_can_transfer()
+ && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from))
+ && Self::token_exists(collection, token_id),
+ <CommonError<T>>::CantApproveMoreThanOwned
+ );
+ }
+
+ // =========
+
+ Self::set_allowance_unchecked(collection, from, to, token_id, amount);
+ Ok(())
+ }
+
/// Returns allowance, which should be set after transaction
fn check_allowed(
collection: &RefungibleHandle<T>,
pallets/refungible/src/weights.rsdiffbeforeafterboth--- a/pallets/refungible/src/weights.rs
+++ b/pallets/refungible/src/weights.rs
@@ -45,6 +45,7 @@
fn transfer_removing() -> Weight;
fn transfer_creating_removing() -> Weight;
fn approve() -> Weight;
+ fn approve_from() -> Weight;
fn transfer_from_normal() -> Weight;
fn transfer_from_creating() -> Weight;
fn transfer_from_removing() -> Weight;
@@ -175,6 +176,13 @@
.saturating_add(T::DbWeight::get().reads(1 as u64))
.saturating_add(T::DbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(T::DbWeight::get().reads(1 as u64))
+ .saturating_add(T::DbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
@@ -400,6 +408,13 @@
.saturating_add(RocksDbWeight::get().reads(1 as u64))
.saturating_add(RocksDbWeight::get().writes(1 as u64))
}
+ // Storage: Refungible Balance (r:1 w:0)
+ // Storage: Refungible Allowance (r:0 w:1)
+ fn approve_from() -> Weight {
+ Weight::from_ref_time(20_649_000 as u64)
+ .saturating_add(RocksDbWeight::get().reads(1 as u64))
+ .saturating_add(RocksDbWeight::get().writes(1 as u64))
+ }
// Storage: Refungible Allowance (r:1 w:1)
// Storage: Refungible CollectionAllowance (r:1 w:0)
// Storage: Refungible Balance (r:2 w:2)
pallets/unique/src/lib.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//! # Unique Pallet18//!19//! A pallet governing Unique transactions.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! The Unique pallet's purpose is to be the primary interface between28//! external users and the inner structure of the Unique chains.29//!30//! It also contains an implementation of [`CollectionHelpers`][`eth`],31//! an Ethereum contract dealing with collection operations.32//!33//! ## Interface34//!35//! ### Dispatchables36//!37//! - `create_collection` - Create a collection of tokens. **Deprecated**, use `create_collection_ex`.38//! - `create_collection_ex` - Create a collection of tokens with explicit parameters.39//! - `destroy_collection` - Destroy a collection if no tokens exist within.40//! - `add_to_allow_list` - Add an address to allow list.41//! - `remove_from_allow_list` - Remove an address from allow list.42//! - `change_collection_owner` - Change the owner of the collection.43//! - `add_collection_admin` - Add an admin to a collection.44//! - `remove_collection_admin` - Remove admin of a collection.45//! - `set_collection_sponsor` - Invite a new collection sponsor.46//! - `confirm_sponsorship` - Confirm own sponsorship of a collection, becoming the sponsor.47//! - `remove_collection_sponsor` - Remove a sponsor from a collection.48//! - `create_item` - Create an item within a collection.49//! - `create_multiple_items` - Create multiple items within a collection.50//! - `set_collection_properties` - Add or change collection properties.51//! - `delete_collection_properties` - Delete specified collection properties.52//! - `set_token_properties` - Add or change token properties.53//! - `delete_token_properties` - Delete token properties.54//! - `set_token_property_permissions` - Add or change token property permissions of a collection.55//! - `create_multiple_items_ex` - Create multiple items within a collection with explicitly specified initial parameters.56//! - `set_transfers_enabled_flag` - Completely allow or disallow transfers for a particular collection.57//! - `burn_item` - Destroy an item.58//! - `burn_from` - Destroy an item on behalf of the owner as a non-owner account.59//! - `transfer` - Change ownership of the token.60//! - `transfer_from` - Change ownership of the token on behalf of the owner as a non-owner account.61//! - `approve` - Allow a non-permissioned address to transfer or burn an item.62//! - `set_collection_limits` - Set specific limits of a collection.63//! - `set_collection_permissions` - Set specific permissions of a collection.64//! - `repartition` - Re-partition a refungible token, while owning all of its parts.6566#![recursion_limit = "1024"]67#![cfg_attr(not(feature = "std"), no_std)]68#![allow(69 clippy::too_many_arguments,70 clippy::unnecessary_mut_passed,71 clippy::unused_unit72)]7374extern crate alloc;7576use frame_support::{77 decl_module, decl_storage, decl_error,78 dispatch::DispatchResult,79 ensure, fail,80 weights::{Weight},81 pallet_prelude::{DispatchResultWithPostInfo, ConstU32},82 BoundedVec,83};84use scale_info::TypeInfo;85use frame_system::{self as system, ensure_signed, ensure_root};86use sp_std::{vec, vec::Vec};87use up_data_structs::{88 MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,89 MAX_PROPERTIES_PER_ITEM, MAX_PROPERTY_KEY_LENGTH, MAX_PROPERTY_VALUE_LENGTH,90 MAX_COLLECTION_PROPERTIES_SIZE, COLLECTION_ADMINS_LIMIT, MAX_TOKEN_PROPERTIES_SIZE,91 CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,92 CreateCollectionData, CreateItemExData, budget, Property, PropertyKey, PropertyKeyPermission,93};94use pallet_evm::account::CrossAccountId;95use pallet_common::{96 CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_tx,97 dispatch::CollectionDispatch, RefungibleExtensionsWeightInfo,98};99pub mod eth;100101#[cfg(feature = "runtime-benchmarks")]102pub mod benchmarking;103pub mod weights;104use weights::WeightInfo;105106/// A maximum number of levels of depth in the token nesting tree.107pub const NESTING_BUDGET: u32 = 5;108109decl_error! {110 /// Errors for the common Unique transactions.111 pub enum Error for Module<T: Config> {112 /// Decimal_points parameter must be lower than [`up_data_structs::MAX_DECIMAL_POINTS`].113 CollectionDecimalPointLimitExceeded,114 /// Length of items properties must be greater than 0.115 EmptyArgument,116 /// Repertition is only supported by refungible collection.117 RepartitionCalledOnNonRefungibleCollection,118 }119}120121/// Configuration trait of this pallet.122pub trait Config: system::Config + pallet_common::Config + Sized + TypeInfo {123 /// Weight information for extrinsics in this pallet.124 type WeightInfo: WeightInfo;125126 /// Weight information for common pallet operations.127 type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;128129 /// Weight info information for extra refungible pallet operations.130 type RefungibleExtensionsWeightInfo: RefungibleExtensionsWeightInfo;131}132133type SelfWeightOf<T> = <T as Config>::WeightInfo;134135// # Used definitions136//137// ## User control levels138//139// chain-controlled - key is uncontrolled by user140// i.e autoincrementing index141// can use non-cryptographic hash142// real - key is controlled by user143// but it is hard to generate enough colliding values, i.e owner of signed txs144// can use non-cryptographic hash145// controlled - key is completly controlled by users146// i.e maps with mutable keys147// should use cryptographic hash148//149// ## User control level downgrade reasons150//151// ?1 - chain-controlled -> controlled152// collections/tokens can be destroyed, resulting in massive holes153// ?2 - chain-controlled -> controlled154// same as ?1, but can be only added, resulting in easier exploitation155// ?3 - real -> controlled156// no confirmation required, so addresses can be easily generated157decl_storage! {158 trait Store for Module<T: Config> as Unique {159160 //#region Private members161 /// Used for migrations162 ChainVersion: u64;163 //#endregion164165 //#region Tokens transfer sponosoring rate limit baskets166 /// (Collection id (controlled?2), who created (real))167 /// TODO: Off chain worker should remove from this map when collection gets removed168 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;169 /// Collection id (controlled?2), token id (controlled?2)170 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;171 /// Collection id (controlled?2), owning user (real)172 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;173 /// Collection id (controlled?2), token id (controlled?2)174 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;175 //#endregion176177 /// Variable metadata sponsoring178 /// Collection id (controlled?2), token id (controlled?2)179 #[deprecated]180 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;181 /// Last sponsoring of token property setting // todo:doc rephrase this and the following182 pub TokenPropertyBasket get(fn token_property_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;183184 /// Last sponsoring of NFT approval in a collection185 pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;186 /// Last sponsoring of fungible tokens approval in a collection187 pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;188 /// Last sponsoring of RFT approval in a collection189 pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;190 }191}192193decl_module! {194 /// Type alias to Pallet, to be used by construct_runtime.195 pub struct Module<T: Config> for enum Call196 where197 origin: T::RuntimeOrigin198 {199 type Error = Error<T>;200201 #[doc = "A maximum number of levels of depth in the token nesting tree."]202 const NESTING_BUDGET: u32 = NESTING_BUDGET;203204 #[doc = "Maximal length of a collection name."]205 const MAX_COLLECTION_NAME_LENGTH: u32 = MAX_COLLECTION_NAME_LENGTH;206207 #[doc = "Maximal length of a collection description."]208 const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = MAX_COLLECTION_DESCRIPTION_LENGTH;209210 #[doc = "Maximal length of a token prefix."]211 const MAX_TOKEN_PREFIX_LENGTH: u32 = MAX_TOKEN_PREFIX_LENGTH;212213 #[doc = "Maximum admins per collection."]214 const COLLECTION_ADMINS_LIMIT: u32 = COLLECTION_ADMINS_LIMIT;215216 #[doc = "Maximal length of a property key."]217 const MAX_PROPERTY_KEY_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH;218219 #[doc = "Maximal length of a property value."]220 const MAX_PROPERTY_VALUE_LENGTH: u32 = MAX_PROPERTY_VALUE_LENGTH;221222 #[doc = "A maximum number of token properties."]223 const MAX_PROPERTIES_PER_ITEM: u32 = MAX_PROPERTIES_PER_ITEM;224225 #[doc = "Maximum size for all collection properties."]226 const MAX_COLLECTION_PROPERTIES_SIZE: u32 = MAX_COLLECTION_PROPERTIES_SIZE;227228 #[doc = "Maximum size of all token properties."]229 const MAX_TOKEN_PROPERTIES_SIZE: u32 = MAX_TOKEN_PROPERTIES_SIZE;230231 #[doc = "Default NFT collection limit."]232 const NFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::NFT);233234 #[doc = "Default RFT collection limit."]235 const RFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::ReFungible);236237 #[doc = "Default FT collection limit."]238 const FT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::Fungible(0));239240 fn on_initialize(_now: T::BlockNumber) -> Weight {241 Weight::zero()242 }243244 fn on_runtime_upgrade() -> Weight {245 Weight::zero()246 }247248 /// Create a collection of tokens.249 ///250 /// Each Token may have multiple properties encoded as an array of bytes251 /// of certain length. The initial owner of the collection is set252 /// to the address that signed the transaction and can be changed later.253 ///254 /// Prefer the more advanced [`create_collection_ex`][`Pallet::create_collection_ex`] instead.255 ///256 /// # Permissions257 ///258 /// * Anyone - becomes the owner of the new collection.259 ///260 /// # Arguments261 ///262 /// * `collection_name`: Wide-character string with collection name263 /// (limit [`MAX_COLLECTION_NAME_LENGTH`]).264 /// * `collection_description`: Wide-character string with collection description265 /// (limit [`MAX_COLLECTION_DESCRIPTION_LENGTH`]).266 /// * `token_prefix`: Byte string containing the token prefix to mark a collection267 /// to which a token belongs (limit [`MAX_TOKEN_PREFIX_LENGTH`]).268 /// * `mode`: Type of items stored in the collection and type dependent data.269 // returns collection ID270 #[weight = <SelfWeightOf<T>>::create_collection()]271 #[deprecated(note = "`create_collection_ex` is more up-to-date and advanced, prefer it instead")]272 pub fn create_collection(273 origin,274 collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,275 collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,276 token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,277 mode: CollectionMode278 ) -> DispatchResult {279 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {280 name: collection_name,281 description: collection_description,282 token_prefix,283 mode,284 ..Default::default()285 };286 Self::create_collection_ex(origin, data)287 }288289 /// Create a collection with explicit parameters.290 ///291 /// Prefer it to the deprecated [`create_collection`][`Pallet::create_collection`] method.292 ///293 /// # Permissions294 ///295 /// * Anyone - becomes the owner of the new collection.296 ///297 /// # Arguments298 ///299 /// * `data`: Explicit data of a collection used for its creation.300 #[weight = <SelfWeightOf<T>>::create_collection()]301 pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {302 let sender = ensure_signed(origin)?;303304 // =========305 let sender = T::CrossAccountId::from_sub(sender);306 let _id = T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;307308 Ok(())309 }310311 /// Destroy a collection if no tokens exist within.312 ///313 /// # Permissions314 ///315 /// * Collection owner316 ///317 /// # Arguments318 ///319 /// * `collection_id`: Collection to destroy.320 #[weight = <SelfWeightOf<T>>::destroy_collection()]321 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {322 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);323324 Self::destroy_collection_internal(sender, collection_id)325 }326327 /// Add an address to allow list.328 ///329 /// # Permissions330 ///331 /// * Collection owner332 /// * Collection admin333 ///334 /// # Arguments335 ///336 /// * `collection_id`: ID of the modified collection.337 /// * `address`: ID of the address to be added to the allowlist.338 #[weight = <SelfWeightOf<T>>::add_to_allow_list()]339 pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{340341 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);342 let collection = <CollectionHandle<T>>::try_get(collection_id)?;343 collection.check_is_internal()?;344345 <PalletCommon<T>>::toggle_allowlist(346 &collection,347 &sender,348 &address,349 true,350 )?;351352 Ok(())353 }354355 /// Remove an address from allow list.356 ///357 /// # Permissions358 ///359 /// * Collection owner360 /// * Collection admin361 ///362 /// # Arguments363 ///364 /// * `collection_id`: ID of the modified collection.365 /// * `address`: ID of the address to be removed from the allowlist.366 #[weight = <SelfWeightOf<T>>::remove_from_allow_list()]367 pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{368369 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);370 let collection = <CollectionHandle<T>>::try_get(collection_id)?;371 collection.check_is_internal()?;372373 <PalletCommon<T>>::toggle_allowlist(374 &collection,375 &sender,376 &address,377 false,378 )?;379380 Ok(())381 }382383 /// Change the owner of the collection.384 ///385 /// # Permissions386 ///387 /// * Collection owner388 ///389 /// # Arguments390 ///391 /// * `collection_id`: ID of the modified collection.392 /// * `new_owner`: ID of the account that will become the owner.393 #[weight = <SelfWeightOf<T>>::change_collection_owner()]394 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {395 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);396 let new_owner = T::CrossAccountId::from_sub(new_owner);397 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;398 target_collection.change_owner(sender, new_owner.clone())399 }400401 /// Add an admin to a collection.402 ///403 /// NFT Collection can be controlled by multiple admin addresses404 /// (some which can also be servers, for example). Admins can issue405 /// and burn NFTs, as well as add and remove other admins,406 /// but cannot change NFT or Collection ownership.407 ///408 /// # Permissions409 ///410 /// * Collection owner411 /// * Collection admin412 ///413 /// # Arguments414 ///415 /// * `collection_id`: ID of the Collection to add an admin for.416 /// * `new_admin`: Address of new admin to add.417 #[weight = <SelfWeightOf<T>>::add_collection_admin()]418 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {419 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);420 let collection = <CollectionHandle<T>>::try_get(collection_id)?;421 <PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)422 }423424 /// Remove admin of a collection.425 ///426 /// An admin address can remove itself. List of admins may become empty,427 /// in which case only Collection Owner will be able to add an Admin.428 ///429 /// # Permissions430 ///431 /// * Collection owner432 /// * Collection admin433 ///434 /// # Arguments435 ///436 /// * `collection_id`: ID of the collection to remove the admin for.437 /// * `account_id`: Address of the admin to remove.438 #[weight = <SelfWeightOf<T>>::remove_collection_admin()]439 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {440 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);441 let collection = <CollectionHandle<T>>::try_get(collection_id)?;442 <PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)443 }444445 /// Set (invite) a new collection sponsor.446 ///447 /// If successful, confirmation from the sponsor-to-be will be pending.448 ///449 /// # Permissions450 ///451 /// * Collection owner452 /// * Collection admin453 ///454 /// # Arguments455 ///456 /// * `collection_id`: ID of the modified collection.457 /// * `new_sponsor`: ID of the account of the sponsor-to-be.458 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]459 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {460 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);461 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;462 target_collection.set_sponsor(&sender, new_sponsor.clone())463 }464465 /// Confirm own sponsorship of a collection, becoming the sponsor.466 ///467 /// An invitation must be pending, see [`set_collection_sponsor`][`Pallet::set_collection_sponsor`].468 /// Sponsor can pay the fees of a transaction instead of the sender,469 /// but only within specified limits.470 ///471 /// # Permissions472 ///473 /// * Sponsor-to-be474 ///475 /// # Arguments476 ///477 /// * `collection_id`: ID of the collection with the pending sponsor.478 #[weight = <SelfWeightOf<T>>::confirm_sponsorship()]479 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {480 let sender = ensure_signed(origin)?;481 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;482 target_collection.confirm_sponsorship(&sender)483 }484485 /// Remove a collection's a sponsor, making everyone pay for their own transactions.486 ///487 /// # Permissions488 ///489 /// * Collection owner490 ///491 /// # Arguments492 ///493 /// * `collection_id`: ID of the collection with the sponsor to remove.494 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]495 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {496 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);497 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;498 target_collection.remove_sponsor(&sender)499 }500501 /// Mint an item within a collection.502 ///503 /// A collection must exist first, see [`create_collection_ex`][`Pallet::create_collection_ex`].504 ///505 /// # Permissions506 ///507 /// * Collection owner508 /// * Collection admin509 /// * Anyone if510 /// * Allow List is enabled, and511 /// * Address is added to allow list, and512 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])513 ///514 /// # Arguments515 ///516 /// * `collection_id`: ID of the collection to which an item would belong.517 /// * `owner`: Address of the initial owner of the item.518 /// * `data`: Token data describing the item to store on chain.519 #[weight = T::CommonWeightInfo::create_item()]520 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {521 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);522 let budget = budget::Value::new(NESTING_BUDGET);523524 dispatch_tx::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))525 }526527 /// Create multiple items within a collection.528 ///529 /// A collection must exist first, see [`create_collection_ex`][`Pallet::create_collection_ex`].530 ///531 /// # Permissions532 ///533 /// * Collection owner534 /// * Collection admin535 /// * Anyone if536 /// * Allow List is enabled, and537 /// * Address is added to the allow list, and538 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])539 ///540 /// # Arguments541 ///542 /// * `collection_id`: ID of the collection to which the tokens would belong.543 /// * `owner`: Address of the initial owner of the tokens.544 /// * `items_data`: Vector of data describing each item to be created.545 #[weight = T::CommonWeightInfo::create_multiple_items(&items_data)]546 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {547 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);548 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);549 let budget = budget::Value::new(NESTING_BUDGET);550551 dispatch_tx::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))552 }553554 /// Add or change collection properties.555 ///556 /// # Permissions557 ///558 /// * Collection owner559 /// * Collection admin560 ///561 /// # Arguments562 ///563 /// * `collection_id`: ID of the modified collection.564 /// * `properties`: Vector of key-value pairs stored as the collection's metadata.565 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.566 #[weight = T::CommonWeightInfo::set_collection_properties(properties.len() as u32)]567 pub fn set_collection_properties(568 origin,569 collection_id: CollectionId,570 properties: Vec<Property>571 ) -> DispatchResultWithPostInfo {572 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);573574 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);575576 dispatch_tx::<T, _>(collection_id, |d| d.set_collection_properties(sender, properties))577 }578579 /// Delete specified collection properties.580 ///581 /// # Permissions582 ///583 /// * Collection Owner584 /// * Collection Admin585 ///586 /// # Arguments587 ///588 /// * `collection_id`: ID of the modified collection.589 /// * `property_keys`: Vector of keys of the properties to be deleted.590 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.591 #[weight = T::CommonWeightInfo::delete_collection_properties(property_keys.len() as u32)]592 pub fn delete_collection_properties(593 origin,594 collection_id: CollectionId,595 property_keys: Vec<PropertyKey>,596 ) -> DispatchResultWithPostInfo {597 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);598599 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);600601 dispatch_tx::<T, _>(collection_id, |d| d.delete_collection_properties(&sender, property_keys))602 }603604 /// Add or change token properties according to collection's permissions.605 /// Currently properties only work with NFTs.606 ///607 /// # Permissions608 ///609 /// * Depends on collection's token property permissions and specified property mutability:610 /// * Collection owner611 /// * Collection admin612 /// * Token owner613 ///614 /// See [`set_token_property_permissions`][`Pallet::set_token_property_permissions`].615 ///616 /// # Arguments617 ///618 /// * `collection_id: ID of the collection to which the token belongs.619 /// * `token_id`: ID of the modified token.620 /// * `properties`: Vector of key-value pairs stored as the token's metadata.621 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.622 #[weight = T::CommonWeightInfo::set_token_properties(properties.len() as u32)]623 pub fn set_token_properties(624 origin,625 collection_id: CollectionId,626 token_id: TokenId,627 properties: Vec<Property>628 ) -> DispatchResultWithPostInfo {629 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);630631 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);632 let budget = budget::Value::new(NESTING_BUDGET);633634 dispatch_tx::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties, &budget))635 }636637 /// Delete specified token properties. Currently properties only work with NFTs.638 ///639 /// # Permissions640 ///641 /// * Depends on collection's token property permissions and specified property mutability:642 /// * Collection owner643 /// * Collection admin644 /// * Token owner645 ///646 /// # Arguments647 ///648 /// * `collection_id`: ID of the collection to which the token belongs.649 /// * `token_id`: ID of the modified token.650 /// * `property_keys`: Vector of keys of the properties to be deleted.651 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.652 #[weight = T::CommonWeightInfo::delete_token_properties(property_keys.len() as u32)]653 pub fn delete_token_properties(654 origin,655 collection_id: CollectionId,656 token_id: TokenId,657 property_keys: Vec<PropertyKey>658 ) -> DispatchResultWithPostInfo {659 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);660661 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);662 let budget = budget::Value::new(NESTING_BUDGET);663664 dispatch_tx::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys, &budget))665 }666667 /// Add or change token property permissions of a collection.668 ///669 /// Without a permission for a particular key, a property with that key670 /// cannot be created in a token.671 ///672 /// # Permissions673 ///674 /// * Collection owner675 /// * Collection admin676 ///677 /// # Arguments678 ///679 /// * `collection_id`: ID of the modified collection.680 /// * `property_permissions`: Vector of permissions for property keys.681 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.682 #[weight = T::CommonWeightInfo::set_token_property_permissions(property_permissions.len() as u32)]683 pub fn set_token_property_permissions(684 origin,685 collection_id: CollectionId,686 property_permissions: Vec<PropertyKeyPermission>,687 ) -> DispatchResultWithPostInfo {688 ensure!(!property_permissions.is_empty(), Error::<T>::EmptyArgument);689690 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);691692 dispatch_tx::<T, _>(collection_id, |d| d.set_token_property_permissions(&sender, property_permissions))693 }694695 /// Create multiple items within a collection with explicitly specified initial parameters.696 ///697 /// # Permissions698 ///699 /// * Collection owner700 /// * Collection admin701 /// * Anyone if702 /// * Allow List is enabled, and703 /// * Address is added to allow list, and704 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])705 ///706 /// # Arguments707 ///708 /// * `collection_id`: ID of the collection to which the tokens would belong.709 /// * `data`: Explicit item creation data.710 #[weight = T::CommonWeightInfo::create_multiple_items_ex(&data)]711 pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {712 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);713 let budget = budget::Value::new(NESTING_BUDGET);714715 dispatch_tx::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))716 }717718 /// Completely allow or disallow transfers for a particular collection.719 ///720 /// # Permissions721 ///722 /// * Collection owner723 ///724 /// # Arguments725 ///726 /// * `collection_id`: ID of the collection.727 /// * `value`: New value of the flag, are transfers allowed?728 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]729 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {730 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);731 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;732 target_collection.check_is_internal()?;733 target_collection.check_is_owner(&sender)?;734735 // =========736737 target_collection.limits.transfers_enabled = Some(value);738 target_collection.save()739 }740741 /// Destroy an item.742 ///743 /// # Permissions744 ///745 /// * Collection owner746 /// * Collection admin747 /// * Current item owner748 ///749 /// # Arguments750 ///751 /// * `collection_id`: ID of the collection to which the item belongs.752 /// * `item_id`: ID of item to burn.753 /// * `value`: Number of pieces of the item to destroy.754 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.755 /// * Fungible Mode: The desired number of pieces to burn.756 /// * Re-Fungible Mode: The desired number of pieces to burn.757 #[weight = T::CommonWeightInfo::burn_item()]758 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {759 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);760761 let post_info = dispatch_tx::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;762 if value == 1 {763 <NftTransferBasket<T>>::remove(collection_id, item_id);764 <NftApproveBasket<T>>::remove(collection_id, item_id);765 }766 // Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?767 // <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());768 // <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));769 Ok(post_info)770 }771772 /// Destroy a token on behalf of the owner as a non-owner account.773 ///774 /// See also: [`approve`][`Pallet::approve`].775 ///776 /// After this method executes, one approval is removed from the total so that777 /// the approved address will not be able to transfer this item again from this owner.778 ///779 /// # Permissions780 ///781 /// * Collection owner782 /// * Collection admin783 /// * Current token owner784 /// * Address approved by current item owner785 ///786 /// # Arguments787 ///788 /// * `from`: The owner of the burning item.789 /// * `collection_id`: ID of the collection to which the item belongs.790 /// * `item_id`: ID of item to burn.791 /// * `value`: Number of pieces to burn.792 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.793 /// * Fungible Mode: The desired number of pieces to burn.794 /// * Re-Fungible Mode: The desired number of pieces to burn.795 #[weight = T::CommonWeightInfo::burn_from()]796 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {797 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);798 let budget = budget::Value::new(NESTING_BUDGET);799800 dispatch_tx::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))801 }802803 /// Change ownership of the token.804 ///805 /// # Permissions806 ///807 /// * Collection owner808 /// * Collection admin809 /// * Current token owner810 ///811 /// # Arguments812 ///813 /// * `recipient`: Address of token recipient.814 /// * `collection_id`: ID of the collection the item belongs to.815 /// * `item_id`: ID of the item.816 /// * Non-Fungible Mode: Required.817 /// * Fungible Mode: Ignored.818 /// * Re-Fungible Mode: Required.819 ///820 /// * `value`: Amount to transfer.821 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.822 /// * Fungible Mode: The desired number of pieces to transfer.823 /// * Re-Fungible Mode: The desired number of pieces to transfer.824 #[weight = T::CommonWeightInfo::transfer()]825 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {826 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);827 let budget = budget::Value::new(NESTING_BUDGET);828829 dispatch_tx::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))830 }831832 /// Allow a non-permissioned address to transfer or burn an item.833 ///834 /// # Permissions835 ///836 /// * Collection owner837 /// * Collection admin838 /// * Current item owner839 ///840 /// # Arguments841 ///842 /// * `spender`: Account to be approved to make specific transactions on non-owned tokens.843 /// * `collection_id`: ID of the collection the item belongs to.844 /// * `item_id`: ID of the item transactions on which are now approved.845 /// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).846 /// Set to 0 to revoke the approval.847 #[weight = T::CommonWeightInfo::approve()]848 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {849 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);850851 dispatch_tx::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))852 }853854 /// Change ownership of an item on behalf of the owner as a non-owner account.855 ///856 /// See the [`approve`][`Pallet::approve`] method for additional information.857 ///858 /// After this method executes, one approval is removed from the total so that859 /// the approved address will not be able to transfer this item again from this owner.860 ///861 /// # Permissions862 ///863 /// * Collection owner864 /// * Collection admin865 /// * Current item owner866 /// * Address approved by current item owner867 ///868 /// # Arguments869 ///870 /// * `from`: Address that currently owns the token.871 /// * `recipient`: Address of the new token-owner-to-be.872 /// * `collection_id`: ID of the collection the item.873 /// * `item_id`: ID of the item to be transferred.874 /// * `value`: Amount to transfer.875 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.876 /// * Fungible Mode: The desired number of pieces to transfer.877 /// * Re-Fungible Mode: The desired number of pieces to transfer.878 #[weight = T::CommonWeightInfo::transfer_from()]879 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {880 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);881 let budget = budget::Value::new(NESTING_BUDGET);882883 dispatch_tx::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))884 }885886 /// Set specific limits of a collection. Empty, or None fields mean chain default.887 ///888 /// # Permissions889 ///890 /// * Collection owner891 /// * Collection admin892 ///893 /// # Arguments894 ///895 /// * `collection_id`: ID of the modified collection.896 /// * `new_limit`: New limits of the collection. Fields that are not set (None)897 /// will not overwrite the old ones.898 #[weight = <SelfWeightOf<T>>::set_collection_limits()]899 pub fn set_collection_limits(900 origin,901 collection_id: CollectionId,902 new_limit: CollectionLimits,903 ) -> DispatchResult {904 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);905 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;906 <PalletCommon<T>>::update_limits(&sender, &mut target_collection, new_limit)907 }908909 /// Set specific permissions of a collection. Empty, or None fields mean chain default.910 ///911 /// # Permissions912 ///913 /// * Collection owner914 /// * Collection admin915 ///916 /// # Arguments917 ///918 /// * `collection_id`: ID of the modified collection.919 /// * `new_permission`: New permissions of the collection. Fields that are not set (None)920 /// will not overwrite the old ones.921 #[weight = <SelfWeightOf<T>>::set_collection_limits()]922 pub fn set_collection_permissions(923 origin,924 collection_id: CollectionId,925 new_permission: CollectionPermissions,926 ) -> DispatchResult {927 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);928 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;929 <PalletCommon<T>>::update_permissions(930 &sender,931 &mut target_collection,932 new_permission933 )934 }935936 /// Re-partition a refungible token, while owning all of its parts/pieces.937 ///938 /// # Permissions939 ///940 /// * Token owner (must own every part)941 ///942 /// # Arguments943 ///944 /// * `collection_id`: ID of the collection the RFT belongs to.945 /// * `token_id`: ID of the RFT.946 /// * `amount`: New number of parts/pieces into which the token shall be partitioned.947 #[weight = T::RefungibleExtensionsWeightInfo::repartition()]948 pub fn repartition(949 origin,950 collection_id: CollectionId,951 token_id: TokenId,952 amount: u128,953 ) -> DispatchResultWithPostInfo {954 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);955 dispatch_tx::<T, _>(collection_id, |d| {956 if let Some(refungible_extensions) = d.refungible_extensions() {957 refungible_extensions.repartition(&sender, token_id, amount)958 } else {959 fail!(<Error<T>>::RepartitionCalledOnNonRefungibleCollection)960 }961 })962 }963964 /// Sets or unsets the approval of a given operator.965 ///966 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.967 ///968 /// # Arguments969 ///970 /// * `owner`: Token owner971 /// * `operator`: Operator972 /// * `approve`: Should operator status be granted or revoked?973 #[weight = T::CommonWeightInfo::set_allowance_for_all()]974 pub fn set_allowance_for_all(975 origin,976 collection_id: CollectionId,977 operator: T::CrossAccountId,978 approve: bool,979 ) -> DispatchResultWithPostInfo {980 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);981 dispatch_tx::<T, _>(collection_id, |d| {982 d.set_allowance_for_all(sender, operator, approve)983 })984 }985986 /// Repairs a collection if the data was somehow corrupted.987 ///988 /// # Arguments989 ///990 /// * `collection_id`: ID of the collection to repair.991 #[weight = <SelfWeightOf<T>>::force_repair_collection()]992 pub fn force_repair_collection(993 origin,994 collection_id: CollectionId,995 ) -> DispatchResult {996 ensure_root(origin)?;997 <PalletCommon<T>>::repair_collection(collection_id)998 }9991000 /// Repairs a token if the data was somehow corrupted.1001 ///1002 /// # Arguments1003 ///1004 /// * `collection_id`: ID of the collection the item belongs to.1005 /// * `item_id`: ID of the item.1006 #[weight = T::CommonWeightInfo::force_repair_item()]1007 pub fn force_repair_item(1008 origin,1009 collection_id: CollectionId,1010 item_id: TokenId,1011 ) -> DispatchResultWithPostInfo {1012 ensure_root(origin)?;1013 dispatch_tx::<T, _>(collection_id, |d| {1014 d.repair_item(item_id)1015 })1016 }1017 }1018}10191020impl<T: Config> Pallet<T> {1021 /// Force set `sponsor` for `collection`.1022 ///1023 /// Differs from [`set_collection_sponsor`][`Pallet::set_collection_sponsor`] in that confirmation1024 /// from the `sponsor` is not required.1025 ///1026 /// # Arguments1027 ///1028 /// * `sponsor`: ID of the account of the sponsor-to-be.1029 /// * `collection_id`: ID of the modified collection.1030 pub fn force_set_sponsor(sponsor: T::AccountId, collection_id: CollectionId) -> DispatchResult {1031 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1032 target_collection.force_set_sponsor(sponsor.clone())1033 }10341035 /// Force remove `sponsor` for `collection`.1036 ///1037 /// Differs from `remove_sponsor` in that1038 /// it doesn't require consent from the `owner` of the collection.1039 ///1040 /// # Arguments1041 ///1042 /// * `collection_id`: ID of the modified collection.1043 pub fn force_remove_collection_sponsor(collection_id: CollectionId) -> DispatchResult {1044 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1045 target_collection.force_remove_sponsor()1046 }10471048 #[inline(always)]1049 pub(crate) fn destroy_collection_internal(1050 sender: T::CrossAccountId,1051 collection_id: CollectionId,1052 ) -> DispatchResult {1053 let collection = <CollectionHandle<T>>::try_get(collection_id)?;1054 collection.check_is_internal()?;10551056 T::CollectionDispatch::destroy(sender, collection)?;10571058 // TODO: basket cleanup should be moved elsewhere1059 // Maybe runtime dispatch.rs should perform it?10601061 let _ = <NftTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1062 let _ = <FungibleTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1063 let _ = <ReFungibleTransferBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);10641065 let _ = <NftApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1066 let _ = <FungibleApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1067 let _ = <RefungibleApproveBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);10681069 Ok(())1070 }1071}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//! # Unique Pallet18//!19//! A pallet governing Unique transactions.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! The Unique pallet's purpose is to be the primary interface between28//! external users and the inner structure of the Unique chains.29//!30//! It also contains an implementation of [`CollectionHelpers`][`eth`],31//! an Ethereum contract dealing with collection operations.32//!33//! ## Interface34//!35//! ### Dispatchables36//!37//! - `create_collection` - Create a collection of tokens. **Deprecated**, use `create_collection_ex`.38//! - `create_collection_ex` - Create a collection of tokens with explicit parameters.39//! - `destroy_collection` - Destroy a collection if no tokens exist within.40//! - `add_to_allow_list` - Add an address to allow list.41//! - `remove_from_allow_list` - Remove an address from allow list.42//! - `change_collection_owner` - Change the owner of the collection.43//! - `add_collection_admin` - Add an admin to a collection.44//! - `remove_collection_admin` - Remove admin of a collection.45//! - `set_collection_sponsor` - Invite a new collection sponsor.46//! - `confirm_sponsorship` - Confirm own sponsorship of a collection, becoming the sponsor.47//! - `remove_collection_sponsor` - Remove a sponsor from a collection.48//! - `create_item` - Create an item within a collection.49//! - `create_multiple_items` - Create multiple items within a collection.50//! - `set_collection_properties` - Add or change collection properties.51//! - `delete_collection_properties` - Delete specified collection properties.52//! - `set_token_properties` - Add or change token properties.53//! - `delete_token_properties` - Delete token properties.54//! - `set_token_property_permissions` - Add or change token property permissions of a collection.55//! - `create_multiple_items_ex` - Create multiple items within a collection with explicitly specified initial parameters.56//! - `set_transfers_enabled_flag` - Completely allow or disallow transfers for a particular collection.57//! - `burn_item` - Destroy an item.58//! - `burn_from` - Destroy an item on behalf of the owner as a non-owner account.59//! - `transfer` - Change ownership of the token.60//! - `transfer_from` - Change ownership of the token on behalf of the owner as a non-owner account.61//! - `approve` - Allow a non-permissioned address to transfer or burn an item.62//! - `set_collection_limits` - Set specific limits of a collection.63//! - `set_collection_permissions` - Set specific permissions of a collection.64//! - `repartition` - Re-partition a refungible token, while owning all of its parts.6566#![recursion_limit = "1024"]67#![cfg_attr(not(feature = "std"), no_std)]68#![allow(69 clippy::too_many_arguments,70 clippy::unnecessary_mut_passed,71 clippy::unused_unit72)]7374extern crate alloc;7576use frame_support::{77 decl_module, decl_storage, decl_error,78 dispatch::DispatchResult,79 ensure, fail,80 weights::{Weight},81 pallet_prelude::{DispatchResultWithPostInfo, ConstU32},82 BoundedVec,83};84use scale_info::TypeInfo;85use frame_system::{self as system, ensure_signed, ensure_root};86use sp_std::{vec, vec::Vec};87use up_data_structs::{88 MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,89 MAX_PROPERTIES_PER_ITEM, MAX_PROPERTY_KEY_LENGTH, MAX_PROPERTY_VALUE_LENGTH,90 MAX_COLLECTION_PROPERTIES_SIZE, COLLECTION_ADMINS_LIMIT, MAX_TOKEN_PROPERTIES_SIZE,91 CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,92 CreateCollectionData, CreateItemExData, budget, Property, PropertyKey, PropertyKeyPermission,93};94use pallet_evm::account::CrossAccountId;95use pallet_common::{96 CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_tx,97 dispatch::CollectionDispatch, RefungibleExtensionsWeightInfo,98};99pub mod eth;100101#[cfg(feature = "runtime-benchmarks")]102pub mod benchmarking;103pub mod weights;104use weights::WeightInfo;105106/// A maximum number of levels of depth in the token nesting tree.107pub const NESTING_BUDGET: u32 = 5;108109decl_error! {110 /// Errors for the common Unique transactions.111 pub enum Error for Module<T: Config> {112 /// Decimal_points parameter must be lower than [`up_data_structs::MAX_DECIMAL_POINTS`].113 CollectionDecimalPointLimitExceeded,114 /// Length of items properties must be greater than 0.115 EmptyArgument,116 /// Repertition is only supported by refungible collection.117 RepartitionCalledOnNonRefungibleCollection,118 }119}120121/// Configuration trait of this pallet.122pub trait Config: system::Config + pallet_common::Config + Sized + TypeInfo {123 /// Weight information for extrinsics in this pallet.124 type WeightInfo: WeightInfo;125126 /// Weight information for common pallet operations.127 type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;128129 /// Weight info information for extra refungible pallet operations.130 type RefungibleExtensionsWeightInfo: RefungibleExtensionsWeightInfo;131}132133type SelfWeightOf<T> = <T as Config>::WeightInfo;134135// # Used definitions136//137// ## User control levels138//139// chain-controlled - key is uncontrolled by user140// i.e autoincrementing index141// can use non-cryptographic hash142// real - key is controlled by user143// but it is hard to generate enough colliding values, i.e owner of signed txs144// can use non-cryptographic hash145// controlled - key is completly controlled by users146// i.e maps with mutable keys147// should use cryptographic hash148//149// ## User control level downgrade reasons150//151// ?1 - chain-controlled -> controlled152// collections/tokens can be destroyed, resulting in massive holes153// ?2 - chain-controlled -> controlled154// same as ?1, but can be only added, resulting in easier exploitation155// ?3 - real -> controlled156// no confirmation required, so addresses can be easily generated157decl_storage! {158 trait Store for Module<T: Config> as Unique {159160 //#region Private members161 /// Used for migrations162 ChainVersion: u64;163 //#endregion164165 //#region Tokens transfer sponosoring rate limit baskets166 /// (Collection id (controlled?2), who created (real))167 /// TODO: Off chain worker should remove from this map when collection gets removed168 pub CreateItemBasket get(fn create_item_basket): map hasher(blake2_128_concat) (CollectionId, T::AccountId) => Option<T::BlockNumber>;169 /// Collection id (controlled?2), token id (controlled?2)170 pub NftTransferBasket get(fn nft_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;171 /// Collection id (controlled?2), owning user (real)172 pub FungibleTransferBasket get(fn fungible_transfer_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;173 /// Collection id (controlled?2), token id (controlled?2)174 pub ReFungibleTransferBasket get(fn refungible_transfer_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;175 //#endregion176177 /// Variable metadata sponsoring178 /// Collection id (controlled?2), token id (controlled?2)179 #[deprecated]180 pub VariableMetaDataBasket get(fn variable_meta_data_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;181 /// Last sponsoring of token property setting // todo:doc rephrase this and the following182 pub TokenPropertyBasket get(fn token_property_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;183184 /// Last sponsoring of NFT approval in a collection185 pub NftApproveBasket get(fn nft_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<T::BlockNumber>;186 /// Last sponsoring of fungible tokens approval in a collection187 pub FungibleApproveBasket get(fn fungible_approve_basket): double_map hasher(blake2_128_concat) CollectionId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;188 /// Last sponsoring of RFT approval in a collection189 pub RefungibleApproveBasket get(fn refungible_approve_basket): nmap hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId, hasher(twox_64_concat) T::AccountId => Option<T::BlockNumber>;190 }191}192193decl_module! {194 /// Type alias to Pallet, to be used by construct_runtime.195 pub struct Module<T: Config> for enum Call196 where197 origin: T::RuntimeOrigin198 {199 type Error = Error<T>;200201 #[doc = "A maximum number of levels of depth in the token nesting tree."]202 const NESTING_BUDGET: u32 = NESTING_BUDGET;203204 #[doc = "Maximal length of a collection name."]205 const MAX_COLLECTION_NAME_LENGTH: u32 = MAX_COLLECTION_NAME_LENGTH;206207 #[doc = "Maximal length of a collection description."]208 const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = MAX_COLLECTION_DESCRIPTION_LENGTH;209210 #[doc = "Maximal length of a token prefix."]211 const MAX_TOKEN_PREFIX_LENGTH: u32 = MAX_TOKEN_PREFIX_LENGTH;212213 #[doc = "Maximum admins per collection."]214 const COLLECTION_ADMINS_LIMIT: u32 = COLLECTION_ADMINS_LIMIT;215216 #[doc = "Maximal length of a property key."]217 const MAX_PROPERTY_KEY_LENGTH: u32 = MAX_PROPERTY_KEY_LENGTH;218219 #[doc = "Maximal length of a property value."]220 const MAX_PROPERTY_VALUE_LENGTH: u32 = MAX_PROPERTY_VALUE_LENGTH;221222 #[doc = "A maximum number of token properties."]223 const MAX_PROPERTIES_PER_ITEM: u32 = MAX_PROPERTIES_PER_ITEM;224225 #[doc = "Maximum size for all collection properties."]226 const MAX_COLLECTION_PROPERTIES_SIZE: u32 = MAX_COLLECTION_PROPERTIES_SIZE;227228 #[doc = "Maximum size of all token properties."]229 const MAX_TOKEN_PROPERTIES_SIZE: u32 = MAX_TOKEN_PROPERTIES_SIZE;230231 #[doc = "Default NFT collection limit."]232 const NFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::NFT);233234 #[doc = "Default RFT collection limit."]235 const RFT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::ReFungible);236237 #[doc = "Default FT collection limit."]238 const FT_DEFAULT_COLLECTION_LIMITS: CollectionLimits = CollectionLimits::with_default_limits(CollectionMode::Fungible(0));239240 fn on_initialize(_now: T::BlockNumber) -> Weight {241 Weight::zero()242 }243244 fn on_runtime_upgrade() -> Weight {245 Weight::zero()246 }247248 /// Create a collection of tokens.249 ///250 /// Each Token may have multiple properties encoded as an array of bytes251 /// of certain length. The initial owner of the collection is set252 /// to the address that signed the transaction and can be changed later.253 ///254 /// Prefer the more advanced [`create_collection_ex`][`Pallet::create_collection_ex`] instead.255 ///256 /// # Permissions257 ///258 /// * Anyone - becomes the owner of the new collection.259 ///260 /// # Arguments261 ///262 /// * `collection_name`: Wide-character string with collection name263 /// (limit [`MAX_COLLECTION_NAME_LENGTH`]).264 /// * `collection_description`: Wide-character string with collection description265 /// (limit [`MAX_COLLECTION_DESCRIPTION_LENGTH`]).266 /// * `token_prefix`: Byte string containing the token prefix to mark a collection267 /// to which a token belongs (limit [`MAX_TOKEN_PREFIX_LENGTH`]).268 /// * `mode`: Type of items stored in the collection and type dependent data.269 // returns collection ID270 #[weight = <SelfWeightOf<T>>::create_collection()]271 #[deprecated(note = "`create_collection_ex` is more up-to-date and advanced, prefer it instead")]272 pub fn create_collection(273 origin,274 collection_name: BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>,275 collection_description: BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>,276 token_prefix: BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>,277 mode: CollectionMode278 ) -> DispatchResult {279 let data: CreateCollectionData<T::AccountId> = CreateCollectionData {280 name: collection_name,281 description: collection_description,282 token_prefix,283 mode,284 ..Default::default()285 };286 Self::create_collection_ex(origin, data)287 }288289 /// Create a collection with explicit parameters.290 ///291 /// Prefer it to the deprecated [`create_collection`][`Pallet::create_collection`] method.292 ///293 /// # Permissions294 ///295 /// * Anyone - becomes the owner of the new collection.296 ///297 /// # Arguments298 ///299 /// * `data`: Explicit data of a collection used for its creation.300 #[weight = <SelfWeightOf<T>>::create_collection()]301 pub fn create_collection_ex(origin, data: CreateCollectionData<T::AccountId>) -> DispatchResult {302 let sender = ensure_signed(origin)?;303304 // =========305 let sender = T::CrossAccountId::from_sub(sender);306 let _id = T::CollectionDispatch::create(sender.clone(), sender, data, Default::default())?;307308 Ok(())309 }310311 /// Destroy a collection if no tokens exist within.312 ///313 /// # Permissions314 ///315 /// * Collection owner316 ///317 /// # Arguments318 ///319 /// * `collection_id`: Collection to destroy.320 #[weight = <SelfWeightOf<T>>::destroy_collection()]321 pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {322 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);323324 Self::destroy_collection_internal(sender, collection_id)325 }326327 /// Add an address to allow list.328 ///329 /// # Permissions330 ///331 /// * Collection owner332 /// * Collection admin333 ///334 /// # Arguments335 ///336 /// * `collection_id`: ID of the modified collection.337 /// * `address`: ID of the address to be added to the allowlist.338 #[weight = <SelfWeightOf<T>>::add_to_allow_list()]339 pub fn add_to_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{340341 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);342 let collection = <CollectionHandle<T>>::try_get(collection_id)?;343 collection.check_is_internal()?;344345 <PalletCommon<T>>::toggle_allowlist(346 &collection,347 &sender,348 &address,349 true,350 )?;351352 Ok(())353 }354355 /// Remove an address from allow list.356 ///357 /// # Permissions358 ///359 /// * Collection owner360 /// * Collection admin361 ///362 /// # Arguments363 ///364 /// * `collection_id`: ID of the modified collection.365 /// * `address`: ID of the address to be removed from the allowlist.366 #[weight = <SelfWeightOf<T>>::remove_from_allow_list()]367 pub fn remove_from_allow_list(origin, collection_id: CollectionId, address: T::CrossAccountId) -> DispatchResult{368369 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);370 let collection = <CollectionHandle<T>>::try_get(collection_id)?;371 collection.check_is_internal()?;372373 <PalletCommon<T>>::toggle_allowlist(374 &collection,375 &sender,376 &address,377 false,378 )?;379380 Ok(())381 }382383 /// Change the owner of the collection.384 ///385 /// # Permissions386 ///387 /// * Collection owner388 ///389 /// # Arguments390 ///391 /// * `collection_id`: ID of the modified collection.392 /// * `new_owner`: ID of the account that will become the owner.393 #[weight = <SelfWeightOf<T>>::change_collection_owner()]394 pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {395 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);396 let new_owner = T::CrossAccountId::from_sub(new_owner);397 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;398 target_collection.change_owner(sender, new_owner.clone())399 }400401 /// Add an admin to a collection.402 ///403 /// NFT Collection can be controlled by multiple admin addresses404 /// (some which can also be servers, for example). Admins can issue405 /// and burn NFTs, as well as add and remove other admins,406 /// but cannot change NFT or Collection ownership.407 ///408 /// # Permissions409 ///410 /// * Collection owner411 /// * Collection admin412 ///413 /// # Arguments414 ///415 /// * `collection_id`: ID of the Collection to add an admin for.416 /// * `new_admin`: Address of new admin to add.417 #[weight = <SelfWeightOf<T>>::add_collection_admin()]418 pub fn add_collection_admin(origin, collection_id: CollectionId, new_admin_id: T::CrossAccountId) -> DispatchResult {419 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);420 let collection = <CollectionHandle<T>>::try_get(collection_id)?;421 <PalletCommon<T>>::toggle_admin(&collection, &sender, &new_admin_id, true)422 }423424 /// Remove admin of a collection.425 ///426 /// An admin address can remove itself. List of admins may become empty,427 /// in which case only Collection Owner will be able to add an Admin.428 ///429 /// # Permissions430 ///431 /// * Collection owner432 /// * Collection admin433 ///434 /// # Arguments435 ///436 /// * `collection_id`: ID of the collection to remove the admin for.437 /// * `account_id`: Address of the admin to remove.438 #[weight = <SelfWeightOf<T>>::remove_collection_admin()]439 pub fn remove_collection_admin(origin, collection_id: CollectionId, account_id: T::CrossAccountId) -> DispatchResult {440 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);441 let collection = <CollectionHandle<T>>::try_get(collection_id)?;442 <PalletCommon<T>>::toggle_admin(&collection, &sender, &account_id, false)443 }444445 /// Set (invite) a new collection sponsor.446 ///447 /// If successful, confirmation from the sponsor-to-be will be pending.448 ///449 /// # Permissions450 ///451 /// * Collection owner452 /// * Collection admin453 ///454 /// # Arguments455 ///456 /// * `collection_id`: ID of the modified collection.457 /// * `new_sponsor`: ID of the account of the sponsor-to-be.458 #[weight = <SelfWeightOf<T>>::set_collection_sponsor()]459 pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {460 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);461 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;462 target_collection.set_sponsor(&sender, new_sponsor.clone())463 }464465 /// Confirm own sponsorship of a collection, becoming the sponsor.466 ///467 /// An invitation must be pending, see [`set_collection_sponsor`][`Pallet::set_collection_sponsor`].468 /// Sponsor can pay the fees of a transaction instead of the sender,469 /// but only within specified limits.470 ///471 /// # Permissions472 ///473 /// * Sponsor-to-be474 ///475 /// # Arguments476 ///477 /// * `collection_id`: ID of the collection with the pending sponsor.478 #[weight = <SelfWeightOf<T>>::confirm_sponsorship()]479 pub fn confirm_sponsorship(origin, collection_id: CollectionId) -> DispatchResult {480 let sender = ensure_signed(origin)?;481 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;482 target_collection.confirm_sponsorship(&sender)483 }484485 /// Remove a collection's a sponsor, making everyone pay for their own transactions.486 ///487 /// # Permissions488 ///489 /// * Collection owner490 ///491 /// # Arguments492 ///493 /// * `collection_id`: ID of the collection with the sponsor to remove.494 #[weight = <SelfWeightOf<T>>::remove_collection_sponsor()]495 pub fn remove_collection_sponsor(origin, collection_id: CollectionId) -> DispatchResult {496 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);497 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;498 target_collection.remove_sponsor(&sender)499 }500501 /// Mint an item within a collection.502 ///503 /// A collection must exist first, see [`create_collection_ex`][`Pallet::create_collection_ex`].504 ///505 /// # Permissions506 ///507 /// * Collection owner508 /// * Collection admin509 /// * Anyone if510 /// * Allow List is enabled, and511 /// * Address is added to allow list, and512 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])513 ///514 /// # Arguments515 ///516 /// * `collection_id`: ID of the collection to which an item would belong.517 /// * `owner`: Address of the initial owner of the item.518 /// * `data`: Token data describing the item to store on chain.519 #[weight = T::CommonWeightInfo::create_item()]520 pub fn create_item(origin, collection_id: CollectionId, owner: T::CrossAccountId, data: CreateItemData) -> DispatchResultWithPostInfo {521 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);522 let budget = budget::Value::new(NESTING_BUDGET);523524 dispatch_tx::<T, _>(collection_id, |d| d.create_item(sender, owner, data, &budget))525 }526527 /// Create multiple items within a collection.528 ///529 /// A collection must exist first, see [`create_collection_ex`][`Pallet::create_collection_ex`].530 ///531 /// # Permissions532 ///533 /// * Collection owner534 /// * Collection admin535 /// * Anyone if536 /// * Allow List is enabled, and537 /// * Address is added to the allow list, and538 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])539 ///540 /// # Arguments541 ///542 /// * `collection_id`: ID of the collection to which the tokens would belong.543 /// * `owner`: Address of the initial owner of the tokens.544 /// * `items_data`: Vector of data describing each item to be created.545 #[weight = T::CommonWeightInfo::create_multiple_items(&items_data)]546 pub fn create_multiple_items(origin, collection_id: CollectionId, owner: T::CrossAccountId, items_data: Vec<CreateItemData>) -> DispatchResultWithPostInfo {547 ensure!(!items_data.is_empty(), Error::<T>::EmptyArgument);548 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);549 let budget = budget::Value::new(NESTING_BUDGET);550551 dispatch_tx::<T, _>(collection_id, |d| d.create_multiple_items(sender, owner, items_data, &budget))552 }553554 /// Add or change collection properties.555 ///556 /// # Permissions557 ///558 /// * Collection owner559 /// * Collection admin560 ///561 /// # Arguments562 ///563 /// * `collection_id`: ID of the modified collection.564 /// * `properties`: Vector of key-value pairs stored as the collection's metadata.565 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.566 #[weight = T::CommonWeightInfo::set_collection_properties(properties.len() as u32)]567 pub fn set_collection_properties(568 origin,569 collection_id: CollectionId,570 properties: Vec<Property>571 ) -> DispatchResultWithPostInfo {572 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);573574 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);575576 dispatch_tx::<T, _>(collection_id, |d| d.set_collection_properties(sender, properties))577 }578579 /// Delete specified collection properties.580 ///581 /// # Permissions582 ///583 /// * Collection Owner584 /// * Collection Admin585 ///586 /// # Arguments587 ///588 /// * `collection_id`: ID of the modified collection.589 /// * `property_keys`: Vector of keys of the properties to be deleted.590 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.591 #[weight = T::CommonWeightInfo::delete_collection_properties(property_keys.len() as u32)]592 pub fn delete_collection_properties(593 origin,594 collection_id: CollectionId,595 property_keys: Vec<PropertyKey>,596 ) -> DispatchResultWithPostInfo {597 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);598599 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);600601 dispatch_tx::<T, _>(collection_id, |d| d.delete_collection_properties(&sender, property_keys))602 }603604 /// Add or change token properties according to collection's permissions.605 /// Currently properties only work with NFTs.606 ///607 /// # Permissions608 ///609 /// * Depends on collection's token property permissions and specified property mutability:610 /// * Collection owner611 /// * Collection admin612 /// * Token owner613 ///614 /// See [`set_token_property_permissions`][`Pallet::set_token_property_permissions`].615 ///616 /// # Arguments617 ///618 /// * `collection_id: ID of the collection to which the token belongs.619 /// * `token_id`: ID of the modified token.620 /// * `properties`: Vector of key-value pairs stored as the token's metadata.621 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.622 #[weight = T::CommonWeightInfo::set_token_properties(properties.len() as u32)]623 pub fn set_token_properties(624 origin,625 collection_id: CollectionId,626 token_id: TokenId,627 properties: Vec<Property>628 ) -> DispatchResultWithPostInfo {629 ensure!(!properties.is_empty(), Error::<T>::EmptyArgument);630631 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);632 let budget = budget::Value::new(NESTING_BUDGET);633634 dispatch_tx::<T, _>(collection_id, |d| d.set_token_properties(sender, token_id, properties, &budget))635 }636637 /// Delete specified token properties. Currently properties only work with NFTs.638 ///639 /// # Permissions640 ///641 /// * Depends on collection's token property permissions and specified property mutability:642 /// * Collection owner643 /// * Collection admin644 /// * Token owner645 ///646 /// # Arguments647 ///648 /// * `collection_id`: ID of the collection to which the token belongs.649 /// * `token_id`: ID of the modified token.650 /// * `property_keys`: Vector of keys of the properties to be deleted.651 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.652 #[weight = T::CommonWeightInfo::delete_token_properties(property_keys.len() as u32)]653 pub fn delete_token_properties(654 origin,655 collection_id: CollectionId,656 token_id: TokenId,657 property_keys: Vec<PropertyKey>658 ) -> DispatchResultWithPostInfo {659 ensure!(!property_keys.is_empty(), Error::<T>::EmptyArgument);660661 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);662 let budget = budget::Value::new(NESTING_BUDGET);663664 dispatch_tx::<T, _>(collection_id, |d| d.delete_token_properties(sender, token_id, property_keys, &budget))665 }666667 /// Add or change token property permissions of a collection.668 ///669 /// Without a permission for a particular key, a property with that key670 /// cannot be created in a token.671 ///672 /// # Permissions673 ///674 /// * Collection owner675 /// * Collection admin676 ///677 /// # Arguments678 ///679 /// * `collection_id`: ID of the modified collection.680 /// * `property_permissions`: Vector of permissions for property keys.681 /// Keys support Latin letters, `-`, `_`, and `.` as symbols.682 #[weight = T::CommonWeightInfo::set_token_property_permissions(property_permissions.len() as u32)]683 pub fn set_token_property_permissions(684 origin,685 collection_id: CollectionId,686 property_permissions: Vec<PropertyKeyPermission>,687 ) -> DispatchResultWithPostInfo {688 ensure!(!property_permissions.is_empty(), Error::<T>::EmptyArgument);689690 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);691692 dispatch_tx::<T, _>(collection_id, |d| d.set_token_property_permissions(&sender, property_permissions))693 }694695 /// Create multiple items within a collection with explicitly specified initial parameters.696 ///697 /// # Permissions698 ///699 /// * Collection owner700 /// * Collection admin701 /// * Anyone if702 /// * Allow List is enabled, and703 /// * Address is added to allow list, and704 /// * MintPermission is enabled (see [`set_collection_permissions`][`Pallet::set_collection_permissions`])705 ///706 /// # Arguments707 ///708 /// * `collection_id`: ID of the collection to which the tokens would belong.709 /// * `data`: Explicit item creation data.710 #[weight = T::CommonWeightInfo::create_multiple_items_ex(&data)]711 pub fn create_multiple_items_ex(origin, collection_id: CollectionId, data: CreateItemExData<T::CrossAccountId>) -> DispatchResultWithPostInfo {712 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);713 let budget = budget::Value::new(NESTING_BUDGET);714715 dispatch_tx::<T, _>(collection_id, |d| d.create_multiple_items_ex(sender, data, &budget))716 }717718 /// Completely allow or disallow transfers for a particular collection.719 ///720 /// # Permissions721 ///722 /// * Collection owner723 ///724 /// # Arguments725 ///726 /// * `collection_id`: ID of the collection.727 /// * `value`: New value of the flag, are transfers allowed?728 #[weight = <SelfWeightOf<T>>::set_transfers_enabled_flag()]729 pub fn set_transfers_enabled_flag(origin, collection_id: CollectionId, value: bool) -> DispatchResult {730 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);731 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;732 target_collection.check_is_internal()?;733 target_collection.check_is_owner(&sender)?;734735 // =========736737 target_collection.limits.transfers_enabled = Some(value);738 target_collection.save()739 }740741 /// Destroy an item.742 ///743 /// # Permissions744 ///745 /// * Collection owner746 /// * Collection admin747 /// * Current item owner748 ///749 /// # Arguments750 ///751 /// * `collection_id`: ID of the collection to which the item belongs.752 /// * `item_id`: ID of item to burn.753 /// * `value`: Number of pieces of the item to destroy.754 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.755 /// * Fungible Mode: The desired number of pieces to burn.756 /// * Re-Fungible Mode: The desired number of pieces to burn.757 #[weight = T::CommonWeightInfo::burn_item()]758 pub fn burn_item(origin, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {759 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);760761 let post_info = dispatch_tx::<T, _>(collection_id, |d| d.burn_item(sender, item_id, value))?;762 if value == 1 {763 <NftTransferBasket<T>>::remove(collection_id, item_id);764 <NftApproveBasket<T>>::remove(collection_id, item_id);765 }766 // Those maps should be cleared only if token disappears completly, need to move this part of logic to pallets?767 // <FungibleApproveBasket<T>>::remove(collection_id, sender.as_sub());768 // <RefungibleApproveBasket<T>>::remove((collection_id, item_id, sender.as_sub()));769 Ok(post_info)770 }771772 /// Destroy a token on behalf of the owner as a non-owner account.773 ///774 /// See also: [`approve`][`Pallet::approve`].775 ///776 /// After this method executes, one approval is removed from the total so that777 /// the approved address will not be able to transfer this item again from this owner.778 ///779 /// # Permissions780 ///781 /// * Collection owner782 /// * Collection admin783 /// * Current token owner784 /// * Address approved by current item owner785 ///786 /// # Arguments787 ///788 /// * `from`: The owner of the burning item.789 /// * `collection_id`: ID of the collection to which the item belongs.790 /// * `item_id`: ID of item to burn.791 /// * `value`: Number of pieces to burn.792 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.793 /// * Fungible Mode: The desired number of pieces to burn.794 /// * Re-Fungible Mode: The desired number of pieces to burn.795 #[weight = T::CommonWeightInfo::burn_from()]796 pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {797 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);798 let budget = budget::Value::new(NESTING_BUDGET);799800 dispatch_tx::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))801 }802803 /// Change ownership of the token.804 ///805 /// # Permissions806 ///807 /// * Collection owner808 /// * Collection admin809 /// * Current token owner810 ///811 /// # Arguments812 ///813 /// * `recipient`: Address of token recipient.814 /// * `collection_id`: ID of the collection the item belongs to.815 /// * `item_id`: ID of the item.816 /// * Non-Fungible Mode: Required.817 /// * Fungible Mode: Ignored.818 /// * Re-Fungible Mode: Required.819 ///820 /// * `value`: Amount to transfer.821 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.822 /// * Fungible Mode: The desired number of pieces to transfer.823 /// * Re-Fungible Mode: The desired number of pieces to transfer.824 #[weight = T::CommonWeightInfo::transfer()]825 pub fn transfer(origin, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {826 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);827 let budget = budget::Value::new(NESTING_BUDGET);828829 dispatch_tx::<T, _>(collection_id, |d| d.transfer(sender, recipient, item_id, value, &budget))830 }831832 /// Allow a non-permissioned address to transfer or burn an item.833 ///834 /// # Permissions835 ///836 /// * Collection owner837 /// * Collection admin838 /// * Current item owner839 ///840 /// # Arguments841 ///842 /// * `spender`: Account to be approved to make specific transactions on non-owned tokens.843 /// * `collection_id`: ID of the collection the item belongs to.844 /// * `item_id`: ID of the item transactions on which are now approved.845 /// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).846 /// Set to 0 to revoke the approval.847 #[weight = T::CommonWeightInfo::approve()]848 pub fn approve(origin, spender: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {849 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);850851 dispatch_tx::<T, _>(collection_id, |d| d.approve(sender, spender, item_id, amount))852 }853854 /// Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.855 ///856 /// # Permissions857 ///858 /// * Collection owner859 /// * Collection admin860 /// * Current item owner861 ///862 /// # Arguments863 ///864 /// * `from`: Owner's account eth mirror865 /// * `to`: Account to be approved to make specific transactions on non-owned tokens.866 /// * `collection_id`: ID of the collection the item belongs to.867 /// * `item_id`: ID of the item transactions on which are now approved.868 /// * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).869 /// Set to 0 to revoke the approval.870 #[weight = T::CommonWeightInfo::approve_from()]871 pub fn approve_from(origin, from:T::CrossAccountId, to: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, amount: u128) -> DispatchResultWithPostInfo {872 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);873874 dispatch_tx::<T, _>(collection_id, |d| d.approve_from(sender, from, to, item_id, amount))875 }876877 /// Change ownership of an item on behalf of the owner as a non-owner account.878 ///879 /// See the [`approve`][`Pallet::approve`] method for additional information.880 ///881 /// After this method executes, one approval is removed from the total so that882 /// the approved address will not be able to transfer this item again from this owner.883 ///884 /// # Permissions885 ///886 /// * Collection owner887 /// * Collection admin888 /// * Current item owner889 /// * Address approved by current item owner890 ///891 /// # Arguments892 ///893 /// * `from`: Address that currently owns the token.894 /// * `recipient`: Address of the new token-owner-to-be.895 /// * `collection_id`: ID of the collection the item.896 /// * `item_id`: ID of the item to be transferred.897 /// * `value`: Amount to transfer.898 /// * Non-Fungible Mode: An NFT is indivisible, there is always 1 corresponding to an ID.899 /// * Fungible Mode: The desired number of pieces to transfer.900 /// * Re-Fungible Mode: The desired number of pieces to transfer.901 #[weight = T::CommonWeightInfo::transfer_from()]902 pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {903 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);904 let budget = budget::Value::new(NESTING_BUDGET);905906 dispatch_tx::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))907 }908909 /// Set specific limits of a collection. Empty, or None fields mean chain default.910 ///911 /// # Permissions912 ///913 /// * Collection owner914 /// * Collection admin915 ///916 /// # Arguments917 ///918 /// * `collection_id`: ID of the modified collection.919 /// * `new_limit`: New limits of the collection. Fields that are not set (None)920 /// will not overwrite the old ones.921 #[weight = <SelfWeightOf<T>>::set_collection_limits()]922 pub fn set_collection_limits(923 origin,924 collection_id: CollectionId,925 new_limit: CollectionLimits,926 ) -> DispatchResult {927 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);928 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;929 <PalletCommon<T>>::update_limits(&sender, &mut target_collection, new_limit)930 }931932 /// Set specific permissions of a collection. Empty, or None fields mean chain default.933 ///934 /// # Permissions935 ///936 /// * Collection owner937 /// * Collection admin938 ///939 /// # Arguments940 ///941 /// * `collection_id`: ID of the modified collection.942 /// * `new_permission`: New permissions of the collection. Fields that are not set (None)943 /// will not overwrite the old ones.944 #[weight = <SelfWeightOf<T>>::set_collection_limits()]945 pub fn set_collection_permissions(946 origin,947 collection_id: CollectionId,948 new_permission: CollectionPermissions,949 ) -> DispatchResult {950 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);951 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;952 <PalletCommon<T>>::update_permissions(953 &sender,954 &mut target_collection,955 new_permission956 )957 }958959 /// Re-partition a refungible token, while owning all of its parts/pieces.960 ///961 /// # Permissions962 ///963 /// * Token owner (must own every part)964 ///965 /// # Arguments966 ///967 /// * `collection_id`: ID of the collection the RFT belongs to.968 /// * `token_id`: ID of the RFT.969 /// * `amount`: New number of parts/pieces into which the token shall be partitioned.970 #[weight = T::RefungibleExtensionsWeightInfo::repartition()]971 pub fn repartition(972 origin,973 collection_id: CollectionId,974 token_id: TokenId,975 amount: u128,976 ) -> DispatchResultWithPostInfo {977 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);978 dispatch_tx::<T, _>(collection_id, |d| {979 if let Some(refungible_extensions) = d.refungible_extensions() {980 refungible_extensions.repartition(&sender, token_id, amount)981 } else {982 fail!(<Error<T>>::RepartitionCalledOnNonRefungibleCollection)983 }984 })985 }986987 /// Sets or unsets the approval of a given operator.988 ///989 /// The `operator` is allowed to transfer all tokens of the `owner` on their behalf.990 ///991 /// # Arguments992 ///993 /// * `owner`: Token owner994 /// * `operator`: Operator995 /// * `approve`: Should operator status be granted or revoked?996 #[weight = T::CommonWeightInfo::set_allowance_for_all()]997 pub fn set_allowance_for_all(998 origin,999 collection_id: CollectionId,1000 operator: T::CrossAccountId,1001 approve: bool,1002 ) -> DispatchResultWithPostInfo {1003 let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);1004 dispatch_tx::<T, _>(collection_id, |d| {1005 d.set_allowance_for_all(sender, operator, approve)1006 })1007 }10081009 /// Repairs a collection if the data was somehow corrupted.1010 ///1011 /// # Arguments1012 ///1013 /// * `collection_id`: ID of the collection to repair.1014 #[weight = <SelfWeightOf<T>>::force_repair_collection()]1015 pub fn force_repair_collection(1016 origin,1017 collection_id: CollectionId,1018 ) -> DispatchResult {1019 ensure_root(origin)?;1020 <PalletCommon<T>>::repair_collection(collection_id)1021 }10221023 /// Repairs a token if the data was somehow corrupted.1024 ///1025 /// # Arguments1026 ///1027 /// * `collection_id`: ID of the collection the item belongs to.1028 /// * `item_id`: ID of the item.1029 #[weight = T::CommonWeightInfo::force_repair_item()]1030 pub fn force_repair_item(1031 origin,1032 collection_id: CollectionId,1033 item_id: TokenId,1034 ) -> DispatchResultWithPostInfo {1035 ensure_root(origin)?;1036 dispatch_tx::<T, _>(collection_id, |d| {1037 d.repair_item(item_id)1038 })1039 }1040 }1041}10421043impl<T: Config> Pallet<T> {1044 /// Force set `sponsor` for `collection`.1045 ///1046 /// Differs from [`set_collection_sponsor`][`Pallet::set_collection_sponsor`] in that confirmation1047 /// from the `sponsor` is not required.1048 ///1049 /// # Arguments1050 ///1051 /// * `sponsor`: ID of the account of the sponsor-to-be.1052 /// * `collection_id`: ID of the modified collection.1053 pub fn force_set_sponsor(sponsor: T::AccountId, collection_id: CollectionId) -> DispatchResult {1054 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1055 target_collection.force_set_sponsor(sponsor.clone())1056 }10571058 /// Force remove `sponsor` for `collection`.1059 ///1060 /// Differs from `remove_sponsor` in that1061 /// it doesn't require consent from the `owner` of the collection.1062 ///1063 /// # Arguments1064 ///1065 /// * `collection_id`: ID of the modified collection.1066 pub fn force_remove_collection_sponsor(collection_id: CollectionId) -> DispatchResult {1067 let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;1068 target_collection.force_remove_sponsor()1069 }10701071 #[inline(always)]1072 pub(crate) fn destroy_collection_internal(1073 sender: T::CrossAccountId,1074 collection_id: CollectionId,1075 ) -> DispatchResult {1076 let collection = <CollectionHandle<T>>::try_get(collection_id)?;1077 collection.check_is_internal()?;10781079 T::CollectionDispatch::destroy(sender, collection)?;10801081 // TODO: basket cleanup should be moved elsewhere1082 // Maybe runtime dispatch.rs should perform it?10831084 let _ = <NftTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1085 let _ = <FungibleTransferBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1086 let _ = <ReFungibleTransferBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);10871088 let _ = <NftApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1089 let _ = <FungibleApproveBasket<T>>::clear_prefix(collection_id, u32::MAX, None);1090 let _ = <RefungibleApproveBasket<T>>::clear_prefix((collection_id,), u32::MAX, None);10911092 Ok(())1093 }1094}runtime/common/identity.rsdiffbeforeafterboth--- a/runtime/common/identity.rs
+++ b/runtime/common/identity.rs
@@ -21,9 +21,7 @@
use sp_runtime::{
traits::{DispatchInfoOf, SignedExtension},
- transaction_validity::{
- TransactionValidity, ValidTransaction, InvalidTransaction, TransactionValidityError,
- },
+ transaction_validity::{TransactionValidity, ValidTransaction, TransactionValidityError},
};
#[derive(Debug, Encode, Decode, PartialEq, Eq, Clone, TypeInfo)]
runtime/common/weights.rsdiffbeforeafterboth--- a/runtime/common/weights.rs
+++ b/runtime/common/weights.rs
@@ -101,6 +101,10 @@
dispatch_weight::<T>() + max_weight_of!(approve())
}
+ fn approve_from() -> Weight {
+ dispatch_weight::<T>() + max_weight_of!(approve_from())
+ }
+
fn transfer_from() -> Weight {
dispatch_weight::<T>() + max_weight_of!(transfer_from())
}
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -16,336 +16,521 @@
import {IKeyringPair} from '@polkadot/types/types';
import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {CrossAccountId} from './util/playgrounds/unique';
+
-describe('Integration Test approve(spender, collection_id, item_id, amount):', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+[
+ {method: 'approveToken', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account)},
+ {method: 'approveTokenFromEth', account: (account: IKeyringPair) => CrossAccountId.fromKeyring(account).toEthereum()},
+].map(testCase => {
+ describe(`Integration Test ${testCase.method}(spender, collection_id, item_id, amount):`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
});
- });
- itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- });
+ itSub('[nft] Execute the extrinsic and check approvedList', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ });
+
+ itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amount).to.be.equal(BigInt(1));
+ });
+
+ itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amount).to.be.equal(BigInt(1));
+ });
+
+ itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const collectionId = collection.collectionId;
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+ });
- itSub('[fungible] Execute the extrinsic and check approvedList', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
- itSub.ifWithPallets('[refungible] Execute the extrinsic and check approvedList', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+ });
- itSub('[nft] Remove approval by using 0 amount', async ({helper}) => {
- const collection = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const collectionId = collection.collectionId;
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
- });
+ itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
- itSub('[fungible] Remove approval by using 0 amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, {Substrate: alice.address});
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+ });
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ const result = (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(result).to.be.rejected;
+ });
});
- itSub.ifWithPallets('[refungible] Remove approval by using 0 amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] Normal user can approve other users to transfer:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
- });
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- itSub('can`t be called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTokenTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTokenTx()).to.be.rejected;
- });
-});
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
+ });
-describe('Normal user can approve other users to transfer:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+ expect(amount).to.be.equal(BigInt(1));
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+ const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, testCase.account(bob));
+ expect(amount).to.be.equal(BigInt(100n));
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.true;
- });
+ describe(`[${testCase.method}] Approved users can transferFrom up to approved amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const amount = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
- expect(amount).to.be.equal(BigInt(1));
- });
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
- const amount = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: charlie.address}, {Substrate: bob.address});
- expect(amount).to.be.equal(BigInt(100n));
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+ expect(owner.Substrate).to.be.equal(alice.address);
+ });
+
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+ });
+
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+ });
});
-});
-describe('Approved users can transferFrom up to approved amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ describe(`[${testCase.method}] Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
+ expect(owner.Substrate).to.be.equal(alice.address);
+ const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address});
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub('Fungible up to an approved amount', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(bob));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(1));
+
+ const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 1n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob), pieces: 100n});
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
+ const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+ const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
+ expect(after - before).to.be.equal(BigInt(100));
+ const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, testCase.account(bob), {Substrate: alice.address}, 100n);
+ await expect(transferTokenFromTx()).to.be.rejected;
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
- expect(owner.Substrate).to.be.equal(alice.address);
+ describe(`[${testCase.method}] Approved amount decreases by the transferred amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+ let dave: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+
+ const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+ await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: charlie.address}, 2n);
+ const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
+ expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+
+ const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+ await helper.ft.transferTokenFrom(bob, collectionId, tokenId, testCase.account(alice), {Substrate: dave.address}, 8n);
+ const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
+ expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
+ });
});
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] User may clear the approvals to approving for 0 amount:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
+ await (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
+ const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub('Fungible', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
+
+ await (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+
+ const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
+
+ itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address});
+ const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountBefore).to.be.equal(BigInt(1));
+
+ await (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
+ const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, testCase.account(alice));
+ expect(amountAfter).to.be.equal(BigInt(0));
+
+ const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
+ await expect(transferTokenFromTx()).to.be.rejected;
+ });
});
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ describe(`[${testCase.method}] User cannot approve for the amount greater than they own:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
+
+ itSub('1 for NFT', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address}, 2n);
+ await expect(result).to.be.rejected;
+ expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
+ });
+
+ itSub('Fungible', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ const result = (helper.ft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
+ await expect(result).to.be.rejected;
+ });
+
+ itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ const result = (helper.rft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
+ await expect(result).to.be.rejected;
+ });
});
-});
-describe('Approved users cannot use transferFrom to repeat transfers if approved amount was already transferred:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ describe(`[${testCase.method}] Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
+
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub('can be called by collection admin on non-owned item', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
+ const result = (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(result).to.be.rejected;
});
});
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- const owner = await helper.nft.getTokenOwner(collectionId, tokenId);
- expect(owner.Substrate).to.be.equal(alice.address);
- const transferTokenFromTx = () => helper.nft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ describe(`[${testCase.method}] Negative Integration Test approve(spender, collection_id, item_id, amount):`, () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let charlie: IKeyringPair;
- itSub('Fungible up to an approved amount', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, bob.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- const before = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- await helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- const after = await helper.ft.getBalance(collectionId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(1));
+ before(async () => {
+ await usingPlaygrounds(async (helper, privateKey) => {
+ const donor = await privateKey({filename: __filename});
+ [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ });
+ });
- const transferTokenFromTx = () => helper.ft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 1n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ await expect((helper.nft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address})).to.be.rejected;
+ });
+
+ itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- itSub.ifWithPallets('ReFungible up to an approved amount', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: bob.address, pieces: 100n});
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address}, 100n);
- const before = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- await helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
- const after = await helper.rft.getTokenBalance(collectionId, tokenId, {Substrate: alice.address});
- expect(after - before).to.be.equal(BigInt(100));
- const transferTokenFromTx = () => helper.rft.transferTokenFrom(charlie, collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address}, 100n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
-});
+ itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
+ const collectionId = 1 << 32 - 1;
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, 1, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
-describe('Approved amount decreases by the transferred amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
- let dave: IKeyringPair;
+ itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.nft.burn(alice, collectionId);
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie, dave] = await helper.arrange.createAccounts([100n, 100n, 100n, 100n], donor);
+ itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.burn(alice, collectionId);
+ const approveTx = () => (helper.ft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
});
- });
- itSub('If a user B is approved to transfer 10 Fungible tokens from user A, they can transfer 2 tokens to user C, which will result in decreasing approval from 10 to 8. Then user B can transfer 8 tokens to user D.', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
+ itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.rft.burn(alice, collectionId);
+ const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 1, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- const charlieBefore = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
- await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: charlie.address}, 2n);
- const charlieAfter = await helper.ft.getBalance(collectionId, {Substrate: charlie.address});
- expect(charlieAfter - charlieBefore).to.be.equal(BigInt(2));
+ itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- const daveBefore = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
- await helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: alice.address}, {Substrate: dave.address}, 8n);
- const daveAfter = await helper.ft.getBalance(collectionId, {Substrate: dave.address});
- expect(daveAfter - daveBefore).to.be.equal(BigInt(8));
- });
-});
+ itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const approveTx = () => (helper.rft as any)[testCase.method](alice, collectionId, 2, {Substrate: bob.address});
+ await expect(approveTx()).to.be.rejected;
+ });
-describe('User may clear the approvals to approving for 0 amount:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
+ itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice)});
+ const approveTx = () => (helper.nft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.mintTokens(alice, collectionId, 10n, testCase.account(alice));
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
});
- });
- itSub('NFT', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
- const transferTokenFromTx = () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(alice), pieces: 100n});
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address});
+ await expect(approveTx()).to.be.rejected;
+ });
- itSub('Fungible', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
+ const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
+ await helper.rft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 100n);
+ await (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
- await helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.ft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ const approveTx = () => (helper.rft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
+ await expect(approveTx()).to.be.rejected;
+ });
- const transferTokenFromTx = () => helper.ft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 1n);
- await expect(transferTokenFromTx()).to.be.rejected;
- });
+ itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
+ const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
+ const tokenId = await helper.ft.getLastTokenId(collectionId);
- itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
- const amountBefore = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountBefore).to.be.equal(BigInt(1));
+ await helper.ft.transferToken(alice, collectionId, tokenId, testCase.account(bob), 10n);
+ await (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
+ const approveTx = () => (helper.ft as any)[testCase.method](bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
+ await expect(approveTx()).to.be.rejected;
+ });
- await helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 0n);
- const amountAfter = await helper.rft.getTokenApprovedPieces(collectionId, tokenId, {Substrate: bob.address}, {Substrate: alice.address});
- expect(amountAfter).to.be.equal(BigInt(0));
+ itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
+ const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
+ const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: testCase.account(bob)});
+ await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
- const transferTokenFromTx = () => helper.rft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: charlie.address}, 100n);
- await expect(transferTokenFromTx()).to.be.rejected;
+ const approveTx = () => (helper.nft as any)[testCase.method](alice, collectionId, tokenId, {Substrate: charlie.address});
+ await expect(approveTx()).to.be.rejected;
+ });
});
});
-describe('User cannot approve for the amount greater than they own:', () => {
+describe('Normal user can approve other users to be wallet operator:', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
- let charlie: IKeyringPair;
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+ [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
});
});
- itSub('1 for NFT', async ({helper}) => {
+ itSub('[nft] Enable and disable approval', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTx = () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
- await expect(approveTx()).to.be.rejected;
- expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
- });
- itSub('Fungible', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'}, 0);
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- const approveTx = () => helper.ft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 11n);
- await expect(approveTx()).to.be.rejected;
+ const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkBeforeApproval).to.be.false;
+
+ await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+ const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterApproval).to.be.true;
+
+ await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+ const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterDisapproval).to.be.false;
});
- itSub.ifWithPallets('ReFungible', [Pallets.ReFungible], async ({helper}) => {
+ itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- const approveTx = () => helper.rft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address}, 101n);
- await expect(approveTx()).to.be.rejected;
+
+ const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkBeforeApproval).to.be.false;
+
+ await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
+ const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterApproval).to.be.true;
+
+ await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
+ const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
+ expect(checkAfterDisapproval).to.be.false;
});
});
@@ -464,184 +649,5 @@
await token.approve(dave, {Substrate: bob.address}, 50n);
await expect(token.approve(dave, {Substrate: charlie.address}, 51n))
.to.be.rejectedWith('this test would fail (since it is skipped), replace this expecting message with what would have been received');
- });
-});
-
-describe('Integration Test approve(spender, collection_id, item_id, amount) with collection admin permissions:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
- });
- });
-
- itSub('can be called by collection admin on non-owned item', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- await helper.collection.addAdmin(alice, collectionId, {Substrate: bob.address});
- const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-});
-
-describe('Negative Integration Test approve(spender, collection_id, item_id, amount):', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
- let charlie: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
- });
- });
-
- itSub('[nft] Approve for a collection that does not exist', async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.nft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve for a collection that does not exist', async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.ft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve for a collection that does not exist', [Pallets.ReFungible], async ({helper}) => {
- const collectionId = 1 << 32 - 1;
- const approveTx = () => helper.rft.approveToken(bob, collectionId, 1, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve for a collection that was destroyed', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.nft.burn(alice, collectionId);
- const approveTx = () => helper.nft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve for a collection that was destroyed', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.burn(alice, collectionId);
- const approveTx = () => helper.ft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve for a collection that was destroyed', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.rft.burn(alice, collectionId);
- const approveTx = () => helper.rft.approveToken(alice, collectionId, 1, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve transfer of a token that does not exist', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const approveTx = () => helper.nft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve transfer of a token that does not exist', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const approveTx = () => helper.rft.approveToken(alice, collectionId, 2, {Substrate: bob.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[nft] Approve using the address that does not own the approved token', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
- const approveTx = () => helper.nft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('[fungible] Approve using the address that does not own the approved token', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
- const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('[refungible] Approve using the address that does not own the approved token', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address});
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub.ifWithPallets('should fail if approved more ReFungibles than owned', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.rft.mintToken(alice, {collectionId: collectionId, owner: alice.address, pieces: 100n});
- await helper.rft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 100n);
- await helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 100n);
-
- const approveTx = () => helper.rft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 101n);
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('should fail if approved more Fungibles than owned', async ({helper}) => {
- const {collectionId} = await helper.ft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- await helper.ft.mintTokens(alice, collectionId, 10n, alice.address);
- const tokenId = await helper.ft.getLastTokenId(collectionId);
-
- await helper.ft.transferToken(alice, collectionId, tokenId, {Substrate: bob.address}, 10n);
- await helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 10n);
- const approveTx = () => helper.ft.approveToken(bob, collectionId, tokenId, {Substrate: alice.address}, 11n);
- await expect(approveTx()).to.be.rejected;
- });
-
- itSub('fails when called by collection owner on non-owned item when OwnerCanTransfer == false', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
- const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- await helper.collection.setLimits(alice, collectionId, {ownerCanTransfer: false});
-
- const approveTx = () => helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: charlie.address});
- await expect(approveTx()).to.be.rejected;
- });
-});
-
-describe('Normal user can approve other users to be wallet operator:', () => {
- let alice: IKeyringPair;
- let bob: IKeyringPair;
-
- before(async () => {
- await usingPlaygrounds(async (helper, privateKey) => {
- const donor = await privateKey({filename: __filename});
- [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
- });
- });
-
- itSub('[nft] Enable and disable approval', async ({helper}) => {
- const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
- const checkBeforeApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkBeforeApproval).to.be.false;
-
- await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
- const checkAfterApproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterApproval).to.be.true;
-
- await helper.nft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
- const checkAfterDisapproval = await helper.nft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterDisapproval).to.be.false;
- });
-
- itSub.ifWithPallets('[rft] Enable and disable approval', [Pallets.ReFungible], async ({helper}) => {
- const {collectionId} = await helper.rft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
-
- const checkBeforeApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkBeforeApproval).to.be.false;
-
- await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, true);
- const checkAfterApproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterApproval).to.be.true;
-
- await helper.rft.setAllowanceForAll(alice, collectionId, {Substrate: bob.address}, false);
- const checkAfterDisapproval = await helper.rft.allowanceForAll(collectionId, {Substrate: alice.address}, {Substrate: bob.address});
- expect(checkAfterDisapproval).to.be.false;
});
});
tests/src/eth/api/ContractHelpers.soldiffbeforeafterboth--- a/tests/src/eth/api/ContractHelpers.sol
+++ b/tests/src/eth/api/ContractHelpers.sol
@@ -183,9 +183,9 @@
/// Ethereum representation of Optional value with CrossAddress.
struct OptionCrossAddress {
- /// TODO: field description
+ /// Whether or not this CrossAdress is valid and has meaning.
bool status;
- /// TODO: field description
+ /// The underlying CrossAddress value. If the status is false, can be set to whatever.
CrossAddress value;
}
tests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -85,6 +85,10 @@
**/
AccountTokenLimitExceeded: AugmentedError<ApiType>;
/**
+ * Only spending from eth mirror could be approved
+ **/
+ AddressIsNotEthMirror: AugmentedError<ApiType>;
+ /**
* Can't transfer tokens to ethereum zero address
**/
AddressIsZero: AugmentedError<ApiType>;
tests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -1214,6 +1214,25 @@
**/
approve: AugmentedSubmittable<(spender: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
/**
+ * Allow a non-permissioned address to transfer or burn an item from owner's eth mirror.
+ *
+ * # Permissions
+ *
+ * * Collection owner
+ * * Collection admin
+ * * Current item owner
+ *
+ * # Arguments
+ *
+ * * `from`: Owner's account eth mirror
+ * * `to`: Account to be approved to make specific transactions on non-owned tokens.
+ * * `collection_id`: ID of the collection the item belongs to.
+ * * `item_id`: ID of the item transactions on which are now approved.
+ * * `amount`: Number of pieces of the item approved for a transaction (maximum of 1 for NFTs).
+ * Set to 0 to revoke the approval.
+ **/
+ approveFrom: AugmentedSubmittable<(from: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, to: PalletEvmAccountBasicCrossAccountIdRepr | { Substrate: any } | { Ethereum: any } | string | Uint8Array, collectionId: u32 | AnyNumber | Uint8Array, itemId: u32 | AnyNumber | Uint8Array, amount: u128 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [PalletEvmAccountBasicCrossAccountIdRepr, PalletEvmAccountBasicCrossAccountIdRepr, u32, u32, u128]>;
+ /**
* Destroy a token on behalf of the owner as a non-owner account.
*
* See also: [`approve`][`Pallet::approve`].
tests/src/interfaces/default/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/default/types.ts
+++ b/tests/src/interfaces/default/types.ts
@@ -1216,6 +1216,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -1231,7 +1232,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletCommonEvent */
@@ -2306,6 +2307,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2345,7 +2354,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name PalletUniqueError */
tests/src/interfaces/lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/lookup.ts
+++ b/tests/src/interfaces/lookup.ts
@@ -2264,6 +2264,13 @@
itemId: 'u32',
amount: 'u128',
},
+ approve_from: {
+ from: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ to: 'PalletEvmAccountBasicCrossAccountIdRepr',
+ collectionId: 'u32',
+ itemId: 'u32',
+ amount: 'u128',
+ },
transfer_from: {
from: 'PalletEvmAccountBasicCrossAccountIdRepr',
recipient: 'PalletEvmAccountBasicCrossAccountIdRepr',
@@ -3280,7 +3287,7 @@
* Lookup423: pallet_common::pallet::Error<T>
**/
PalletCommonError: {
- _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
+ _enum: ['CollectionNotFound', 'MustBeTokenOwner', 'NoPermission', 'CantDestroyNotEmptyCollection', 'PublicMintingNotAllowed', 'AddressNotInAllowlist', 'CollectionNameLimitExceeded', 'CollectionDescriptionLimitExceeded', 'CollectionTokenPrefixLimitExceeded', 'TotalCollectionsLimitExceeded', 'CollectionAdminCountExceeded', 'CollectionLimitBoundsExceeded', 'OwnerPermissionsCantBeReverted', 'TransferNotAllowed', 'AccountTokenLimitExceeded', 'CollectionTokenLimitExceeded', 'MetadataFlagFrozen', 'TokenNotFound', 'TokenValueTooLow', 'ApprovedValueTooLow', 'CantApproveMoreThanOwned', 'AddressIsNotEthMirror', 'AddressIsZero', 'UnsupportedOperation', 'NotSufficientFounds', 'UserIsNotAllowedToNest', 'SourceCollectionIsNotAllowedToNest', 'CollectionFieldSizeExceeded', 'NoSpaceForProperty', 'PropertyLimitReached', 'PropertyKeyIsTooLong', 'InvalidCharacterInPropertyKey', 'EmptyPropertyKey', 'CollectionIsExternal', 'CollectionIsInternal', 'ConfirmSponsorshipFail', 'UserIsNotCollectionAdmin']
},
/**
* Lookup425: pallet_fungible::pallet::Error<T>
tests/src/interfaces/types-lookup.tsdiffbeforeafterboth--- a/tests/src/interfaces/types-lookup.ts
+++ b/tests/src/interfaces/types-lookup.ts
@@ -2493,6 +2493,14 @@
readonly itemId: u32;
readonly amount: u128;
} & Struct;
+ readonly isApproveFrom: boolean;
+ readonly asApproveFrom: {
+ readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly to: PalletEvmAccountBasicCrossAccountIdRepr;
+ readonly collectionId: u32;
+ readonly itemId: u32;
+ readonly amount: u128;
+ } & Struct;
readonly isTransferFrom: boolean;
readonly asTransferFrom: {
readonly from: PalletEvmAccountBasicCrossAccountIdRepr;
@@ -2532,7 +2540,7 @@
readonly collectionId: u32;
readonly itemId: u32;
} & Struct;
- readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
+ readonly type: 'CreateCollection' | 'CreateCollectionEx' | 'DestroyCollection' | 'AddToAllowList' | 'RemoveFromAllowList' | 'ChangeCollectionOwner' | 'AddCollectionAdmin' | 'RemoveCollectionAdmin' | 'SetCollectionSponsor' | 'ConfirmSponsorship' | 'RemoveCollectionSponsor' | 'CreateItem' | 'CreateMultipleItems' | 'SetCollectionProperties' | 'DeleteCollectionProperties' | 'SetTokenProperties' | 'DeleteTokenProperties' | 'SetTokenPropertyPermissions' | 'CreateMultipleItemsEx' | 'SetTransfersEnabledFlag' | 'BurnItem' | 'BurnFrom' | 'Transfer' | 'Approve' | 'ApproveFrom' | 'TransferFrom' | 'SetCollectionLimits' | 'SetCollectionPermissions' | 'Repartition' | 'SetAllowanceForAll' | 'ForceRepairCollection' | 'ForceRepairItem';
}
/** @name UpDataStructsCollectionMode (236) */
@@ -3564,6 +3572,7 @@
readonly isTokenValueTooLow: boolean;
readonly isApprovedValueTooLow: boolean;
readonly isCantApproveMoreThanOwned: boolean;
+ readonly isAddressIsNotEthMirror: boolean;
readonly isAddressIsZero: boolean;
readonly isUnsupportedOperation: boolean;
readonly isNotSufficientFounds: boolean;
@@ -3579,7 +3588,7 @@
readonly isCollectionIsInternal: boolean;
readonly isConfirmSponsorshipFail: boolean;
readonly isUserIsNotCollectionAdmin: boolean;
- readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
+ readonly type: 'CollectionNotFound' | 'MustBeTokenOwner' | 'NoPermission' | 'CantDestroyNotEmptyCollection' | 'PublicMintingNotAllowed' | 'AddressNotInAllowlist' | 'CollectionNameLimitExceeded' | 'CollectionDescriptionLimitExceeded' | 'CollectionTokenPrefixLimitExceeded' | 'TotalCollectionsLimitExceeded' | 'CollectionAdminCountExceeded' | 'CollectionLimitBoundsExceeded' | 'OwnerPermissionsCantBeReverted' | 'TransferNotAllowed' | 'AccountTokenLimitExceeded' | 'CollectionTokenLimitExceeded' | 'MetadataFlagFrozen' | 'TokenNotFound' | 'TokenValueTooLow' | 'ApprovedValueTooLow' | 'CantApproveMoreThanOwned' | 'AddressIsNotEthMirror' | 'AddressIsZero' | 'UnsupportedOperation' | 'NotSufficientFounds' | 'UserIsNotAllowedToNest' | 'SourceCollectionIsNotAllowedToNest' | 'CollectionFieldSizeExceeded' | 'NoSpaceForProperty' | 'PropertyLimitReached' | 'PropertyKeyIsTooLong' | 'InvalidCharacterInPropertyKey' | 'EmptyPropertyKey' | 'CollectionIsExternal' | 'CollectionIsInternal' | 'ConfirmSponsorshipFail' | 'UserIsNotCollectionAdmin';
}
/** @name PalletFungibleError (425) */
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -633,6 +633,10 @@
let call = this.getApi() as any;
for(const part of apiCall.slice(4).split('.')) {
call = call[part];
+ if (!call) {
+ const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';
+ throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);
+ }
}
return call(...params);
}
@@ -1259,6 +1263,42 @@
}
/**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param fromAddressObj Signer's Ethereum address containing her tokens
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {
+ const approveResult = await this.helper.executeExtrinsic(
+ signer,
+ 'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],
+ true, // `Unable to approve token for ${label}`,
+ );
+
+ return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');
+ }
+
+ /**
+ * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.
+ *
+ * @param signer keyring of signer
+ * @param collectionId ID of collection
+ * @param tokenId ID of token
+ * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens
+ * @param amount amount of token to be approved. For NFT must be set to 1n
+ * @returns ```true``` if extrinsic success, otherwise ```false```
+ */
+ async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();
+ return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);
+ }
+
+ /**
* Get the amount of token pieces approved to transfer or burn. Normally 0.
*
* @param collectionId ID of collection
@@ -1756,8 +1796,8 @@
* @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})
* @returns ```true``` if extrinsic success, otherwise ```false```
*/
- approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {
- return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);
+ approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {
+ return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);
}
}