difftreelog
Merge pull request #574 from UniqueNetwork/feature/eth_passthrought
in: master
Feature/eth passthrought
19 files changed
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -20,6 +20,7 @@
solidity_interface, solidity, ToLog,
types::*,
execution::{Result, Error},
+ weight,
};
pub use pallet_evm::{PrecompileOutput, PrecompileResult, PrecompileHandle, account::CrossAccountId};
use pallet_evm_coder_substrate::dispatch_to_evm;
@@ -31,8 +32,12 @@
use alloc::format;
use crate::{
- Pallet, CollectionHandle, Config, CollectionProperties,
- eth::{convert_cross_account_to_uint256, convert_uint256_to_cross_account},
+ Pallet, CollectionHandle, Config, CollectionProperties, SelfWeightOf,
+ eth::{
+ convert_cross_account_to_uint256, convert_uint256_to_cross_account,
+ convert_cross_account_to_tuple,
+ },
+ weights::WeightInfo,
};
/// Events for ethereum collection helper.
@@ -69,6 +74,7 @@
///
/// @param key Property key.
/// @param value Propery value.
+ #[weight(<SelfWeightOf<T>>::set_collection_properties(1))]
fn set_collection_property(
&mut self,
caller: caller,
@@ -88,7 +94,10 @@
/// Delete collection property.
///
/// @param key Property key.
+ #[weight(<SelfWeightOf<T>>::delete_collection_properties(1))]
fn delete_collection_property(&mut self, caller: caller, key: string) -> Result<()> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let key = <Vec<u8>>::from(key)
.try_into()
@@ -120,6 +129,8 @@
///
/// @param sponsor Address of the sponsor from whose account funds will be debited for operations with the contract.
fn set_collection_sponsor(&mut self, caller: caller, sponsor: address) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let sponsor = T::CrossAccountId::from_eth(sponsor);
@@ -138,6 +149,8 @@
caller: caller,
sponsor: uint256,
) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let sponsor = convert_uint256_to_cross_account::<T>(sponsor);
@@ -146,7 +159,7 @@
save(self)
}
- // /// Whether there is a pending sponsor.
+ /// Whether there is a pending sponsor.
fn has_collection_pending_sponsor(&self) -> Result<bool> {
Ok(matches!(
self.collection.sponsorship,
@@ -158,6 +171,8 @@
///
/// @dev After setting the sponsor for the collection, it must be confirmed with this function.
fn confirm_collection_sponsorship(&mut self, caller: caller) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
if !self
.confirm_sponsorship(caller.as_sub())
@@ -170,6 +185,7 @@
/// Remove collection sponsor.
fn remove_collection_sponsor(&mut self, caller: caller) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
check_is_owner_or_admin(caller, self)?;
self.remove_sponsor().map_err(dispatch_to_evm::<T>)?;
save(self)
@@ -206,6 +222,8 @@
/// @param value Value of the limit.
#[solidity(rename_selector = "setCollectionLimit")]
fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut limits = self.limits.clone();
@@ -249,6 +267,8 @@
/// @param value Value of the limit.
#[solidity(rename_selector = "setCollectionLimit")]
fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut limits = self.limits.clone();
@@ -275,7 +295,7 @@
}
/// Get contract address.
- fn contract_address(&self, _caller: caller) -> Result<address> {
+ fn contract_address(&self) -> Result<address> {
Ok(crate::eth::collection_id_to_address(self.id))
}
@@ -286,6 +306,8 @@
caller: caller,
new_admin: uint256,
) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_admin = convert_uint256_to_cross_account::<T>(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
@@ -299,6 +321,8 @@
caller: caller,
admin: uint256,
) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let admin = convert_uint256_to_cross_account::<T>(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
@@ -308,6 +332,8 @@
/// Add collection admin.
/// @param newAdmin Address of the added administrator.
fn add_collection_admin(&mut self, caller: caller, new_admin: address) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_admin = T::CrossAccountId::from_eth(new_admin);
<Pallet<T>>::toggle_admin(self, &caller, &new_admin, true).map_err(dispatch_to_evm::<T>)?;
@@ -318,6 +344,8 @@
///
/// @param admin Address of the removed administrator.
fn remove_collection_admin(&mut self, caller: caller, admin: address) -> Result<void> {
+ self.consume_store_writes(2)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let admin = T::CrossAccountId::from_eth(admin);
<Pallet<T>>::toggle_admin(self, &caller, &admin, false).map_err(dispatch_to_evm::<T>)?;
@@ -329,6 +357,8 @@
/// @param enable If "true" degenerates to nesting: 'Owner' else to nesting: 'Disabled'
#[solidity(rename_selector = "setCollectionNesting")]
fn set_nesting_bool(&mut self, caller: caller, enable: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let mut permissions = self.collection.permissions.clone();
@@ -358,6 +388,8 @@
enable: bool,
collections: Vec<address>,
) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
if collections.is_empty() {
return Err("no addresses provided".into());
}
@@ -401,6 +433,8 @@
/// 0 for Normal
/// 1 for AllowList
fn set_collection_access(&mut self, caller: caller, mode: uint8) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let permissions = CollectionPermissions {
access: Some(match mode {
@@ -420,30 +454,78 @@
save(self)
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ fn allowed(&self, user: address) -> Result<bool> {
+ Ok(Pallet::<T>::allowed(
+ self.id,
+ T::CrossAccountId::from_eth(user),
+ ))
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
fn add_to_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
<Pallet<T>>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ fn add_to_collection_allow_list_substrate(
+ &mut self,
+ caller: caller,
+ user: uint256,
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_uint256_to_cross_account::<T>(user);
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, true).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
fn remove_from_collection_allow_list(&mut self, caller: caller, user: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let user = T::CrossAccountId::from_eth(user);
<Pallet<T>>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
Ok(())
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ fn remove_from_collection_allow_list_substrate(
+ &mut self,
+ caller: caller,
+ user: uint256,
+ ) -> Result<void> {
+ self.consume_store_writes(1)?;
+
+ let caller = T::CrossAccountId::from_eth(caller);
+ let user = convert_uint256_to_cross_account::<T>(user);
+ Pallet::<T>::toggle_allowlist(self, &caller, &user, false).map_err(dispatch_to_evm::<T>)?;
+ Ok(())
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
fn set_collection_mint_mode(&mut self, caller: caller, mode: bool) -> Result<void> {
+ self.consume_store_reads_and_writes(1, 1)?;
+
check_is_owner_or_admin(caller, self)?;
let permissions = CollectionPermissions {
mint_mode: Some(mode),
@@ -481,7 +563,7 @@
/// Returns collection type
///
/// @return `Fungible` or `NFT` or `ReFungible`
- fn unique_collection_type(&mut self) -> Result<string> {
+ fn unique_collection_type(&self) -> Result<string> {
let mode = match self.collection.mode {
CollectionMode::Fungible(_) => "Fungible",
CollectionMode::NFT => "NFT",
@@ -490,11 +572,23 @@
Ok(mode.into())
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ fn collection_owner(&self) -> Result<(address, uint256)> {
+ Ok(convert_cross_account_to_tuple::<T>(
+ &T::CrossAccountId::from_sub(self.owner.clone()),
+ ))
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner account
fn set_owner(&mut self, caller: caller, new_owner: address) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_owner = T::CrossAccountId::from_eth(new_owner);
self.set_owner_internal(caller, new_owner)
@@ -506,13 +600,25 @@
/// @dev Owner can be changed only by current owner
/// @param newOwner new owner substrate account
fn set_owner_substrate(&mut self, caller: caller, new_owner: uint256) -> Result<void> {
+ self.consume_store_writes(1)?;
+
let caller = T::CrossAccountId::from_eth(caller);
let new_owner = convert_uint256_to_cross_account::<T>(new_owner);
self.set_owner_internal(caller, new_owner)
.map_err(dispatch_to_evm::<T>)
}
+
+ // TODO: need implement AbiWriter for &Vec<T>
+ // fn collection_admins(&self) -> Result<Vec<(address, uint256)>> {
+ // let result = pallet_common::IsAdmin::<T>::iter_prefix((self.id,))
+ // .map(|(admin, _)| pallet_common::eth::convert_cross_account_to_tuple::<T>(&admin))
+ // .collect();
+ // Ok(result)
+ // }
}
+/// ### Note
+/// Do not forget to add: `self.consume_store_reads(1)?;`
fn check_is_owner_or_admin<T: Config>(
caller: caller,
collection: &CollectionHandle<T>,
@@ -524,9 +630,9 @@
Ok(caller)
}
+/// ### Note
+/// Do not forget to add: `self.consume_store_writes(1)?;`
fn save<T: Config>(collection: &CollectionHandle<T>) -> Result<void> {
- // TODO possibly delete for the lack of transaction
- collection.consume_store_writes(1)?;
collection
.check_is_internal()
.map_err(dispatch_to_evm::<T>)?;
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -16,7 +16,7 @@
//! The module contains a number of functions for converting and checking ethereum identifiers.
-use evm_coder::types::uint256;
+use evm_coder::types::{uint256, address};
pub use pallet_evm::account::{Config, CrossAccountId};
use sp_core::H160;
use up_data_structs::CollectionId;
@@ -69,3 +69,19 @@
let account_id = T::AccountId::from(new_admin_arr);
T::CrossAccountId::from_sub(account_id)
}
+
+/// Convert `CrossAccountId` to `(address, uint256)`.
+pub fn convert_cross_account_to_tuple<T: Config>(
+ cross_account_id: &T::CrossAccountId,
+) -> (address, uint256)
+where
+ T::AccountId: AsRef<[u8; 32]>,
+{
+ if cross_account_id.is_canonical_substrate() {
+ let sub = convert_cross_account_to_uint256::<T>(cross_account_id);
+ (Default::default(), sub)
+ } else {
+ let eth = *cross_account_id.as_eth();
+ (eth, Default::default())
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -112,7 +112,6 @@
RmrkBoundedTheme,
RmrkNftChild,
CollectionPermissions,
- SchemaVersion,
};
pub use pallet::*;
@@ -202,6 +201,21 @@
))
}
+ /// Consume gas for reading and writing.
+ pub fn consume_store_reads_and_writes(
+ &self,
+ reads: u64,
+ writes: u64,
+ ) -> evm_coder::execution::Result<()> {
+ let weight = <T as frame_system::Config>::DbWeight::get();
+ let reads = weight.read.saturating_mul(reads);
+ let writes = weight.read.saturating_mul(writes);
+ self.recorder
+ .consume_gas(T::GasWeightMapping::weight_to_gas(
+ reads.saturating_add(writes),
+ ))
+ }
+
/// Save collection to storage.
pub fn save(&self) -> DispatchResult {
<CollectionById<T>>::insert(self.id, &self.collection);
@@ -310,6 +324,8 @@
}
/// Changes collection owner to another account
+ /// #### Store read/writes
+ /// 1 writes
fn set_owner_internal(
&mut self,
caller: T::CrossAccountId,
@@ -1292,6 +1308,8 @@
}
/// Toggle `user` participation in the `collection`'s allow list.
+ /// #### Store read/writes
+ /// 1 writes
pub fn toggle_allowlist(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
@@ -1312,6 +1330,8 @@
}
/// Toggle `user` participation in the `collection`'s admin list.
+ /// #### Store read/writes
+ /// 2 writes
pub fn toggle_admin(
collection: &CollectionHandle<T>,
sender: &T::CrossAccountId,
pallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -172,14 +172,9 @@
fn get_sponsor(&self, contract_address: address) -> Result<(address, uint256)> {
let sponsor =
Pallet::<T>::get_sponsor(contract_address).ok_or("Contract has no sponsor")?;
- let result: (address, uint256) = if sponsor.is_canonical_substrate() {
- let sponsor = pallet_common::eth::convert_cross_account_to_uint256::<T>(&sponsor);
- (Default::default(), sponsor)
- } else {
- let sponsor = *sponsor.as_eth();
- (sponsor, Default::default())
- };
- Ok(result)
+ Ok(pallet_common::eth::convert_cross_account_to_tuple::<T>(
+ &sponsor,
+ ))
}
/// Check tat contract has confirmed sponsor.
pallets/fungible/src/stubs/UniqueFungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/fungible/src/stubs/UniqueFungible.soldiffbeforeafterboth--- a/pallets/fungible/src/stubs/UniqueFungible.sol
+++ b/pallets/fungible/src/stubs/UniqueFungible.sol
@@ -22,7 +22,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -255,6 +255,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -266,6 +278,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -277,6 +300,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -325,6 +359,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple6 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple6(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
pallets/nonfungible/src/stubs/UniqueNFT.rawdiffbeforeafterbothbinary blob — no preview
pallets/nonfungible/src/stubs/UniqueNFT.soldiffbeforeafterboth--- a/pallets/nonfungible/src/stubs/UniqueNFT.sol
+++ b/pallets/nonfungible/src/stubs/UniqueNFT.sol
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -332,6 +332,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -343,6 +355,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -354,6 +377,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -402,6 +436,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
pallets/refungible/src/stubs/UniqueRefungible.rawdiffbeforeafterbothbinary blob — no preview
pallets/refungible/src/stubs/UniqueRefungible.soldiffbeforeafterboth--- a/pallets/refungible/src/stubs/UniqueRefungible.sol
+++ b/pallets/refungible/src/stubs/UniqueRefungible.sol
@@ -99,7 +99,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
contract Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -332,6 +332,18 @@
dummy = 0;
}
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) public view returns (bool) {
+ require(false, stub_error);
+ user;
+ dummy;
+ return false;
+ }
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -343,6 +355,17 @@
dummy = 0;
}
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -354,6 +377,17 @@
dummy = 0;
}
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) public {
+ require(false, stub_error);
+ user;
+ dummy = 0;
+ }
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -402,6 +436,18 @@
return "";
}
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() public view returns (Tuple17 memory) {
+ require(false, stub_error);
+ dummy;
+ return Tuple17(0x0000000000000000000000000000000000000000, 0);
+ }
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/allowlist.test.tsdiffbeforeafterboth--- a/tests/src/eth/allowlist.test.ts
+++ b/tests/src/eth/allowlist.test.ts
@@ -14,10 +14,22 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+import {IKeyringPair} from '@polkadot/types/types';
import {expect} from 'chai';
-import {contractHelpers, createEthAccountWithBalance, deployFlipper, itWeb3} from './util/helpers';
+import {isAllowlisted, normalizeAccountId} from '../util/helpers';
+import {
+ contractHelpers,
+ createEthAccount,
+ createEthAccountWithBalance,
+ deployFlipper,
+ evmCollection,
+ evmCollectionHelpers,
+ getCollectionAddressFromResult,
+ itWeb3,
+} from './util/helpers';
+import {itEth, usingEthPlaygrounds} from './util/playgrounds';
-describe('EVM allowlist', () => {
+describe('EVM contract allowlist', () => {
itWeb3('Contract allowlist can be toggled', async ({api, web3, privateKeyWrapper}) => {
const owner = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
const flipper = await deployFlipper(web3, owner);
@@ -58,3 +70,79 @@
expect(await flipper.methods.getValue().call()).to.be.false;
});
});
+
+describe('EVM collection allowlist', () => {
+ let donor: IKeyringPair;
+
+ before(async function() {
+ await usingEthPlaygrounds(async (_helper, privateKey) => {
+ donor = privateKey('//Alice');
+ });
+ });
+
+ itEth('Collection allowlist can be added and removed by [eth] address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.eth.createAccount();
+
+ const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+
+ await collectionEvm.methods.removeFromCollectionAllowList(user).send({from: owner});
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ });
+
+ itEth('Collection allowlist can be added and removed by [sub] address', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+
+ await collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ });
+
+ itEth('Collection allowlist can not be add and remove [eth] address by not owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const user = helper.eth.createAccount();
+
+ const {collectionAddress} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await expect(collectionEvm.methods.addToCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowList(user).send({from: owner});
+
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+ await expect(collectionEvm.methods.removeFromCollectionAllowList(user).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await collectionEvm.methods.allowed(user).call({from: owner})).to.be.true;
+ });
+
+ itEth('Collection allowlist can not be add and remove [sub] address by not owner', async ({helper}) => {
+ const owner = await helper.eth.createAccountWithBalance(donor);
+ const notOwner = await helper.eth.createAccountWithBalance(donor);
+ const user = donor;
+
+ const {collectionAddress, collectionId} = await helper.eth.createNonfungibleCollection(owner, 'A', 'B', 'C');
+ const collectionEvm = helper.ethNativeContract.collection(collectionAddress, 'nft', owner);
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await expect(collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.false;
+ await collectionEvm.methods.addToCollectionAllowListSubstrate(user.addressRaw).send({from: owner});
+
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ await expect(collectionEvm.methods.removeFromCollectionAllowListSubstrate(user.addressRaw).call({from: notOwner})).to.be.rejectedWith('NoPermission');
+ expect(await helper.collection.allowed(collectionId, {Substrate: user.address})).to.be.true;
+ });
+});
tests/src/eth/api/UniqueFungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueFungible.sol
+++ b/tests/src/eth/api/UniqueFungible.sol
@@ -13,7 +13,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -164,6 +164,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -171,6 +178,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -178,6 +192,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -208,6 +229,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple6 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/api/UniqueNFT.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueNFT.sol
+++ b/tests/src/eth/api/UniqueNFT.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -216,6 +216,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -223,6 +230,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -230,6 +244,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -260,6 +281,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple17 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/api/UniqueRefungible.soldiffbeforeafterboth--- a/tests/src/eth/api/UniqueRefungible.sol
+++ b/tests/src/eth/api/UniqueRefungible.sol
@@ -65,7 +65,7 @@
}
/// @title A contract that allows you to work with collections.
-/// @dev the ERC-165 identifier for this interface is 0xe54be640
+/// @dev the ERC-165 identifier for this interface is 0x9f70d4e0
interface Collection is Dummy, ERC165 {
/// Set collection property.
///
@@ -216,6 +216,13 @@
/// or in textual repr: setCollectionAccess(uint8)
function setCollectionAccess(uint8 mode) external;
+ /// Checks that user allowed to operate with collection.
+ ///
+ /// @param user User address to check.
+ /// @dev EVM selector for this function is: 0xd63a8e11,
+ /// or in textual repr: allowed(address)
+ function allowed(address user) external view returns (bool);
+
/// Add the user to the allowed list.
///
/// @param user Address of a trusted user.
@@ -223,6 +230,13 @@
/// or in textual repr: addToCollectionAllowList(address)
function addToCollectionAllowList(address user) external;
+ /// Add substrate user to allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xd06ad267,
+ /// or in textual repr: addToCollectionAllowListSubstrate(uint256)
+ function addToCollectionAllowListSubstrate(uint256 user) external;
+
/// Remove the user from the allowed list.
///
/// @param user Address of a removed user.
@@ -230,6 +244,13 @@
/// or in textual repr: removeFromCollectionAllowList(address)
function removeFromCollectionAllowList(address user) external;
+ /// Remove substrate user from allowed list.
+ ///
+ /// @param user User substrate address.
+ /// @dev EVM selector for this function is: 0xa31913ed,
+ /// or in textual repr: removeFromCollectionAllowListSubstrate(uint256)
+ function removeFromCollectionAllowListSubstrate(uint256 user) external;
+
/// Switch permission for minting.
///
/// @param mode Enable if "true".
@@ -260,6 +281,14 @@
/// or in textual repr: uniqueCollectionType()
function uniqueCollectionType() external returns (string memory);
+ /// Get collection owner.
+ ///
+ /// @return Tuble with sponsor address and his substrate mirror.
+ /// If address is canonical then substrate mirror is zero and vice versa.
+ /// @dev EVM selector for this function is: 0xdf727d3b,
+ /// or in textual repr: collectionOwner()
+ function collectionOwner() external view returns (Tuple17 memory);
+
/// Changes collection owner to another account
///
/// @dev Owner can be changed only by current owner
tests/src/eth/fungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/fungibleAbi.json
+++ b/tests/src/eth/fungibleAbi.json
@@ -78,6 +78,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "owner", "type": "address" },
{ "internalType": "address", "name": "spender", "type": "address" }
],
@@ -88,6 +97,15 @@
},
{
"inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "spender", "type": "address" },
{ "internalType": "uint256", "name": "amount", "type": "uint256" }
],
@@ -116,6 +134,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple6",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -261,6 +296,15 @@
"type": "function"
},
{
+ "inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "uint8", "name": "mode", "type": "uint8" }],
"name": "setCollectionAccess",
"outputs": [],
tests/src/eth/nonFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/nonFungibleAbi.json
+++ b/tests/src/eth/nonFungibleAbi.json
@@ -109,6 +109,24 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "approved", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -146,6 +164,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -376,6 +411,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
tests/src/eth/reFungibleAbi.jsondiffbeforeafterboth--- a/tests/src/eth/reFungibleAbi.json
+++ b/tests/src/eth/reFungibleAbi.json
@@ -109,6 +109,24 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "addToCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "address", "name": "user", "type": "address" }
+ ],
+ "name": "allowed",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "approved", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
],
@@ -146,6 +164,23 @@
"type": "function"
},
{
+ "inputs": [],
+ "name": "collectionOwner",
+ "outputs": [
+ {
+ "components": [
+ { "internalType": "address", "name": "field_0", "type": "address" },
+ { "internalType": "uint256", "name": "field_1", "type": "uint256" }
+ ],
+ "internalType": "struct Tuple17",
+ "name": "",
+ "type": "tuple"
+ }
+ ],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
"inputs": [{ "internalType": "string", "name": "key", "type": "string" }],
"name": "collectionProperty",
"outputs": [{ "internalType": "bytes", "name": "", "type": "bytes" }],
@@ -376,6 +411,15 @@
},
{
"inputs": [
+ { "internalType": "uint256", "name": "user", "type": "uint256" }
+ ],
+ "name": "removeFromCollectionAllowListSubstrate",
+ "outputs": [],
+ "stateMutability": "nonpayable",
+ "type": "function"
+ },
+ {
+ "inputs": [
{ "internalType": "address", "name": "from", "type": "address" },
{ "internalType": "address", "name": "to", "type": "address" },
{ "internalType": "uint256", "name": "tokenId", "type": "uint256" }
tests/src/util/helpers.tsdiffbeforeafterboth1// 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/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38 Substrate: string,39} | {40 Ethereum: string,41};424344export enum Pallets {45 Inflation = 'inflation',46 RmrkCore = 'rmrkcore',47 RmrkEquip = 'rmrkequip',48 ReFungible = 'refungible',49 Fungible = 'fungible',50 NFT = 'nonfungible',51 Scheduler = 'scheduler',52 AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56 return usingApi(async api => {57 const chain = await api.rpc.system.chain();5859 return chain.eq('UNIQUE');60 });61}6263export async function isQuartz(): Promise<boolean> {64 return usingApi(async api => {65 const chain = await api.rpc.system.chain();66 67 return chain.eq('QUARTZ');68 });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73 if (typeof modulesNames === 'undefined') 74 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75 return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79 return await usingApi(async api => {80 const pallets = getModuleNames(api);8182 return requiredPallets.filter(p => !pallets.includes(p));83 });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87 return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91 const missingPallets = await missingRequiredPallets(requiredPallets);9293 if (missingPallets.length > 0) {94 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100 mocha.skip();101 }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {109 if (typeof input === 'string') {110 if (input.length >= 47) {111 return {Substrate: input};112 } else if (input.length === 42 && input.startsWith('0x')) {113 return {Ethereum: input.toLowerCase()};114 } else if (input.length === 40 && !input.startsWith('0x')) {115 return {Ethereum: '0x' + input.toLowerCase()};116 } else {117 throw new Error(`Unknown address format: "${input}"`);118 }119 }120 if ('address' in input) {121 return {Substrate: input.address};122 }123 if ('Ethereum' in input) {124 return {125 Ethereum: input.Ethereum.toLowerCase(),126 };127 } else if ('ethereum' in input) {128 return {129 Ethereum: (input as any).ethereum.toLowerCase(),130 };131 } else if ('Substrate' in input) {132 return input;133 } else if ('substrate' in input) {134 return {135 Substrate: (input as any).substrate,136 };137 }138139 // AccountId140 return {Substrate: input.toString()};141}142export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {143 input = normalizeAccountId(input);144 if ('Substrate' in input) {145 return input.Substrate;146 } else {147 return evmToAddress(input.Ethereum);148 }149}150151export const U128_MAX = (1n << 128n) - 1n;152153const MICROUNIQUE = 1_000_000_000_000n;154const MILLIUNIQUE = 1_000n * MICROUNIQUE;155const CENTIUNIQUE = 10n * MILLIUNIQUE;156export const UNIQUE = 100n * CENTIUNIQUE;157158interface GenericResult<T> {159 success: boolean;160 data: T | null;161}162163interface CreateCollectionResult {164 success: boolean;165 collectionId: number;166}167168interface CreateItemResult {169 success: boolean;170 collectionId: number;171 itemId: number;172 recipient?: CrossAccountId;173 amount?: number;174}175176interface DestroyItemResult {177 success: boolean;178 collectionId: number;179 itemId: number;180 owner: CrossAccountId;181 amount: number;182}183184interface TransferResult {185 collectionId: number;186 itemId: number;187 sender?: CrossAccountId;188 recipient?: CrossAccountId;189 value: bigint;190}191192interface IReFungibleOwner {193 fraction: BN;194 owner: number[];195}196197interface IGetMessage {198 checkMsgUnqMethod: string;199 checkMsgTrsMethod: string;200 checkMsgSysMethod: string;201}202203export interface IFungibleTokenDataType {204 value: number;205}206207export interface IChainLimits {208 collectionNumbersLimit: number;209 accountTokenOwnershipLimit: number;210 collectionsAdminsLimit: number;211 customDataLimit: number;212 nftSponsorTransferTimeout: number;213 fungibleSponsorTransferTimeout: number;214 refungibleSponsorTransferTimeout: number;215 //offchainSchemaLimit: number;216 //constOnChainSchemaLimit: number;217}218219export interface IReFungibleTokenDataType {220 owner: IReFungibleOwner[];221}222223export function uniqueEventMessage(events: EventRecord[]): IGetMessage {224 let checkMsgUnqMethod = '';225 let checkMsgTrsMethod = '';226 let checkMsgSysMethod = '';227 events.forEach(({event: {method, section}}) => {228 if (section === 'common') {229 checkMsgUnqMethod = method;230 } else if (section === 'treasury') {231 checkMsgTrsMethod = method;232 } else if (section === 'system') {233 checkMsgSysMethod = method;234 } else { return null; }235 });236 const result: IGetMessage = {237 checkMsgUnqMethod,238 checkMsgTrsMethod,239 checkMsgSysMethod,240 };241 return result;242}243244export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {245 const event = events.find(r => check(r.event));246 if (!event) return;247 return event.event as T;248}249250export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;251export function getGenericResult<T>(252 events: EventRecord[],253 expectSection: string,254 expectMethod: string,255 extractAction: (data: GenericEventData) => T256): GenericResult<T>;257258export function getGenericResult<T>(259 events: EventRecord[],260 expectSection?: string,261 expectMethod?: string,262 extractAction?: (data: GenericEventData) => T,263): GenericResult<T> {264 let success = false;265 let successData = null;266267 events.forEach(({event: {data, method, section}}) => {268 // console.log(` ${phase}: ${section}.${method}:: ${data}`);269 if (method === 'ExtrinsicSuccess') {270 success = true;271 } else if ((expectSection == section) && (expectMethod == method)) {272 successData = extractAction!(data as any);273 }274 });275276 const result: GenericResult<T> = {277 success,278 data: successData,279 };280 return result;281}282283export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {284 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));285 const result: CreateCollectionResult = {286 success: genericResult.success,287 collectionId: genericResult.data ?? 0,288 };289 return result;290}291292export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {293 const results: CreateItemResult[] = [];294 295 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {296 const collectionId = parseInt(data[0].toString(), 10);297 const itemId = parseInt(data[1].toString(), 10);298 const recipient = normalizeAccountId(data[2].toJSON() as any);299 const amount = parseInt(data[3].toString(), 10);300301 const itemRes: CreateItemResult = {302 success: true,303 collectionId,304 itemId,305 recipient,306 amount,307 };308309 results.push(itemRes);310 return results;311 });312313 if (!genericResult.success) return [];314 return results;315}316317export function getCreateItemResult(events: EventRecord[]): CreateItemResult {318 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));319 320 if (genericResult.data == null) 321 return {322 success: genericResult.success,323 collectionId: 0,324 itemId: 0,325 amount: 0,326 };327 else 328 return {329 success: genericResult.success,330 collectionId: genericResult.data[0] as number,331 itemId: genericResult.data[1] as number,332 recipient: normalizeAccountId(genericResult.data![2] as any),333 amount: genericResult.data[3] as number,334 };335}336337export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {338 const results: DestroyItemResult[] = [];339 340 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {341 const collectionId = parseInt(data[0].toString(), 10);342 const itemId = parseInt(data[1].toString(), 10);343 const owner = normalizeAccountId(data[2].toJSON() as any);344 const amount = parseInt(data[3].toString(), 10);345346 const itemRes: DestroyItemResult = {347 success: true,348 collectionId,349 itemId,350 owner,351 amount,352 };353354 results.push(itemRes);355 return results;356 });357358 if (!genericResult.success) return [];359 return results;360}361362export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {363 for (const {event} of events) {364 if (api.events.common.Transfer.is(event)) {365 const [collection, token, sender, recipient, value] = event.data;366 return {367 collectionId: collection.toNumber(),368 itemId: token.toNumber(),369 sender: normalizeAccountId(sender.toJSON() as any),370 recipient: normalizeAccountId(recipient.toJSON() as any),371 value: value.toBigInt(),372 };373 }374 }375 throw new Error('no transfer event');376}377378interface Nft {379 type: 'NFT';380}381382interface Fungible {383 type: 'Fungible';384 decimalPoints: number;385}386387interface ReFungible {388 type: 'ReFungible';389}390391export type CollectionMode = Nft | Fungible | ReFungible;392393export type Property = {394 key: any,395 value: any,396};397398type Permission = {399 mutable: boolean;400 collectionAdmin: boolean;401 tokenOwner: boolean;402}403404type PropertyPermission = {405 key: any;406 permission: Permission;407}408409export type CreateCollectionParams = {410 mode: CollectionMode,411 name: string,412 description: string,413 tokenPrefix: string,414 properties?: Array<Property>,415 propPerm?: Array<PropertyPermission>416};417418const defaultCreateCollectionParams: CreateCollectionParams = {419 description: 'description',420 mode: {type: 'NFT'},421 name: 'name',422 tokenPrefix: 'prefix',423};424425export async function426createCollection(427 api: ApiPromise,428 sender: IKeyringPair,429 params: Partial<CreateCollectionParams> = {},430): Promise<CreateCollectionResult> {431 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433 let modeprm = {};434 if (mode.type === 'NFT') {435 modeprm = {nft: null};436 } else if (mode.type === 'Fungible') {437 modeprm = {fungible: mode.decimalPoints};438 } else if (mode.type === 'ReFungible') {439 modeprm = {refungible: null};440 }441442 const tx = api.tx.unique.createCollectionEx({443 name: strToUTF16(name),444 description: strToUTF16(description),445 tokenPrefix: strToUTF16(tokenPrefix),446 mode: modeprm as any,447 });448 const events = await executeTransaction(api, sender, tx);449 return getCreateCollectionResult(events);450}451452export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {453 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};454455 let collectionId = 0;456 await usingApi(async (api, privateKeyWrapper) => {457 // Get number of collections before the transaction458 const collectionCountBefore = await getCreatedCollectionCount(api);459460 // Run the CreateCollection transaction461 const alicePrivateKey = privateKeyWrapper('//Alice');462463 const result = await createCollection(api, alicePrivateKey, params);464465 // Get number of collections after the transaction466 const collectionCountAfter = await getCreatedCollectionCount(api);467468 // Get the collection469 const collection = await queryCollectionExpectSuccess(api, result.collectionId);470471 // What to expect472 // tslint:disable-next-line:no-unused-expression473 expect(result.success).to.be.true;474 expect(result.collectionId).to.be.equal(collectionCountAfter);475 // tslint:disable-next-line:no-unused-expression476 expect(collection).to.be.not.null;477 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');478 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));479 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);480 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);481 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);482483 collectionId = result.collectionId;484 });485486 return collectionId;487}488489export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {490 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};491492 let collectionId = 0;493 await usingApi(async (api, privateKeyWrapper) => {494 // Get number of collections before the transaction495 const collectionCountBefore = await getCreatedCollectionCount(api);496497 // Run the CreateCollection transaction498 const alicePrivateKey = privateKeyWrapper('//Alice');499500 let modeprm = {};501 if (mode.type === 'NFT') {502 modeprm = {nft: null};503 } else if (mode.type === 'Fungible') {504 modeprm = {fungible: mode.decimalPoints};505 } else if (mode.type === 'ReFungible') {506 modeprm = {refungible: null};507 }508509 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});510 const events = await submitTransactionAsync(alicePrivateKey, tx);511 const result = getCreateCollectionResult(events);512513 // Get number of collections after the transaction514 const collectionCountAfter = await getCreatedCollectionCount(api);515516 // Get the collection517 const collection = await queryCollectionExpectSuccess(api, result.collectionId);518519 // What to expect520 // tslint:disable-next-line:no-unused-expression521 expect(result.success).to.be.true;522 expect(result.collectionId).to.be.equal(collectionCountAfter);523 // tslint:disable-next-line:no-unused-expression524 expect(collection).to.be.not.null;525 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');526 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));527 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);528 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);529 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);530531532 collectionId = result.collectionId;533 });534535 return collectionId;536}537538export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {539 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};540541 await usingApi(async (api, privateKeyWrapper) => {542 // Get number of collections before the transaction543 const collectionCountBefore = await getCreatedCollectionCount(api);544545 // Run the CreateCollection transaction546 const alicePrivateKey = privateKeyWrapper('//Alice');547548 let modeprm = {};549 if (mode.type === 'NFT') {550 modeprm = {nft: null};551 } else if (mode.type === 'Fungible') {552 modeprm = {fungible: mode.decimalPoints};553 } else if (mode.type === 'ReFungible') {554 modeprm = {refungible: null};555 }556557 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});558 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;559560561 // Get number of collections after the transaction562 const collectionCountAfter = await getCreatedCollectionCount(api);563564 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');565 });566}567568export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {569 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};570571 let modeprm = {};572 if (mode.type === 'NFT') {573 modeprm = {nft: null};574 } else if (mode.type === 'Fungible') {575 modeprm = {fungible: mode.decimalPoints};576 } else if (mode.type === 'ReFungible') {577 modeprm = {refungible: null};578 }579580 await usingApi(async (api, privateKeyWrapper) => {581 // Get number of collections before the transaction582 const collectionCountBefore = await getCreatedCollectionCount(api);583584 // Run the CreateCollection transaction585 const alicePrivateKey = privateKeyWrapper('//Alice');586 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});587 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;588589 // Get number of collections after the transaction590 const collectionCountAfter = await getCreatedCollectionCount(api);591592 // What to expect593 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');594 });595}596597export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {598 let bal = 0n;599 let unused;600 do {601 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;602 unused = privateKeyWrapper(`//${randomSeed}`);603 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();604 } while (bal !== 0n);605 return unused;606}607608export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {609 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();610}611612export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {613 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));614}615616export async function findNotExistingCollection(api: ApiPromise): Promise<number> {617 const totalNumber = await getCreatedCollectionCount(api);618 const newCollection: number = totalNumber + 1;619 return newCollection;620}621622function getDestroyResult(events: EventRecord[]): boolean {623 let success = false;624 events.forEach(({event: {method}}) => {625 if (method == 'ExtrinsicSuccess') {626 success = true;627 }628 });629 return success;630}631632export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {633 await usingApi(async (api, privateKeyWrapper) => {634 // Run the DestroyCollection transaction635 const alicePrivateKey = privateKeyWrapper(senderSeed);636 const tx = api.tx.unique.destroyCollection(collectionId);637 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638 });639}640641export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {642 await usingApi(async (api, privateKeyWrapper) => {643 // Run the DestroyCollection transaction644 const alicePrivateKey = privateKeyWrapper(senderSeed);645 const tx = api.tx.unique.destroyCollection(collectionId);646 const events = await submitTransactionAsync(alicePrivateKey, tx);647 const result = getDestroyResult(events);648 expect(result).to.be.true;649650 // What to expect651 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;652 });653}654655export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {656 await usingApi(async (api) => {657 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);658 const events = await submitTransactionAsync(sender, tx);659 const result = getGenericResult(events);660661 expect(result.success).to.be.true;662 });663}664665export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {666 await usingApi(async(api) => {667 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673};674675export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {676 await usingApi(async (api) => {677 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);678 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 const result = getGenericResult(events);680681 expect(result.success).to.be.false;682 });683}684685export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {686 await usingApi(async (api, privateKeyWrapper) => {687688 // Run the transaction689 const senderPrivateKey = privateKeyWrapper(sender);690 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);691 const events = await submitTransactionAsync(senderPrivateKey, tx);692 const result = getGenericResult(events);693694 // Get the collection695 const collection = await queryCollectionExpectSuccess(api, collectionId);696697 // What to expect698 expect(result.success).to.be.true;699 expect(collection.sponsorship.toJSON()).to.deep.equal({700 unconfirmed: sponsor,701 });702 });703}704705export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {706 await usingApi(async (api, privateKeyWrapper) => {707708 // Run the transaction709 const alicePrivateKey = privateKeyWrapper(sender);710 const tx = api.tx.unique.removeCollectionSponsor(collectionId);711 const events = await submitTransactionAsync(alicePrivateKey, tx);712 const result = getGenericResult(events);713714 // Get the collection715 const collection = await queryCollectionExpectSuccess(api, collectionId);716717 // What to expect718 expect(result.success).to.be.true;719 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});720 });721}722723export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {724 await usingApi(async (api, privateKeyWrapper) => {725726 // Run the transaction727 const alicePrivateKey = privateKeyWrapper(senderSeed);728 const tx = api.tx.unique.removeCollectionSponsor(collectionId);729 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;730 });731}732733export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {734 await usingApi(async (api, privateKeyWrapper) => {735736 // Run the transaction737 const alicePrivateKey = privateKeyWrapper(senderSeed);738 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);739 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;740 });741}742743export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {744 await usingApi(async (api, privateKeyWrapper) => {745746 // Run the transaction747 const sender = privateKeyWrapper(senderSeed);748 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);749 });750}751752export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {753 await usingApi(async (api, privateKeyWrapper) => {754755 // Run the transaction756 const tx = api.tx.unique.confirmSponsorship(collectionId);757 const events = await submitTransactionAsync(sender, tx);758 const result = getGenericResult(events);759760 // Get the collection761 const collection = await queryCollectionExpectSuccess(api, collectionId);762763 // What to expect764 expect(result.success).to.be.true;765 expect(collection.sponsorship.toJSON()).to.be.deep.equal({766 confirmed: sender.address,767 });768 });769}770771772export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {773 await usingApi(async (api, privateKeyWrapper) => {774775 // Run the transaction776 const sender = privateKeyWrapper(senderSeed);777 const tx = api.tx.unique.confirmSponsorship(collectionId);778 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779 });780}781782export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {783 await usingApi(async (api) => {784 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);785 const events = await submitTransactionAsync(sender, tx);786 const result = getGenericResult(events);787788 expect(result.success).to.be.true;789 });790}791792export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {793 await usingApi(async (api) => {794 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);795 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;796 const result = getGenericResult(events);797798 expect(result.success).to.be.false;799 });800}801802export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {803804 await usingApi(async (api) => {805806 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);807 const events = await submitTransactionAsync(sender, tx);808 const result = getGenericResult(events);809810 expect(result.success).to.be.true;811 });812}813814export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {815816 await usingApi(async (api) => {817818 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);819 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;820 const result = getGenericResult(events);821822 expect(result.success).to.be.false;823 });824}825826export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {827 await usingApi(async (api) => {828 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);829 const events = await submitTransactionAsync(sender, tx);830 const result = getGenericResult(events);831832 expect(result.success).to.be.true;833 });834}835836export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {837 await usingApi(async (api) => {838 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);839 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;840 const result = getGenericResult(events);841842 expect(result.success).to.be.false;843 });844}845846export async function getNextSponsored(847 api: ApiPromise,848 collectionId: number,849 account: string | CrossAccountId,850 tokenId: number,851): Promise<number> {852 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));853}854855export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {856 await usingApi(async (api) => {857 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);858 const events = await submitTransactionAsync(sender, tx);859 const result = getGenericResult(events);860861 expect(result.success).to.be.true;862 });863}864865export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {866 let allowlisted = false;867 await usingApi(async (api) => {868 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;869 });870 return allowlisted;871}872873export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {874 await usingApi(async (api) => {875 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());876 const events = await submitTransactionAsync(sender, tx);877 const result = getGenericResult(events);878879 expect(result.success).to.be.true;880 });881}882883export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {884 await usingApi(async (api) => {885 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());886 const events = await submitTransactionAsync(sender, tx);887 const result = getGenericResult(events);888889 expect(result.success).to.be.true;890 });891}892893export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {894 await usingApi(async (api) => {895 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());896 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;897 const result = getGenericResult(events);898899 expect(result.success).to.be.false;900 });901}902903export interface CreateFungibleData {904 readonly Value: bigint;905}906907export interface CreateReFungibleData { }908export interface CreateNftData { }909910export type CreateItemData = {911 NFT: CreateNftData;912} | {913 Fungible: CreateFungibleData;914} | {915 ReFungible: CreateReFungibleData;916};917918export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {919 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);920 const events = await submitTransactionAsync(sender, tx);921 return getGenericResult(events).success;922}923924export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {925 await usingApi(async (api) => {926 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927 // if burning token by admin - use adminButnItemExpectSuccess928 expect(balanceBefore >= BigInt(value)).to.be.true;929930 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;931932 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);933 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);934 });935}936937export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938 await usingApi(async (api) => {939 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);940941 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;942 const result = getCreateCollectionResult(events);943 // tslint:disable-next-line:no-unused-expression944 expect(result.success).to.be.false;945 });946}947948export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {949 await usingApi(async (api) => {950 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);951 const events = await submitTransactionAsync(sender, tx);952 return getGenericResult(events).success;953 });954}955956export async function957approve(958 api: ApiPromise,959 collectionId: number,960 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,961) {962 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963 const events = await submitTransactionAsync(owner, approveUniqueTx);964 return getGenericResult(events).success;965}966967export async function968approveExpectSuccess(969 collectionId: number,970 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,971) {972 await usingApi(async (api: ApiPromise) => {973 const result = await approve(api, collectionId, tokenId, owner, approved, amount);974 expect(result).to.be.true;975976 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));977 });978}979980export async function adminApproveFromExpectSuccess(981 collectionId: number,982 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,983) {984 await usingApi(async (api: ApiPromise) => {985 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);986 const events = await submitTransactionAsync(admin, approveUniqueTx);987 const result = getGenericResult(events);988 expect(result.success).to.be.true;989990 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991 });992}993994export async function995transferFrom(996 api: ApiPromise,997 collectionId: number,998 tokenId: number,999 accountApproved: IKeyringPair,1000 accountFrom: IKeyringPair | CrossAccountId,1001 accountTo: IKeyringPair | CrossAccountId,1002 value: number | bigint,1003) {1004 const from = normalizeAccountId(accountFrom);1005 const to = normalizeAccountId(accountTo);1006 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1007 const events = await submitTransactionAsync(accountApproved, transferFromTx);1008 return getGenericResult(events).success;1009}10101011export async function1012transferFromExpectSuccess(1013 collectionId: number,1014 tokenId: number,1015 accountApproved: IKeyringPair,1016 accountFrom: IKeyringPair | CrossAccountId,1017 accountTo: IKeyringPair | CrossAccountId,1018 value: number | bigint = 1,1019 type = 'NFT',1020) {1021 await usingApi(async (api: ApiPromise) => {1022 const from = normalizeAccountId(accountFrom);1023 const to = normalizeAccountId(accountTo);1024 let balanceBefore = 0n;1025 if (type === 'Fungible' || type === 'ReFungible') {1026 balanceBefore = await getBalance(api, collectionId, to, tokenId);1027 }1028 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1029 if (type === 'NFT') {1030 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1031 }1032 if (type === 'Fungible') {1033 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1034 if (JSON.stringify(to) !== JSON.stringify(from)) {1035 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1036 } else {1037 expect(balanceAfter).to.be.equal(balanceBefore);1038 }1039 }1040 if (type === 'ReFungible') {1041 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1042 }1043 });1044}10451046export async function1047transferFromExpectFail(1048 collectionId: number,1049 tokenId: number,1050 accountApproved: IKeyringPair,1051 accountFrom: IKeyringPair,1052 accountTo: IKeyringPair,1053 value: number | bigint = 1,1054) {1055 await usingApi(async (api: ApiPromise) => {1056 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1057 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1058 const result = getCreateCollectionResult(events);1059 // tslint:disable-next-line:no-unused-expression1060 expect(result.success).to.be.false;1061 });1062}10631064/* eslint no-async-promise-executor: "off" */1065export async function getBlockNumber(api: ApiPromise): Promise<number> {1066 return new Promise<number>(async (resolve) => {1067 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1068 unsubscribe();1069 resolve(head.number.toNumber());1070 });1071 });1072}10731074export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1075 await usingApi(async (api) => {1076 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1077 const events = await submitTransactionAsync(sender, changeAdminTx);1078 const result = getCreateCollectionResult(events);1079 expect(result.success).to.be.true;1080 });1081}10821083export async function adminApproveFromExpectFail(1084 collectionId: number,1085 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1086) {1087 await usingApi(async (api: ApiPromise) => {1088 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1089 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1090 const result = getGenericResult(events);1091 expect(result.success).to.be.false;1092 });1093}10941095export async function1096getFreeBalance(account: IKeyringPair): Promise<bigint> {1097 let balance = 0n;1098 await usingApi(async (api) => {1099 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1100 });11011102 return balance;1103}11041105export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1106 const tx = api.tx.balances.transfer(target, amount);1107 const events = await submitTransactionAsync(source, tx);1108 const result = getGenericResult(events);1109 expect(result.success).to.be.true;1110}11111112export async function1113scheduleExpectSuccess(1114 operationTx: any,1115 sender: IKeyringPair,1116 blockSchedule: number,1117 scheduledId: string,1118 period = 1,1119 repetitions = 1,1120) {1121 await usingApi(async (api: ApiPromise) => {1122 const blockNumber: number | undefined = await getBlockNumber(api);1123 const expectedBlockNumber = blockNumber + blockSchedule;11241125 expect(blockNumber).to.be.greaterThan(0);1126 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1127 scheduledId,1128 expectedBlockNumber, 1129 repetitions > 1 ? [period, repetitions] : null, 1130 0, 1131 {Value: operationTx as any},1132 );11331134 const events = await submitTransactionAsync(sender, scheduleTx);1135 expect(getGenericResult(events).success).to.be.true;1136 });1137}11381139export async function1140scheduleExpectFailure(1141 operationTx: any,1142 sender: IKeyringPair,1143 blockSchedule: number,1144 scheduledId: string,1145 period = 1,1146 repetitions = 1,1147) {1148 await usingApi(async (api: ApiPromise) => {1149 const blockNumber: number | undefined = await getBlockNumber(api);1150 const expectedBlockNumber = blockNumber + blockSchedule;11511152 expect(blockNumber).to.be.greaterThan(0);1153 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1154 scheduledId,1155 expectedBlockNumber, 1156 repetitions <= 1 ? null : [period, repetitions], 1157 0, 1158 {Value: operationTx as any},1159 );11601161 //const events = 1162 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1163 //expect(getGenericResult(events).success).to.be.false;1164 });1165}11661167export async function1168scheduleTransferAndWaitExpectSuccess(1169 collectionId: number,1170 tokenId: number,1171 sender: IKeyringPair,1172 recipient: IKeyringPair,1173 value: number | bigint = 1,1174 blockSchedule: number,1175 scheduledId: string,1176) {1177 await usingApi(async (api: ApiPromise) => {1178 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11791180 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11811182 // sleep for n + 1 blocks1183 await waitNewBlocks(blockSchedule + 1);11841185 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11861187 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1188 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1189 });1190}11911192export async function1193scheduleTransferExpectSuccess(1194 collectionId: number,1195 tokenId: number,1196 sender: IKeyringPair,1197 recipient: IKeyringPair,1198 value: number | bigint = 1,1199 blockSchedule: number,1200 scheduledId: string,1201) {1202 await usingApi(async (api: ApiPromise) => {1203 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12041205 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12061207 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1208 });1209}12101211export async function1212scheduleTransferFundsPeriodicExpectSuccess(1213 amount: bigint,1214 sender: IKeyringPair,1215 recipient: IKeyringPair,1216 blockSchedule: number,1217 scheduledId: string,1218 period: number,1219 repetitions: number,1220) {1221 await usingApi(async (api: ApiPromise) => {1222 const transferTx = api.tx.balances.transfer(recipient.address, amount);12231224 const balanceBefore = await getFreeBalance(recipient);1225 1226 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12271228 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1229 });1230}12311232export async function1233transfer(1234 api: ApiPromise,1235 collectionId: number,1236 tokenId: number,1237 sender: IKeyringPair,1238 recipient: IKeyringPair | CrossAccountId,1239 value: number | bigint,1240) : Promise<boolean> {1241 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242 const events = await executeTransaction(api, sender, transferTx);1243 return getGenericResult(events).success;1244}12451246export async function1247transferExpectSuccess(1248 collectionId: number,1249 tokenId: number,1250 sender: IKeyringPair,1251 recipient: IKeyringPair | CrossAccountId,1252 value: number | bigint = 1,1253 type = 'NFT',1254) {1255 await usingApi(async (api: ApiPromise) => {1256 const from = normalizeAccountId(sender);1257 const to = normalizeAccountId(recipient);12581259 let balanceBefore = 0n;1260 if (type === 'Fungible' || type === 'ReFungible') {1261 balanceBefore = await getBalance(api, collectionId, to, tokenId);1262 }12631264 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1265 const events = await executeTransaction(api, sender, transferTx);1266 const result = getTransferResult(api, events);12671268 expect(result.collectionId).to.be.equal(collectionId);1269 expect(result.itemId).to.be.equal(tokenId);1270 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1271 expect(result.recipient).to.be.deep.equal(to);1272 expect(result.value).to.be.equal(BigInt(value));12731274 if (type === 'NFT') {1275 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1276 }1277 if (type === 'Fungible' || type === 'ReFungible') {1278 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1279 if (JSON.stringify(to) !== JSON.stringify(from)) {1280 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1281 } else {1282 expect(balanceAfter).to.be.equal(balanceBefore);1283 }1284 }1285 });1286}12871288export async function1289transferExpectFailure(1290 collectionId: number,1291 tokenId: number,1292 sender: IKeyringPair,1293 recipient: IKeyringPair | CrossAccountId,1294 value: number | bigint = 1,1295) {1296 await usingApi(async (api: ApiPromise) => {1297 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1298 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1299 const result = getGenericResult(events);1300 // if (events && Array.isArray(events)) {1301 // const result = getCreateCollectionResult(events);1302 // tslint:disable-next-line:no-unused-expression1303 expect(result.success).to.be.false;1304 //}1305 });1306}13071308export async function1309approveExpectFail(1310 collectionId: number,1311 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1312) {1313 await usingApi(async (api: ApiPromise) => {1314 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1315 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1316 const result = getCreateCollectionResult(events);1317 // tslint:disable-next-line:no-unused-expression1318 expect(result.success).to.be.false;1319 });1320}13211322export async function getBalance(1323 api: ApiPromise,1324 collectionId: number,1325 owner: string | CrossAccountId | IKeyringPair,1326 token: number,1327): Promise<bigint> {1328 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1329}1330export async function getTokenOwner(1331 api: ApiPromise,1332 collectionId: number,1333 token: number,1334): Promise<CrossAccountId> {1335 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1336 if (owner == null) throw new Error('owner == null');1337 return normalizeAccountId(owner);1338}1339export async function getTopmostTokenOwner(1340 api: ApiPromise,1341 collectionId: number,1342 token: number,1343): Promise<CrossAccountId> {1344 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1345 if (owner == null) throw new Error('owner == null');1346 return normalizeAccountId(owner);1347}1348export async function getTokenChildren(1349 api: ApiPromise,1350 collectionId: number,1351 tokenId: number,1352): Promise<UpDataStructsTokenChild[]> {1353 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1354}1355export async function isTokenExists(1356 api: ApiPromise,1357 collectionId: number,1358 token: number,1359): Promise<boolean> {1360 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1361}1362export async function getLastTokenId(1363 api: ApiPromise,1364 collectionId: number,1365): Promise<number> {1366 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1367}1368export async function getAdminList(1369 api: ApiPromise,1370 collectionId: number,1371): Promise<string[]> {1372 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1373}1374export async function getTokenProperties(1375 api: ApiPromise,1376 collectionId: number,1377 tokenId: number,1378 propertyKeys: string[],1379): Promise<UpDataStructsProperty[]> {1380 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1381}13821383export async function createFungibleItemExpectSuccess(1384 sender: IKeyringPair,1385 collectionId: number,1386 data: CreateFungibleData,1387 owner: CrossAccountId | string = sender.address,1388) {1389 return await usingApi(async (api) => {1390 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13911392 const events = await submitTransactionAsync(sender, tx);1393 const result = getCreateItemResult(events);13941395 expect(result.success).to.be.true;1396 return result.itemId;1397 });1398}13991400export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1401 await usingApi(async (api) => {1402 const to = normalizeAccountId(owner);1403 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14041405 const events = await submitTransactionAsync(sender, tx);1406 expect(getGenericResult(events).success).to.be.true;1407 });1408}14091410export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1411 await usingApi(async (api) => {1412 const to = normalizeAccountId(owner);1413 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14141415 const events = await submitTransactionAsync(sender, tx);1416 const result = getCreateItemsResult(events);14171418 for (const res of result) {1419 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1420 }1421 });1422}14231424export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1425 await usingApi(async (api) => {1426 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14271428 const events = await submitTransactionAsync(sender, tx);1429 const result = getCreateItemsResult(events);14301431 for (const res of result) {1432 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1433 }1434 });1435}14361437export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1438 let newItemId = 0;1439 await usingApi(async (api) => {1440 const to = normalizeAccountId(owner);1441 const itemCountBefore = await getLastTokenId(api, collectionId);1442 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14431444 let tx;1445 if (createMode === 'Fungible') {1446 const createData = {fungible: {value: 10}};1447 tx = api.tx.unique.createItem(collectionId, to, createData as any);1448 } else if (createMode === 'ReFungible') {1449 const createData = {refungible: {pieces: 100}};1450 tx = api.tx.unique.createItem(collectionId, to, createData as any);1451 } else {1452 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1453 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1454 }14551456 const events = await submitTransactionAsync(sender, tx);1457 const result = getCreateItemResult(events);14581459 const itemCountAfter = await getLastTokenId(api, collectionId);1460 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14611462 if (createMode === 'NFT') {1463 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1464 }14651466 // What to expect1467 // tslint:disable-next-line:no-unused-expression1468 expect(result.success).to.be.true;1469 if (createMode === 'Fungible') {1470 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1471 } else {1472 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1473 }1474 expect(collectionId).to.be.equal(result.collectionId);1475 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1476 expect(to).to.be.deep.equal(result.recipient);1477 newItemId = result.itemId;1478 });1479 return newItemId;1480}14811482export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1483 await usingApi(async (api) => {14841485 let tx;1486 if (createMode === 'NFT') {1487 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1488 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1489 } else {1490 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1491 }149214931494 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1495 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1496 const result = getCreateItemResult(events);14971498 expect(result.success).to.be.false;1499 });1500}15011502export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1503 let newItemId = 0;1504 await usingApi(async (api) => {1505 const to = normalizeAccountId(owner);1506 const itemCountBefore = await getLastTokenId(api, collectionId);1507 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15081509 let tx;1510 if (createMode === 'Fungible') {1511 const createData = {fungible: {value: 10}};1512 tx = api.tx.unique.createItem(collectionId, to, createData as any);1513 } else if (createMode === 'ReFungible') {1514 const createData = {refungible: {pieces: 100}};1515 tx = api.tx.unique.createItem(collectionId, to, createData as any);1516 } else {1517 const createData = {nft: {}};1518 tx = api.tx.unique.createItem(collectionId, to, createData as any);1519 }15201521 const events = await executeTransaction(api, sender, tx);1522 const result = getCreateItemResult(events);15231524 const itemCountAfter = await getLastTokenId(api, collectionId);1525 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15261527 // What to expect1528 // tslint:disable-next-line:no-unused-expression1529 expect(result.success).to.be.true;1530 if (createMode === 'Fungible') {1531 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1532 } else {1533 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1534 }1535 expect(collectionId).to.be.equal(result.collectionId);1536 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1537 expect(to).to.be.deep.equal(result.recipient);1538 newItemId = result.itemId;1539 });1540 return newItemId;1541}15421543export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1544 const createData = {refungible: {pieces: amount}};1545 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15461547 const events = await submitTransactionAsync(sender, tx);1548 return getCreateItemResult(events);1549}15501551export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1552 await usingApi(async (api) => {1553 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15541555 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1556 const result = getCreateItemResult(events);15571558 expect(result.success).to.be.false;1559 });1560}15611562export async function setPublicAccessModeExpectSuccess(1563 sender: IKeyringPair, collectionId: number,1564 accessMode: 'Normal' | 'AllowList',1565) {1566 await usingApi(async (api) => {15671568 // Run the transaction1569 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1570 const events = await submitTransactionAsync(sender, tx);1571 const result = getGenericResult(events);15721573 // Get the collection1574 const collection = await queryCollectionExpectSuccess(api, collectionId);15751576 // What to expect1577 // tslint:disable-next-line:no-unused-expression1578 expect(result.success).to.be.true;1579 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1580 });1581}15821583export async function setPublicAccessModeExpectFail(1584 sender: IKeyringPair, collectionId: number,1585 accessMode: 'Normal' | 'AllowList',1586) {1587 await usingApi(async (api) => {15881589 // Run the transaction1590 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1592 const result = getGenericResult(events);15931594 // What to expect1595 // tslint:disable-next-line:no-unused-expression1596 expect(result.success).to.be.false;1597 });1598}15991600export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1601 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1602}16031604export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1605 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1606}16071608export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1610}16111612export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1613 await usingApi(async (api) => {16141615 // Run the transaction1616 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1617 const events = await submitTransactionAsync(sender, tx);1618 const result = getGenericResult(events);1619 expect(result.success).to.be.true;16201621 // Get the collection1622 const collection = await queryCollectionExpectSuccess(api, collectionId);16231624 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1625 });1626}16271628export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1629 await setMintPermissionExpectSuccess(sender, collectionId, true);1630}16311632export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1633 await usingApi(async (api) => {1634 // Run the transaction1635 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1636 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1637 const result = getCreateCollectionResult(events);1638 // tslint:disable-next-line:no-unused-expression1639 expect(result.success).to.be.false;1640 });1641}16421643export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1644 await usingApi(async (api) => {1645 // Run the transaction1646 const tx = api.tx.unique.setChainLimits(limits);1647 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1648 const result = getCreateCollectionResult(events);1649 // tslint:disable-next-line:no-unused-expression1650 expect(result.success).to.be.false;1651 });1652}16531654export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1655 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1656}16571658export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1659 await usingApi(async (api) => {1660 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16611662 // Run the transaction1663 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1664 const events = await submitTransactionAsync(sender, tx);1665 const result = getGenericResult(events);1666 expect(result.success).to.be.true;16671668 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1669 });1670}16711672export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1673 await usingApi(async (api) => {16741675 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16761677 // Run the transaction1678 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1679 const events = await submitTransactionAsync(sender, tx);1680 const result = getGenericResult(events);1681 expect(result.success).to.be.true;16821683 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1684 });1685}16861687export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1688 await usingApi(async (api) => {16891690 // Run the transaction1691 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1692 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1693 const result = getGenericResult(events);16941695 // What to expect1696 // tslint:disable-next-line:no-unused-expression1697 expect(result.success).to.be.false;1698 });1699}17001701export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1702 await usingApi(async (api) => {1703 // Run the transaction1704 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1705 const events = await submitTransactionAsync(sender, tx);1706 const result = getGenericResult(events);17071708 // What to expect1709 // tslint:disable-next-line:no-unused-expression1710 expect(result.success).to.be.true;1711 });1712}17131714export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1715 await usingApi(async (api) => {1716 // Run the transaction1717 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1718 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719 const result = getGenericResult(events);17201721 // What to expect1722 // tslint:disable-next-line:no-unused-expression1723 expect(result.success).to.be.false;1724 });1725}17261727export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1728 : Promise<UpDataStructsRpcCollection | null> => {1729 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1730};17311732export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1733 // set global object - collectionsCount1734 return (await api.rpc.unique.collectionStats()).created.toNumber();1735};17361737export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1738 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1739}17401741export async function waitNewBlocks(blocksCount = 1): Promise<void> {1742 await usingApi(async (api) => {1743 const promise = new Promise<void>(async (resolve) => {1744 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1745 if (blocksCount > 0) {1746 blocksCount--;1747 } else {1748 unsubscribe();1749 resolve();1750 }1751 });1752 });1753 return promise;1754 });1755}17561757export async function repartitionRFT(1758 api: ApiPromise,1759 collectionId: number,1760 sender: IKeyringPair,1761 tokenId: number,1762 amount: bigint,1763): Promise<boolean> {1764 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1765 const events = await submitTransactionAsync(sender, tx);1766 const result = getGenericResult(events);17671768 return result.success;1769}17701771export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1772 let i: any = it;1773 if (opts.only) i = i.only;1774 else if (opts.skip) i = i.skip;1775 i(name, async () => {1776 await usingApi(async (api, privateKeyWrapper) => {1777 await cb({api, privateKeyWrapper});1778 });1779 });1780}17811782itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1783itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});178417851786export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1787 const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1788 const subEvents = (await api.query.system.events.at(blockHash))1789 .filter(x => x.event.section === section)1790 .map((x) => x.toHuman());1791 const events = methods.map((m) => {1792 return {1793 event: {1794 method: m,1795 section,1796 },1797 };1798 });1799 if (!dryRun) {1800 expect(subEvents).to.be.like(events);1801 }1802 return subEvents;1803}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/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise} from '@polkadot/api';20import type {AccountId, EventRecord, Event, BlockNumber} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import {AnyNumber} from '@polkadot/types-codec/types';25import BN from 'bn.js';26import chai from 'chai';27import chaiAsPromised from 'chai-as-promised';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';32import {Context} from 'mocha';3334chai.use(chaiAsPromised);35const expect = chai.expect;3637export type CrossAccountId = {38 Substrate: string,39} | {40 Ethereum: string,41};424344export enum Pallets {45 Inflation = 'inflation',46 RmrkCore = 'rmrkcore',47 RmrkEquip = 'rmrkequip',48 ReFungible = 'refungible',49 Fungible = 'fungible',50 NFT = 'nonfungible',51 Scheduler = 'scheduler',52 AppPromotion = 'apppromotion',53}5455export async function isUnique(): Promise<boolean> {56 return usingApi(async api => {57 const chain = await api.rpc.system.chain();5859 return chain.eq('UNIQUE');60 });61}6263export async function isQuartz(): Promise<boolean> {64 return usingApi(async api => {65 const chain = await api.rpc.system.chain();66 67 return chain.eq('QUARTZ');68 });69}7071let modulesNames: any;72export function getModuleNames(api: ApiPromise): string[] {73 if (typeof modulesNames === 'undefined') 74 modulesNames = api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());75 return modulesNames;76}7778export async function missingRequiredPallets(requiredPallets: string[]): Promise<string[]> {79 return await usingApi(async api => {80 const pallets = getModuleNames(api);8182 return requiredPallets.filter(p => !pallets.includes(p));83 });84}8586export async function checkPalletsPresence(requiredPallets: string[]): Promise<boolean> {87 return (await missingRequiredPallets(requiredPallets)).length == 0;88}8990export async function requirePallets(mocha: Context, requiredPallets: string[]) {91 const missingPallets = await missingRequiredPallets(requiredPallets);9293 if (missingPallets.length > 0) {94 const skippingTestMsg = `\tSkipping test "${mocha.test?.title}".`;95 const missingPalletsMsg = `\tThe following pallets are missing:\n\t- ${missingPallets.join('\n\t- ')}`;96 const skipMsg = `${skippingTestMsg}\n${missingPalletsMsg}`;9798 console.error('\x1b[38:5:208m%s\x1b[0m', skipMsg);99100 mocha.skip();101 }102}103104export function bigIntToSub(api: ApiPromise, number: bigint) {105 return api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();106}107108export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {109 if (typeof input === 'string') {110 if (input.length >= 47) {111 return {Substrate: input};112 } else if (input.length === 42 && input.startsWith('0x')) {113 return {Ethereum: input.toLowerCase()};114 } else if (input.length === 40 && !input.startsWith('0x')) {115 return {Ethereum: '0x' + input.toLowerCase()};116 } else {117 throw new Error(`Unknown address format: "${input}"`);118 }119 }120 if ('address' in input) {121 return {Substrate: input.address};122 }123 if ('Ethereum' in input) {124 return {125 Ethereum: input.Ethereum.toLowerCase(),126 };127 } else if ('ethereum' in input) {128 return {129 Ethereum: (input as any).ethereum.toLowerCase(),130 };131 } else if ('Substrate' in input) {132 return input;133 } else if ('substrate' in input) {134 return {135 Substrate: (input as any).substrate,136 };137 }138139 // AccountId140 return {Substrate: input.toString()};141}142export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {143 input = normalizeAccountId(input);144 if ('Substrate' in input) {145 return input.Substrate;146 } else {147 return evmToAddress(input.Ethereum);148 }149}150151export const U128_MAX = (1n << 128n) - 1n;152153const MICROUNIQUE = 1_000_000_000_000n;154const MILLIUNIQUE = 1_000n * MICROUNIQUE;155const CENTIUNIQUE = 10n * MILLIUNIQUE;156export const UNIQUE = 100n * CENTIUNIQUE;157158interface GenericResult<T> {159 success: boolean;160 data: T | null;161}162163interface CreateCollectionResult {164 success: boolean;165 collectionId: number;166}167168interface CreateItemResult {169 success: boolean;170 collectionId: number;171 itemId: number;172 recipient?: CrossAccountId;173 amount?: number;174}175176interface DestroyItemResult {177 success: boolean;178 collectionId: number;179 itemId: number;180 owner: CrossAccountId;181 amount: number;182}183184interface TransferResult {185 collectionId: number;186 itemId: number;187 sender?: CrossAccountId;188 recipient?: CrossAccountId;189 value: bigint;190}191192interface IReFungibleOwner {193 fraction: BN;194 owner: number[];195}196197interface IGetMessage {198 checkMsgUnqMethod: string;199 checkMsgTrsMethod: string;200 checkMsgSysMethod: string;201}202203export interface IFungibleTokenDataType {204 value: number;205}206207export interface IChainLimits {208 collectionNumbersLimit: number;209 accountTokenOwnershipLimit: number;210 collectionsAdminsLimit: number;211 customDataLimit: number;212 nftSponsorTransferTimeout: number;213 fungibleSponsorTransferTimeout: number;214 refungibleSponsorTransferTimeout: number;215 //offchainSchemaLimit: number;216 //constOnChainSchemaLimit: number;217}218219export interface IReFungibleTokenDataType {220 owner: IReFungibleOwner[];221}222223export function uniqueEventMessage(events: EventRecord[]): IGetMessage {224 let checkMsgUnqMethod = '';225 let checkMsgTrsMethod = '';226 let checkMsgSysMethod = '';227 events.forEach(({event: {method, section}}) => {228 if (section === 'common') {229 checkMsgUnqMethod = method;230 } else if (section === 'treasury') {231 checkMsgTrsMethod = method;232 } else if (section === 'system') {233 checkMsgSysMethod = method;234 } else { return null; }235 });236 const result: IGetMessage = {237 checkMsgUnqMethod,238 checkMsgTrsMethod,239 checkMsgSysMethod,240 };241 return result;242}243244export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {245 const event = events.find(r => check(r.event));246 if (!event) return;247 return event.event as T;248}249250export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;251export function getGenericResult<T>(252 events: EventRecord[],253 expectSection: string,254 expectMethod: string,255 extractAction: (data: GenericEventData) => T256): GenericResult<T>;257258export function getGenericResult<T>(259 events: EventRecord[],260 expectSection?: string,261 expectMethod?: string,262 extractAction?: (data: GenericEventData) => T,263): GenericResult<T> {264 let success = false;265 let successData = null;266267 events.forEach(({event: {data, method, section}}) => {268 // console.log(` ${phase}: ${section}.${method}:: ${data}`);269 if (method === 'ExtrinsicSuccess') {270 success = true;271 } else if ((expectSection == section) && (expectMethod == method)) {272 successData = extractAction!(data as any);273 }274 });275276 const result: GenericResult<T> = {277 success,278 data: successData,279 };280 return result;281}282283export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {284 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));285 const result: CreateCollectionResult = {286 success: genericResult.success,287 collectionId: genericResult.data ?? 0,288 };289 return result;290}291292export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {293 const results: CreateItemResult[] = [];294 295 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {296 const collectionId = parseInt(data[0].toString(), 10);297 const itemId = parseInt(data[1].toString(), 10);298 const recipient = normalizeAccountId(data[2].toJSON() as any);299 const amount = parseInt(data[3].toString(), 10);300301 const itemRes: CreateItemResult = {302 success: true,303 collectionId,304 itemId,305 recipient,306 amount,307 };308309 results.push(itemRes);310 return results;311 });312313 if (!genericResult.success) return [];314 return results;315}316317export function getCreateItemResult(events: EventRecord[]): CreateItemResult {318 const genericResult = getGenericResult(events, 'common', 'ItemCreated', (data) => data.map(function(value) { return value.toJSON(); }));319 320 if (genericResult.data == null) 321 return {322 success: genericResult.success,323 collectionId: 0,324 itemId: 0,325 amount: 0,326 };327 else 328 return {329 success: genericResult.success,330 collectionId: genericResult.data[0] as number,331 itemId: genericResult.data[1] as number,332 recipient: normalizeAccountId(genericResult.data![2] as any),333 amount: genericResult.data[3] as number,334 };335}336337export function getDestroyItemsResult(events: EventRecord[]): DestroyItemResult[] {338 const results: DestroyItemResult[] = [];339 340 const genericResult = getGenericResult<DestroyItemResult[]>(events, 'common', 'ItemDestroyed', (data) => {341 const collectionId = parseInt(data[0].toString(), 10);342 const itemId = parseInt(data[1].toString(), 10);343 const owner = normalizeAccountId(data[2].toJSON() as any);344 const amount = parseInt(data[3].toString(), 10);345346 const itemRes: DestroyItemResult = {347 success: true,348 collectionId,349 itemId,350 owner,351 amount,352 };353354 results.push(itemRes);355 return results;356 });357358 if (!genericResult.success) return [];359 return results;360}361362export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {363 for (const {event} of events) {364 if (api.events.common.Transfer.is(event)) {365 const [collection, token, sender, recipient, value] = event.data;366 return {367 collectionId: collection.toNumber(),368 itemId: token.toNumber(),369 sender: normalizeAccountId(sender.toJSON() as any),370 recipient: normalizeAccountId(recipient.toJSON() as any),371 value: value.toBigInt(),372 };373 }374 }375 throw new Error('no transfer event');376}377378interface Nft {379 type: 'NFT';380}381382interface Fungible {383 type: 'Fungible';384 decimalPoints: number;385}386387interface ReFungible {388 type: 'ReFungible';389}390391export type CollectionMode = Nft | Fungible | ReFungible;392393export type Property = {394 key: any,395 value: any,396};397398type Permission = {399 mutable: boolean;400 collectionAdmin: boolean;401 tokenOwner: boolean;402}403404type PropertyPermission = {405 key: any;406 permission: Permission;407}408409export type CreateCollectionParams = {410 mode: CollectionMode,411 name: string,412 description: string,413 tokenPrefix: string,414 properties?: Array<Property>,415 propPerm?: Array<PropertyPermission>416};417418const defaultCreateCollectionParams: CreateCollectionParams = {419 description: 'description',420 mode: {type: 'NFT'},421 name: 'name',422 tokenPrefix: 'prefix',423};424425export async function426createCollection(427 api: ApiPromise,428 sender: IKeyringPair,429 params: Partial<CreateCollectionParams> = {},430): Promise<CreateCollectionResult> {431 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433 let modeprm = {};434 if (mode.type === 'NFT') {435 modeprm = {nft: null};436 } else if (mode.type === 'Fungible') {437 modeprm = {fungible: mode.decimalPoints};438 } else if (mode.type === 'ReFungible') {439 modeprm = {refungible: null};440 }441442 const tx = api.tx.unique.createCollectionEx({443 name: strToUTF16(name),444 description: strToUTF16(description),445 tokenPrefix: strToUTF16(tokenPrefix),446 mode: modeprm as any,447 });448 const events = await executeTransaction(api, sender, tx);449 return getCreateCollectionResult(events);450}451452export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {453 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};454455 let collectionId = 0;456 await usingApi(async (api, privateKeyWrapper) => {457 // Get number of collections before the transaction458 const collectionCountBefore = await getCreatedCollectionCount(api);459460 // Run the CreateCollection transaction461 const alicePrivateKey = privateKeyWrapper('//Alice');462463 const result = await createCollection(api, alicePrivateKey, params);464465 // Get number of collections after the transaction466 const collectionCountAfter = await getCreatedCollectionCount(api);467468 // Get the collection469 const collection = await queryCollectionExpectSuccess(api, result.collectionId);470471 // What to expect472 // tslint:disable-next-line:no-unused-expression473 expect(result.success).to.be.true;474 expect(result.collectionId).to.be.equal(collectionCountAfter);475 // tslint:disable-next-line:no-unused-expression476 expect(collection).to.be.not.null;477 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');478 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));479 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);480 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);481 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);482483 collectionId = result.collectionId;484 });485486 return collectionId;487}488489export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {490 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};491492 let collectionId = 0;493 await usingApi(async (api, privateKeyWrapper) => {494 // Get number of collections before the transaction495 const collectionCountBefore = await getCreatedCollectionCount(api);496497 // Run the CreateCollection transaction498 const alicePrivateKey = privateKeyWrapper('//Alice');499500 let modeprm = {};501 if (mode.type === 'NFT') {502 modeprm = {nft: null};503 } else if (mode.type === 'Fungible') {504 modeprm = {fungible: mode.decimalPoints};505 } else if (mode.type === 'ReFungible') {506 modeprm = {refungible: null};507 }508509 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});510 const events = await submitTransactionAsync(alicePrivateKey, tx);511 const result = getCreateCollectionResult(events);512513 // Get number of collections after the transaction514 const collectionCountAfter = await getCreatedCollectionCount(api);515516 // Get the collection517 const collection = await queryCollectionExpectSuccess(api, result.collectionId);518519 // What to expect520 // tslint:disable-next-line:no-unused-expression521 expect(result.success).to.be.true;522 expect(result.collectionId).to.be.equal(collectionCountAfter);523 // tslint:disable-next-line:no-unused-expression524 expect(collection).to.be.not.null;525 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');526 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));527 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);528 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);529 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);530531532 collectionId = result.collectionId;533 });534535 return collectionId;536}537538export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {539 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};540541 await usingApi(async (api, privateKeyWrapper) => {542 // Get number of collections before the transaction543 const collectionCountBefore = await getCreatedCollectionCount(api);544545 // Run the CreateCollection transaction546 const alicePrivateKey = privateKeyWrapper('//Alice');547548 let modeprm = {};549 if (mode.type === 'NFT') {550 modeprm = {nft: null};551 } else if (mode.type === 'Fungible') {552 modeprm = {fungible: mode.decimalPoints};553 } else if (mode.type === 'ReFungible') {554 modeprm = {refungible: null};555 }556557 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});558 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;559560561 // Get number of collections after the transaction562 const collectionCountAfter = await getCreatedCollectionCount(api);563564 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');565 });566}567568export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {569 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};570571 let modeprm = {};572 if (mode.type === 'NFT') {573 modeprm = {nft: null};574 } else if (mode.type === 'Fungible') {575 modeprm = {fungible: mode.decimalPoints};576 } else if (mode.type === 'ReFungible') {577 modeprm = {refungible: null};578 }579580 await usingApi(async (api, privateKeyWrapper) => {581 // Get number of collections before the transaction582 const collectionCountBefore = await getCreatedCollectionCount(api);583584 // Run the CreateCollection transaction585 const alicePrivateKey = privateKeyWrapper('//Alice');586 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});587 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;588589 // Get number of collections after the transaction590 const collectionCountAfter = await getCreatedCollectionCount(api);591592 // What to expect593 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');594 });595}596597export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {598 let bal = 0n;599 let unused;600 do {601 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;602 unused = privateKeyWrapper(`//${randomSeed}`);603 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();604 } while (bal !== 0n);605 return unused;606}607608export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {609 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();610}611612export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {613 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));614}615616export async function findNotExistingCollection(api: ApiPromise): Promise<number> {617 const totalNumber = await getCreatedCollectionCount(api);618 const newCollection: number = totalNumber + 1;619 return newCollection;620}621622function getDestroyResult(events: EventRecord[]): boolean {623 let success = false;624 events.forEach(({event: {method}}) => {625 if (method == 'ExtrinsicSuccess') {626 success = true;627 }628 });629 return success;630}631632export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {633 await usingApi(async (api, privateKeyWrapper) => {634 // Run the DestroyCollection transaction635 const alicePrivateKey = privateKeyWrapper(senderSeed);636 const tx = api.tx.unique.destroyCollection(collectionId);637 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638 });639}640641export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {642 await usingApi(async (api, privateKeyWrapper) => {643 // Run the DestroyCollection transaction644 const alicePrivateKey = privateKeyWrapper(senderSeed);645 const tx = api.tx.unique.destroyCollection(collectionId);646 const events = await submitTransactionAsync(alicePrivateKey, tx);647 const result = getDestroyResult(events);648 expect(result).to.be.true;649650 // What to expect651 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;652 });653}654655export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {656 await usingApi(async (api) => {657 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);658 const events = await submitTransactionAsync(sender, tx);659 const result = getGenericResult(events);660661 expect(result.success).to.be.true;662 });663}664665export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {666 await usingApi(async(api) => {667 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673};674675export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {676 await usingApi(async (api) => {677 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);678 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 const result = getGenericResult(events);680681 expect(result.success).to.be.false;682 });683}684685export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {686 await usingApi(async (api, privateKeyWrapper) => {687688 // Run the transaction689 const senderPrivateKey = privateKeyWrapper(sender);690 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);691 const events = await submitTransactionAsync(senderPrivateKey, tx);692 const result = getGenericResult(events);693694 // Get the collection695 const collection = await queryCollectionExpectSuccess(api, collectionId);696697 // What to expect698 expect(result.success).to.be.true;699 expect(collection.sponsorship.toJSON()).to.deep.equal({700 unconfirmed: sponsor,701 });702 });703}704705export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {706 await usingApi(async (api, privateKeyWrapper) => {707708 // Run the transaction709 const alicePrivateKey = privateKeyWrapper(sender);710 const tx = api.tx.unique.removeCollectionSponsor(collectionId);711 const events = await submitTransactionAsync(alicePrivateKey, tx);712 const result = getGenericResult(events);713714 // Get the collection715 const collection = await queryCollectionExpectSuccess(api, collectionId);716717 // What to expect718 expect(result.success).to.be.true;719 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});720 });721}722723export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {724 await usingApi(async (api, privateKeyWrapper) => {725726 // Run the transaction727 const alicePrivateKey = privateKeyWrapper(senderSeed);728 const tx = api.tx.unique.removeCollectionSponsor(collectionId);729 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;730 });731}732733export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {734 await usingApi(async (api, privateKeyWrapper) => {735736 // Run the transaction737 const alicePrivateKey = privateKeyWrapper(senderSeed);738 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);739 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;740 });741}742743export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {744 await usingApi(async (api, privateKeyWrapper) => {745746 // Run the transaction747 const sender = privateKeyWrapper(senderSeed);748 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);749 });750}751752export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {753 await usingApi(async (api, privateKeyWrapper) => {754755 // Run the transaction756 const tx = api.tx.unique.confirmSponsorship(collectionId);757 const events = await submitTransactionAsync(sender, tx);758 const result = getGenericResult(events);759760 // Get the collection761 const collection = await queryCollectionExpectSuccess(api, collectionId);762763 // What to expect764 expect(result.success).to.be.true;765 expect(collection.sponsorship.toJSON()).to.be.deep.equal({766 confirmed: sender.address,767 });768 });769}770771772export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {773 await usingApi(async (api, privateKeyWrapper) => {774775 // Run the transaction776 const sender = privateKeyWrapper(senderSeed);777 const tx = api.tx.unique.confirmSponsorship(collectionId);778 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;779 });780}781782export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {783 await usingApi(async (api) => {784 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);785 const events = await submitTransactionAsync(sender, tx);786 const result = getGenericResult(events);787788 expect(result.success).to.be.true;789 });790}791792export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {793 await usingApi(async (api) => {794 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);795 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;796 const result = getGenericResult(events);797798 expect(result.success).to.be.false;799 });800}801802export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {803804 await usingApi(async (api) => {805806 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);807 const events = await submitTransactionAsync(sender, tx);808 const result = getGenericResult(events);809810 expect(result.success).to.be.true;811 });812}813814export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {815816 await usingApi(async (api) => {817818 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);819 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;820 const result = getGenericResult(events);821822 expect(result.success).to.be.false;823 });824}825826export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {827 await usingApi(async (api) => {828 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);829 const events = await submitTransactionAsync(sender, tx);830 const result = getGenericResult(events);831832 expect(result.success).to.be.true;833 });834}835836export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {837 await usingApi(async (api) => {838 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);839 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;840 const result = getGenericResult(events);841842 expect(result.success).to.be.false;843 });844}845846export async function getNextSponsored(847 api: ApiPromise,848 collectionId: number,849 account: string | CrossAccountId,850 tokenId: number,851): Promise<number> {852 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));853}854855export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {856 await usingApi(async (api) => {857 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);858 const events = await submitTransactionAsync(sender, tx);859 const result = getGenericResult(events);860861 expect(result.success).to.be.true;862 });863}864865export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {866 let allowlisted = false;867 await usingApi(async (api) => {868 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;869 });870 return allowlisted;871}872873export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {874 await usingApi(async (api) => {875 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());876 const events = await submitTransactionAsync(sender, tx);877 const result = getGenericResult(events);878879 expect(result.success).to.be.true;880 });881}882883export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {884 await usingApi(async (api) => {885 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());886 const events = await submitTransactionAsync(sender, tx);887 const result = getGenericResult(events);888889 expect(result.success).to.be.true;890 });891}892893export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {894 await usingApi(async (api) => {895 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());896 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;897 const result = getGenericResult(events);898899 expect(result.success).to.be.false;900 });901}902903export interface CreateFungibleData {904 readonly Value: bigint;905}906907export interface CreateReFungibleData { }908export interface CreateNftData { }909910export type CreateItemData = {911 NFT: CreateNftData;912} | {913 Fungible: CreateFungibleData;914} | {915 ReFungible: CreateReFungibleData;916};917918export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {919 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);920 const events = await submitTransactionAsync(sender, tx);921 return getGenericResult(events).success;922}923924export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {925 await usingApi(async (api) => {926 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);927 // if burning token by admin - use adminButnItemExpectSuccess928 expect(balanceBefore >= BigInt(value)).to.be.true;929930 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;931932 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);933 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);934 });935}936937export async function burnItemExpectFailure(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {938 await usingApi(async (api) => {939 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);940941 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;942 const result = getCreateCollectionResult(events);943 // tslint:disable-next-line:no-unused-expression944 expect(result.success).to.be.false;945 });946}947948export async function burnFromExpectSuccess(sender: IKeyringPair, from: IKeyringPair | CrossAccountId, collectionId: number, tokenId: number, value: number | bigint = 1) {949 await usingApi(async (api) => {950 const tx = api.tx.unique.burnFrom(collectionId, normalizeAccountId(from), tokenId, value);951 const events = await submitTransactionAsync(sender, tx);952 return getGenericResult(events).success;953 });954}955956export async function957approve(958 api: ApiPromise,959 collectionId: number,960 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,961) {962 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);963 const events = await submitTransactionAsync(owner, approveUniqueTx);964 return getGenericResult(events).success;965}966967export async function968approveExpectSuccess(969 collectionId: number,970 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,971) {972 await usingApi(async (api: ApiPromise) => {973 const result = await approve(api, collectionId, tokenId, owner, approved, amount);974 expect(result).to.be.true;975976 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));977 });978}979980export async function adminApproveFromExpectSuccess(981 collectionId: number,982 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,983) {984 await usingApi(async (api: ApiPromise) => {985 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);986 const events = await submitTransactionAsync(admin, approveUniqueTx);987 const result = getGenericResult(events);988 expect(result.success).to.be.true;989990 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));991 });992}993994export async function995transferFrom(996 api: ApiPromise,997 collectionId: number,998 tokenId: number,999 accountApproved: IKeyringPair,1000 accountFrom: IKeyringPair | CrossAccountId,1001 accountTo: IKeyringPair | CrossAccountId,1002 value: number | bigint,1003) {1004 const from = normalizeAccountId(accountFrom);1005 const to = normalizeAccountId(accountTo);1006 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);1007 const events = await submitTransactionAsync(accountApproved, transferFromTx);1008 return getGenericResult(events).success;1009}10101011export async function1012transferFromExpectSuccess(1013 collectionId: number,1014 tokenId: number,1015 accountApproved: IKeyringPair,1016 accountFrom: IKeyringPair | CrossAccountId,1017 accountTo: IKeyringPair | CrossAccountId,1018 value: number | bigint = 1,1019 type = 'NFT',1020) {1021 await usingApi(async (api: ApiPromise) => {1022 const from = normalizeAccountId(accountFrom);1023 const to = normalizeAccountId(accountTo);1024 let balanceBefore = 0n;1025 if (type === 'Fungible' || type === 'ReFungible') {1026 balanceBefore = await getBalance(api, collectionId, to, tokenId);1027 }1028 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;1029 if (type === 'NFT') {1030 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1031 }1032 if (type === 'Fungible') {1033 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1034 if (JSON.stringify(to) !== JSON.stringify(from)) {1035 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1036 } else {1037 expect(balanceAfter).to.be.equal(balanceBefore);1038 }1039 }1040 if (type === 'ReFungible') {1041 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));1042 }1043 });1044}10451046export async function1047transferFromExpectFail(1048 collectionId: number,1049 tokenId: number,1050 accountApproved: IKeyringPair,1051 accountFrom: IKeyringPair,1052 accountTo: IKeyringPair,1053 value: number | bigint = 1,1054) {1055 await usingApi(async (api: ApiPromise) => {1056 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);1057 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;1058 const result = getCreateCollectionResult(events);1059 // tslint:disable-next-line:no-unused-expression1060 expect(result.success).to.be.false;1061 });1062}10631064/* eslint no-async-promise-executor: "off" */1065export async function getBlockNumber(api: ApiPromise): Promise<number> {1066 return new Promise<number>(async (resolve) => {1067 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {1068 unsubscribe();1069 resolve(head.number.toNumber());1070 });1071 });1072}10731074export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {1075 await usingApi(async (api) => {1076 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));1077 const events = await submitTransactionAsync(sender, changeAdminTx);1078 const result = getCreateCollectionResult(events);1079 expect(result.success).to.be.true;1080 });1081}10821083export async function adminApproveFromExpectFail(1084 collectionId: number,1085 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,1086) {1087 await usingApi(async (api: ApiPromise) => {1088 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);1089 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;1090 const result = getGenericResult(events);1091 expect(result.success).to.be.false;1092 });1093}10941095export async function1096getFreeBalance(account: IKeyringPair): Promise<bigint> {1097 let balance = 0n;1098 await usingApi(async (api) => {1099 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());1100 });11011102 return balance;1103}11041105export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {1106 const tx = api.tx.balances.transfer(target, amount);1107 const events = await submitTransactionAsync(source, tx);1108 const result = getGenericResult(events);1109 expect(result.success).to.be.true;1110}11111112export async function1113scheduleExpectSuccess(1114 operationTx: any,1115 sender: IKeyringPair,1116 blockSchedule: number,1117 scheduledId: string,1118 period = 1,1119 repetitions = 1,1120) {1121 await usingApi(async (api: ApiPromise) => {1122 const blockNumber: number | undefined = await getBlockNumber(api);1123 const expectedBlockNumber = blockNumber + blockSchedule;11241125 expect(blockNumber).to.be.greaterThan(0);1126 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1127 scheduledId,1128 expectedBlockNumber, 1129 repetitions > 1 ? [period, repetitions] : null, 1130 0, 1131 {Value: operationTx as any},1132 );11331134 const events = await submitTransactionAsync(sender, scheduleTx);1135 expect(getGenericResult(events).success).to.be.true;1136 });1137}11381139export async function1140scheduleExpectFailure(1141 operationTx: any,1142 sender: IKeyringPair,1143 blockSchedule: number,1144 scheduledId: string,1145 period = 1,1146 repetitions = 1,1147) {1148 await usingApi(async (api: ApiPromise) => {1149 const blockNumber: number | undefined = await getBlockNumber(api);1150 const expectedBlockNumber = blockNumber + blockSchedule;11511152 expect(blockNumber).to.be.greaterThan(0);1153 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1154 scheduledId,1155 expectedBlockNumber, 1156 repetitions <= 1 ? null : [period, repetitions], 1157 0, 1158 {Value: operationTx as any},1159 );11601161 //const events = 1162 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1163 //expect(getGenericResult(events).success).to.be.false;1164 });1165}11661167export async function1168scheduleTransferAndWaitExpectSuccess(1169 collectionId: number,1170 tokenId: number,1171 sender: IKeyringPair,1172 recipient: IKeyringPair,1173 value: number | bigint = 1,1174 blockSchedule: number,1175 scheduledId: string,1176) {1177 await usingApi(async (api: ApiPromise) => {1178 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);11791180 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();11811182 // sleep for n + 1 blocks1183 await waitNewBlocks(blockSchedule + 1);11841185 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();11861187 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1188 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1189 });1190}11911192export async function1193scheduleTransferExpectSuccess(1194 collectionId: number,1195 tokenId: number,1196 sender: IKeyringPair,1197 recipient: IKeyringPair,1198 value: number | bigint = 1,1199 blockSchedule: number,1200 scheduledId: string,1201) {1202 await usingApi(async (api: ApiPromise) => {1203 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);12041205 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);12061207 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1208 });1209}12101211export async function1212scheduleTransferFundsPeriodicExpectSuccess(1213 amount: bigint,1214 sender: IKeyringPair,1215 recipient: IKeyringPair,1216 blockSchedule: number,1217 scheduledId: string,1218 period: number,1219 repetitions: number,1220) {1221 await usingApi(async (api: ApiPromise) => {1222 const transferTx = api.tx.balances.transfer(recipient.address, amount);12231224 const balanceBefore = await getFreeBalance(recipient);1225 1226 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);12271228 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1229 });1230}12311232export async function1233transfer(1234 api: ApiPromise,1235 collectionId: number,1236 tokenId: number,1237 sender: IKeyringPair,1238 recipient: IKeyringPair | CrossAccountId,1239 value: number | bigint,1240) : Promise<boolean> {1241 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1242 const events = await executeTransaction(api, sender, transferTx);1243 return getGenericResult(events).success;1244}12451246export async function1247transferExpectSuccess(1248 collectionId: number,1249 tokenId: number,1250 sender: IKeyringPair,1251 recipient: IKeyringPair | CrossAccountId,1252 value: number | bigint = 1,1253 type = 'NFT',1254) {1255 await usingApi(async (api: ApiPromise) => {1256 const from = normalizeAccountId(sender);1257 const to = normalizeAccountId(recipient);12581259 let balanceBefore = 0n;1260 if (type === 'Fungible' || type === 'ReFungible') {1261 balanceBefore = await getBalance(api, collectionId, to, tokenId);1262 }12631264 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1265 const events = await executeTransaction(api, sender, transferTx);1266 const result = getTransferResult(api, events);12671268 expect(result.collectionId).to.be.equal(collectionId);1269 expect(result.itemId).to.be.equal(tokenId);1270 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1271 expect(result.recipient).to.be.deep.equal(to);1272 expect(result.value).to.be.equal(BigInt(value));12731274 if (type === 'NFT') {1275 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1276 }1277 if (type === 'Fungible' || type === 'ReFungible') {1278 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1279 if (JSON.stringify(to) !== JSON.stringify(from)) {1280 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1281 } else {1282 expect(balanceAfter).to.be.equal(balanceBefore);1283 }1284 }1285 });1286}12871288export async function1289transferExpectFailure(1290 collectionId: number,1291 tokenId: number,1292 sender: IKeyringPair,1293 recipient: IKeyringPair | CrossAccountId,1294 value: number | bigint = 1,1295) {1296 await usingApi(async (api: ApiPromise) => {1297 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1298 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1299 const result = getGenericResult(events);1300 // if (events && Array.isArray(events)) {1301 // const result = getCreateCollectionResult(events);1302 // tslint:disable-next-line:no-unused-expression1303 expect(result.success).to.be.false;1304 //}1305 });1306}13071308export async function1309approveExpectFail(1310 collectionId: number,1311 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1312) {1313 await usingApi(async (api: ApiPromise) => {1314 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1315 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1316 const result = getCreateCollectionResult(events);1317 // tslint:disable-next-line:no-unused-expression1318 expect(result.success).to.be.false;1319 });1320}13211322export async function getBalance(1323 api: ApiPromise,1324 collectionId: number,1325 owner: string | CrossAccountId | IKeyringPair,1326 token: number,1327): Promise<bigint> {1328 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1329}1330export async function getTokenOwner(1331 api: ApiPromise,1332 collectionId: number,1333 token: number,1334): Promise<CrossAccountId> {1335 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1336 if (owner == null) throw new Error('owner == null');1337 return normalizeAccountId(owner);1338}1339export async function getTopmostTokenOwner(1340 api: ApiPromise,1341 collectionId: number,1342 token: number,1343): Promise<CrossAccountId> {1344 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1345 if (owner == null) throw new Error('owner == null');1346 return normalizeAccountId(owner);1347}1348export async function getTokenChildren(1349 api: ApiPromise,1350 collectionId: number,1351 tokenId: number,1352): Promise<UpDataStructsTokenChild[]> {1353 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1354}1355export async function isTokenExists(1356 api: ApiPromise,1357 collectionId: number,1358 token: number,1359): Promise<boolean> {1360 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1361}1362export async function getLastTokenId(1363 api: ApiPromise,1364 collectionId: number,1365): Promise<number> {1366 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1367}1368export async function getAdminList(1369 api: ApiPromise,1370 collectionId: number,1371): Promise<string[]> {1372 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1373}1374export async function getTokenProperties(1375 api: ApiPromise,1376 collectionId: number,1377 tokenId: number,1378 propertyKeys: string[],1379): Promise<UpDataStructsProperty[]> {1380 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1381}13821383export async function createFungibleItemExpectSuccess(1384 sender: IKeyringPair,1385 collectionId: number,1386 data: CreateFungibleData,1387 owner: CrossAccountId | string = sender.address,1388) {1389 return await usingApi(async (api) => {1390 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});13911392 const events = await submitTransactionAsync(sender, tx);1393 const result = getCreateItemResult(events);13941395 expect(result.success).to.be.true;1396 return result.itemId;1397 });1398}13991400export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1401 await usingApi(async (api) => {1402 const to = normalizeAccountId(owner);1403 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14041405 const events = await submitTransactionAsync(sender, tx);1406 expect(getGenericResult(events).success).to.be.true;1407 });1408}14091410export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1411 await usingApi(async (api) => {1412 const to = normalizeAccountId(owner);1413 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);14141415 const events = await submitTransactionAsync(sender, tx);1416 const result = getCreateItemsResult(events);14171418 for (const res of result) {1419 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1420 }1421 });1422}14231424export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1425 await usingApi(async (api) => {1426 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);14271428 const events = await submitTransactionAsync(sender, tx);1429 const result = getCreateItemsResult(events);14301431 for (const res of result) {1432 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1433 }1434 });1435}14361437export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1438 let newItemId = 0;1439 await usingApi(async (api) => {1440 const to = normalizeAccountId(owner);1441 const itemCountBefore = await getLastTokenId(api, collectionId);1442 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);14431444 let tx;1445 if (createMode === 'Fungible') {1446 const createData = {fungible: {value: 10}};1447 tx = api.tx.unique.createItem(collectionId, to, createData as any);1448 } else if (createMode === 'ReFungible') {1449 const createData = {refungible: {pieces: 100}};1450 tx = api.tx.unique.createItem(collectionId, to, createData as any);1451 } else {1452 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1453 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1454 }14551456 const events = await submitTransactionAsync(sender, tx);1457 const result = getCreateItemResult(events);14581459 const itemCountAfter = await getLastTokenId(api, collectionId);1460 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14611462 if (createMode === 'NFT') {1463 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1464 }14651466 // What to expect1467 // tslint:disable-next-line:no-unused-expression1468 expect(result.success).to.be.true;1469 if (createMode === 'Fungible') {1470 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1471 } else {1472 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1473 }1474 expect(collectionId).to.be.equal(result.collectionId);1475 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1476 expect(to).to.be.deep.equal(result.recipient);1477 newItemId = result.itemId;1478 });1479 return newItemId;1480}14811482export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1483 await usingApi(async (api) => {14841485 let tx;1486 if (createMode === 'NFT') {1487 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}}) as UpDataStructsCreateItemData;1488 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1489 } else {1490 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1491 }149214931494 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1495 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1496 const result = getCreateItemResult(events);14971498 expect(result.success).to.be.false;1499 });1500}15011502export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1503 let newItemId = 0;1504 await usingApi(async (api) => {1505 const to = normalizeAccountId(owner);1506 const itemCountBefore = await getLastTokenId(api, collectionId);1507 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);15081509 let tx;1510 if (createMode === 'Fungible') {1511 const createData = {fungible: {value: 10}};1512 tx = api.tx.unique.createItem(collectionId, to, createData as any);1513 } else if (createMode === 'ReFungible') {1514 const createData = {refungible: {pieces: 100}};1515 tx = api.tx.unique.createItem(collectionId, to, createData as any);1516 } else {1517 const createData = {nft: {}};1518 tx = api.tx.unique.createItem(collectionId, to, createData as any);1519 }15201521 const events = await executeTransaction(api, sender, tx);1522 const result = getCreateItemResult(events);15231524 const itemCountAfter = await getLastTokenId(api, collectionId);1525 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);15261527 // What to expect1528 // tslint:disable-next-line:no-unused-expression1529 expect(result.success).to.be.true;1530 if (createMode === 'Fungible') {1531 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1532 } else {1533 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1534 }1535 expect(collectionId).to.be.equal(result.collectionId);1536 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1537 expect(to).to.be.deep.equal(result.recipient);1538 newItemId = result.itemId;1539 });1540 return newItemId;1541}15421543export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1544 const createData = {refungible: {pieces: amount}};1545 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);15461547 const events = await submitTransactionAsync(sender, tx);1548 return getCreateItemResult(events);1549}15501551export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1552 await usingApi(async (api) => {1553 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);15541555 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1556 const result = getCreateItemResult(events);15571558 expect(result.success).to.be.false;1559 });1560}15611562export async function setPublicAccessModeExpectSuccess(1563 sender: IKeyringPair, collectionId: number,1564 accessMode: 'Normal' | 'AllowList',1565) {1566 await usingApi(async (api) => {15671568 // Run the transaction1569 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1570 const events = await submitTransactionAsync(sender, tx);1571 const result = getGenericResult(events);15721573 // Get the collection1574 const collection = await queryCollectionExpectSuccess(api, collectionId);15751576 // What to expect1577 // tslint:disable-next-line:no-unused-expression1578 expect(result.success).to.be.true;1579 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1580 });1581}15821583export async function setPublicAccessModeExpectFail(1584 sender: IKeyringPair, collectionId: number,1585 accessMode: 'Normal' | 'AllowList',1586) {1587 await usingApi(async (api) => {15881589 // Run the transaction1590 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1591 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1592 const result = getGenericResult(events);15931594 // What to expect1595 // tslint:disable-next-line:no-unused-expression1596 expect(result.success).to.be.false;1597 });1598}15991600export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1601 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1602}16031604export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1605 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1606}16071608export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1609 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1610}16111612export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1613 await usingApi(async (api) => {16141615 // Run the transaction1616 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1617 const events = await submitTransactionAsync(sender, tx);1618 const result = getGenericResult(events);1619 expect(result.success).to.be.true;16201621 // Get the collection1622 const collection = await queryCollectionExpectSuccess(api, collectionId);16231624 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1625 });1626}16271628export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1629 await setMintPermissionExpectSuccess(sender, collectionId, true);1630}16311632export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1633 await usingApi(async (api) => {1634 // Run the transaction1635 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1636 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1637 const result = getCreateCollectionResult(events);1638 // tslint:disable-next-line:no-unused-expression1639 expect(result.success).to.be.false;1640 });1641}16421643export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1644 await usingApi(async (api) => {1645 // Run the transaction1646 const tx = api.tx.unique.setChainLimits(limits);1647 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1648 const result = getCreateCollectionResult(events);1649 // tslint:disable-next-line:no-unused-expression1650 expect(result.success).to.be.false;1651 });1652}16531654export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId | IKeyringPair) {1655 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1656}16571658export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1659 await usingApi(async (api) => {1660 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;16611662 // Run the transaction1663 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1664 const events = await submitTransactionAsync(sender, tx);1665 const result = getGenericResult(events);1666 expect(result.success).to.be.true;16671668 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1669 });1670}16711672export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1673 await usingApi(async (api) => {16741675 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;16761677 // Run the transaction1678 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1679 const events = await submitTransactionAsync(sender, tx);1680 const result = getGenericResult(events);1681 expect(result.success).to.be.true;16821683 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1684 });1685}16861687export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1688 await usingApi(async (api) => {16891690 // Run the transaction1691 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1692 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1693 const result = getGenericResult(events);16941695 // What to expect1696 // tslint:disable-next-line:no-unused-expression1697 expect(result.success).to.be.false;1698 });1699}17001701export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1702 await usingApi(async (api) => {1703 // Run the transaction1704 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1705 const events = await submitTransactionAsync(sender, tx);1706 const result = getGenericResult(events);17071708 // What to expect1709 // tslint:disable-next-line:no-unused-expression1710 expect(result.success).to.be.true;1711 });1712}17131714export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1715 await usingApi(async (api) => {1716 // Run the transaction1717 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1718 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1719 const result = getGenericResult(events);17201721 // What to expect1722 // tslint:disable-next-line:no-unused-expression1723 expect(result.success).to.be.false;1724 });1725}17261727export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1728 : Promise<UpDataStructsRpcCollection | null> => {1729 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1730};17311732export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1733 // set global object - collectionsCount1734 return (await api.rpc.unique.collectionStats()).created.toNumber();1735};17361737export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1738 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1739}17401741export async function waitNewBlocks(blocksCount = 1): Promise<void> {1742 await usingApi(async (api) => {1743 const promise = new Promise<void>(async (resolve) => {1744 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1745 if (blocksCount > 0) {1746 blocksCount--;1747 } else {1748 unsubscribe();1749 resolve();1750 }1751 });1752 });1753 return promise;1754 });1755}17561757export async function repartitionRFT(1758 api: ApiPromise,1759 collectionId: number,1760 sender: IKeyringPair,1761 tokenId: number,1762 amount: bigint,1763): Promise<boolean> {1764 const tx = api.tx.unique.repartition(collectionId, tokenId, amount);1765 const events = await submitTransactionAsync(sender, tx);1766 const result = getGenericResult(events);17671768 return result.success;1769}17701771export async function itApi(name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any, opts: { only?: boolean, skip?: boolean } = {}) {1772 let i: any = it;1773 if (opts.only) i = i.only;1774 else if (opts.skip) i = i.skip;1775 i(name, async () => {1776 await usingApi(async (api, privateKeyWrapper) => {1777 await cb({api, privateKeyWrapper});1778 });1779 });1780}17811782itApi.only = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {only: true});1783itApi.skip = (name: string, cb: (apis: { api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair }) => any) => itApi(name, cb, {skip: true});178417851786export async function expectSubstrateEventsAtBlock(api: ApiPromise, blockNumber: AnyNumber | BlockNumber, section: string, methods: string[], dryRun = false) {1787 const blockHash = await api.rpc.chain.getBlockHash(blockNumber);1788 const subEvents = (await api.query.system.events.at(blockHash))1789 .filter(x => x.event.section === section)1790 .map((x) => x.toHuman());1791 const events = methods.map((m) => {1792 return {1793 event: {1794 method: m,1795 section,1796 },1797 };1798 });1799 if (!dryRun) {1800 expect(subEvents).to.be.like(events);1801 }1802 return subEvents;1803}tests/src/util/playgrounds/unique.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -730,6 +730,18 @@
}
/**
+ * Check if user is in allow list.
+ *
+ * @param collectionId ID of collection
+ * @param user Account to check
+ * @example await getAdmins(1)
+ * @returns is user in allow list
+ */
+ async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {
+ return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();
+ }
+
+ /**
* Adds an address to allow list
* @param signer keyring of signer
* @param collectionId ID of collection