git.delta.rocks / unique-network / refs/commits / 02783a223963

difftreelog

Merge pull request #336 from UniqueNetwork/feature/CORE-325

kozyrevdev2022-04-21parents: #23e7e86 #447d08b.patch.diff
in: master
Feature/core-325

5 files changed

modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -14,13 +14,14 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
+extern crate alloc;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
 };
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
 use frame_support::BoundedVec;
-use up_data_structs::TokenId;
+use up_data_structs::{TokenId, SchemaVersion};
 use pallet_evm_coder_substrate::dispatch_to_evm;
 use sp_core::{H160, U256};
 use sp_std::{vec::Vec, vec};
@@ -35,6 +36,15 @@
 	SelfWeightOf, weights::WeightInfo,
 };
 
+fn error_unsupported_schema_version() -> Error {
+	alloc::format!(
+		"Unsupported schema version! Support only {:?}",
+		SchemaVersion::ImageURL
+	)
+	.as_str()
+	.into()
+}
+
 #[derive(ToLog)]
 pub enum ERC721Events {
 	Transfer {
@@ -76,6 +86,7 @@
 			.map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
 			.collect::<string>())
 	}
+
 	fn symbol(&self) -> Result<string> {
 		Ok(string::from_utf8_lossy(&self.token_prefix).into())
 	}
@@ -83,6 +94,10 @@
 	/// Returns token's const_metadata
 	#[solidity(rename_selector = "tokenURI")]
 	fn token_uri(&self, token_id: uint256) -> Result<string> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		self.consume_store_reads(1)?;
 		let token_id: u32 = token_id.try_into().map_err(|_| "token id overflow")?;
 		Ok(string::from_utf8_lossy(
@@ -270,6 +285,10 @@
 		token_id: uint256,
 		token_uri: string,
 	) -> Result<bool> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let token_id: u32 = token_id.try_into().map_err(|_| "amount overflow")?;
@@ -411,6 +430,10 @@
 		to: address,
 		tokens: Vec<(uint256, string)>,
 	) -> Result<bool> {
+		if !matches!(self.schema_version, SchemaVersion::ImageURL) {
+			return Err(error_unsupported_schema_version());
+		}
+
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
 		let mut expected_index = <TokensMinted<T>>::get(self.id)
modifiedtests/src/eth/collectionSponsoring.test.tsdiffbeforeafterboth
--- a/tests/src/eth/collectionSponsoring.test.ts
+++ b/tests/src/eth/collectionSponsoring.test.ts
@@ -1,19 +1,16 @@
 import privateKey from '../substrate/privateKey';
 import {addToAllowListExpectSuccess, confirmSponsorshipExpectSuccess, createCollectionExpectSuccess, enablePublicMintingExpectSuccess, setCollectionSponsorExpectSuccess} from '../util/helpers';
-import {itWeb3, transferBalanceToEth, subToEth, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';
+import {itWeb3, createEthAccount, collectionIdToAddress, GAS_ARGS, normalizeEvents} from './util/helpers';
 import nonFungibleAbi from './nonFungibleAbi.json';
 import {expect} from 'chai';
 
 describe('evm collection sponsoring', () => {
-  itWeb3('sponsors mint transactions', async ({api, web3}) => {
+  itWeb3('sponsors mint transactions', async ({web3}) => {
     const alice = privateKey('//Alice');
 
     const collection = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collection, alice.address);
     await confirmSponsorshipExpectSuccess(collection);
-
-    // Wouldn't be needed after CORE-300
-    await transferBalanceToEth(api, alice, subToEth(alice.address));
 
     const minter = createEthAccount(web3);
     expect(await web3.eth.getBalance(minter)).to.equal('0');
modifiedtests/src/eth/metadata.test.tsdiffbeforeafterboth
--- a/tests/src/eth/metadata.test.ts
+++ b/tests/src/eth/metadata.test.ts
@@ -16,8 +16,11 @@
 
 import {expect} from 'chai';
 import {createCollectionExpectSuccess} from '../util/helpers';
-import {collectionIdToAddress, createEthAccountWithBalance, GAS_ARGS, itWeb3} from './util/helpers';
+import {collectionIdToAddress, createEthAccount, createEthAccountWithBalance, GAS_ARGS, itWeb3, normalizeEvents} from './util/helpers';
 import fungibleMetadataAbi from './fungibleMetadataAbi.json';
+import privateKey from '../substrate/privateKey';
+import {submitTransactionAsync} from '../substrate/substrate-api';
+import nonFungibleAbi from './nonFungibleAbi.json';
 
 describe('Common metadata', () => {
   itWeb3('Returns collection name', async ({api, web3}) => {
@@ -62,4 +65,146 @@
 
     expect(+decimals).to.equal(6);
   });
-});
\ No newline at end of file
+});
+
+describe('Support ERC721Metadata', () => {
+  itWeb3('Check unsupport ERC721Metadata SchemaVersion::Unique', async ({web3, api}) => {
+    const collectionId = await createCollectionExpectSuccess({
+      mode: {type: 'NFT'},
+      schemaVersion: 'Unique',
+      name: 'some_name',
+      tokenPrefix: 'some_prefix',
+    });
+    const collection = await api.rpc.unique.collectionById(collectionId);
+    expect(collection.isSome).to.be.true;
+    expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('Unique');
+
+    const alice = privateKey('//Alice');
+
+    const caller = await createEthAccountWithBalance(api, web3);
+    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+    await submitTransactionAsync(alice, changeAdminTx);
+
+    const address = collectionIdToAddress(collectionId);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+
+    expect(await contract.methods.name().call()).to.be.eq('some_name');
+    expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
+
+    const receiver = createEthAccount(web3);
+    const nextTokenId = await contract.methods.nextTokenId().call();
+    expect(nextTokenId).to.be.equal('1');
+    await expect(contract.methods.mintWithTokenURI(
+      receiver,
+      nextTokenId,
+      'Test URI',
+    ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
+
+    await expect(contract.methods.mintBulkWithTokenURI(
+      receiver,
+      [
+        [nextTokenId, 'Test URI 0'],
+        [+nextTokenId + 1, 'Test URI 1'],
+        [+nextTokenId + 2, 'Test URI 2'],
+      ],
+    ).call({from: caller})).to.be.rejectedWith('Unsupported schema version! Support only ImageURL');
+  });
+
+  itWeb3('Check support ERC721Metadata for SchemaVersion::ImageURL', async ({web3, api}) => {
+    const collectionId = await createCollectionExpectSuccess({
+      mode: {type: 'NFT'},
+      name: 'some_name',
+      tokenPrefix: 'some_prefix',
+    });
+    const collection = await api.rpc.unique.collectionById(collectionId);
+    expect(collection.isSome).to.be.true;
+    expect(collection.unwrap().schemaVersion.toHuman()).to.be.eq('ImageURL');
+
+    const alice = privateKey('//Alice');
+
+    const caller = await createEthAccountWithBalance(api, web3);
+    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, {Ethereum: caller});
+    await submitTransactionAsync(alice, changeAdminTx);
+
+    const address = collectionIdToAddress(collectionId);
+    const contract = new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS});
+    
+    expect(await contract.methods.name().call()).to.be.eq('some_name');
+    expect(await contract.methods.symbol().call()).to.be.eq('some_prefix');
+
+    const receiver = createEthAccount(web3);
+    { // mintWithTokenURI
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('1');
+      const result = await contract.methods.mintWithTokenURI(
+        receiver,
+        nextTokenId,
+        'Test URI',
+      ).send({from: caller});
+      const events = normalizeEvents(result.events);
+  
+      expect(events).to.be.deep.equal([
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: nextTokenId,
+          },
+        },
+      ]);
+  
+      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI');
+    }
+
+    { // mintBulkWithTokenURI
+      const nextTokenId = await contract.methods.nextTokenId().call();
+      expect(nextTokenId).to.be.equal('2');
+      const result = await contract.methods.mintBulkWithTokenURI(
+        receiver,
+        [
+          [nextTokenId, 'Test URI 0'],
+          [+nextTokenId + 1, 'Test URI 1'],
+          [+nextTokenId + 2, 'Test URI 2'],
+        ],
+      ).send({from: caller});
+      const events = normalizeEvents(result.events);
+
+      expect(events).to.be.deep.equal([
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: nextTokenId,
+          },
+        },
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: String(+nextTokenId + 1),
+          },
+        },
+        {
+          address,
+          event: 'Transfer',
+          args: {
+            from: '0x0000000000000000000000000000000000000000',
+            to: receiver,
+            tokenId: String(+nextTokenId + 2),
+          },
+        },
+      ]);
+
+      expect(await contract.methods.tokenURI(nextTokenId).call()).to.be.equal('Test URI 0');
+      expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
+      expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
+    }
+  });
+});
+
modifiedtests/src/setConstOnChainSchema.test.tsdiffbeforeafterboth
--- a/tests/src/setConstOnChainSchema.test.ts
+++ b/tests/src/setConstOnChainSchema.test.ts
@@ -32,16 +32,16 @@
 
 let alice: IKeyringPair;
 let bob: IKeyringPair;
-let shema: any;
-let largeShema: any;
+let schema: any;
+let largeSchema: any;
 
 before(async () => {
   await usingApi(async () => {
     const keyring = new Keyring({type: 'sr25519'});
     alice = keyring.addFromUri('//Alice');
     bob = keyring.addFromUri('//Bob');
-    shema = '0x31';
-    largeShema = new Array(1024 * 1024 + 10).fill(0xff);
+    schema = '0x31';
+    largeSchema = new Array(1024 * 1024 + 10).fill(0xff);
   });
 });
 describe('Integration Test ext. setConstOnChainSchema()', () => {
@@ -51,8 +51,8 @@
       const collectionId = await createCollectionExpectSuccess();
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(alice, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(alice, setSchema);
     });
   });
 
@@ -62,18 +62,18 @@
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
       await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(bob, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(bob, setSchema);
     });
   });
 
   it('Checking collection data using the ConstOnChainSchema parameter', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await submitTransactionAsync(alice, setShema);
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await submitTransactionAsync(alice, setSchema);
       const collection = await queryCollectionExpectSuccess(api, collectionId);
-      expect(collection.constOnChainSchema.toString()).to.be.eq(shema);
+      expect(collection.constOnChainSchema.toString()).to.be.eq(schema);
     });
   });
 });
@@ -84,8 +84,8 @@
     await usingApi(async (api) => {
       // tslint:disable-next-line: radix
       const collectionId = await getCreatedCollectionCount(api) + 1;
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
@@ -93,16 +93,16 @@
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
       await destroyCollectionExpectSuccess(collectionId);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
   it('Set invalid data in schema (size too large:> 1MB)', async () => {
     await usingApi(async (api) => {
       const collectionId = await createCollectionExpectSuccess();
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, largeShema);
-      await expect(submitTransactionExpectFailAsync(alice, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, largeSchema);
+      await expect(submitTransactionExpectFailAsync(alice, setSchema)).to.be.rejected;
     });
   });
 
@@ -111,8 +111,8 @@
       const collectionId = await createCollectionExpectSuccess();
       const collection = await queryCollectionExpectSuccess(api, collectionId);
       expect(collection.owner.toString()).to.be.eq(alice.address);
-      const setShema = api.tx.unique.setConstOnChainSchema(collectionId, shema);
-      await expect(submitTransactionExpectFailAsync(bob, setShema)).to.be.rejected;
+      const setSchema = api.tx.unique.setConstOnChainSchema(collectionId, schema);
+      await expect(submitTransactionExpectFailAsync(bob, setSchema)).to.be.rejected;
     });
   });
 
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
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, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271};272273const defaultCreateCollectionParams: CreateCollectionParams = {274  description: 'description',275  mode: {type: 'NFT'},276  name: 'name',277  tokenPrefix: 'prefix',278};279280export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {281  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};282283  let collectionId = 0;284  await usingApi(async (api) => {285    // Get number of collections before the transaction286    const collectionCountBefore = await getCreatedCollectionCount(api);287288    // Run the CreateCollection transaction289    const alicePrivateKey = privateKey('//Alice');290291    let modeprm = {};292    if (mode.type === 'NFT') {293      modeprm = {nft: null};294    } else if (mode.type === 'Fungible') {295      modeprm = {fungible: mode.decimalPoints};296    } else if (mode.type === 'ReFungible') {297      modeprm = {refungible: null};298    }299300    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});301    const events = await submitTransactionAsync(alicePrivateKey, tx);302    const result = getCreateCollectionResult(events);303304    // Get number of collections after the transaction305    const collectionCountAfter = await getCreatedCollectionCount(api);306307    // Get the collection308    const collection = await queryCollectionExpectSuccess(api, result.collectionId);309310    // What to expect311    // tslint:disable-next-line:no-unused-expression312    expect(result.success).to.be.true;313    expect(result.collectionId).to.be.equal(collectionCountAfter);314    // tslint:disable-next-line:no-unused-expression315    expect(collection).to.be.not.null;316    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');317    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));318    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);319    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);320    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);321322    collectionId = result.collectionId;323  });324325  return collectionId;326}327328export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {329  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};330331  let modeprm = {};332  if (mode.type === 'NFT') {333    modeprm = {nft: null};334  } else if (mode.type === 'Fungible') {335    modeprm = {fungible: mode.decimalPoints};336  } else if (mode.type === 'ReFungible') {337    modeprm = {refungible: null};338  }339340  await usingApi(async (api) => {341    // Get number of collections before the transaction342    const collectionCountBefore = await getCreatedCollectionCount(api);343344    // Run the CreateCollection transaction345    const alicePrivateKey = privateKey('//Alice');346    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});347    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;348349    // Get number of collections after the transaction350    const collectionCountAfter = await getCreatedCollectionCount(api);351352    // What to expect353    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');354  });355}356357export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {358  let bal = 0n;359  let unused;360  do {361    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;362    const keyring = new Keyring({type: 'sr25519'});363    unused = keyring.addFromUri(`//${randomSeed}`);364    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();365  } while (bal !== 0n);366  return unused;367}368369export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {370  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();371}372373export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {374  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));375}376377export async function findNotExistingCollection(api: ApiPromise): Promise<number> {378  const totalNumber = await getCreatedCollectionCount(api);379  const newCollection: number = totalNumber + 1;380  return newCollection;381}382383function getDestroyResult(events: EventRecord[]): boolean {384  let success = false;385  events.forEach(({event: {method}}) => {386    if (method == 'ExtrinsicSuccess') {387      success = true;388    }389  });390  return success;391}392393export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {394  await usingApi(async (api) => {395    // Run the DestroyCollection transaction396    const alicePrivateKey = privateKey(senderSeed);397    const tx = api.tx.unique.destroyCollection(collectionId);398    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;399  });400}401402export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {403  await usingApi(async (api) => {404    // Run the DestroyCollection transaction405    const alicePrivateKey = privateKey(senderSeed);406    const tx = api.tx.unique.destroyCollection(collectionId);407    const events = await submitTransactionAsync(alicePrivateKey, tx);408    const result = getDestroyResult(events);409    expect(result).to.be.true;410411    // What to expect412    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;413  });414}415416export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {417  await usingApi(async (api) => {418    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);419    const events = await submitTransactionAsync(sender, tx);420    const result = getGenericResult(events);421422    expect(result.success).to.be.true;423  });424}425426export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {427  await usingApi(async (api) => {428    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);429    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;430    const result = getGenericResult(events);431432    expect(result.success).to.be.false;433  });434}435436export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {437  await usingApi(async (api) => {438439    // Run the transaction440    const senderPrivateKey = privateKey(sender);441    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);442    const events = await submitTransactionAsync(senderPrivateKey, tx);443    const result = getGenericResult(events);444445    // Get the collection446    const collection = await queryCollectionExpectSuccess(api, collectionId);447448    // What to expect449    expect(result.success).to.be.true;450    expect(collection.sponsorship.toJSON()).to.deep.equal({451      unconfirmed: sponsor,452    });453  });454}455456export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {457  await usingApi(async (api) => {458459    // Run the transaction460    const alicePrivateKey = privateKey(sender);461    const tx = api.tx.unique.removeCollectionSponsor(collectionId);462    const events = await submitTransactionAsync(alicePrivateKey, tx);463    const result = getGenericResult(events);464465    // Get the collection466    const collection = await queryCollectionExpectSuccess(api, collectionId);467468    // What to expect469    expect(result.success).to.be.true;470    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});471  });472}473474export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {475  await usingApi(async (api) => {476477    // Run the transaction478    const alicePrivateKey = privateKey(senderSeed);479    const tx = api.tx.unique.removeCollectionSponsor(collectionId);480    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;481  });482}483484export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {485  await usingApi(async (api) => {486487    // Run the transaction488    const alicePrivateKey = privateKey(senderSeed);489    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);490    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;491  });492}493494export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {495  await usingApi(async (api) => {496497    // Run the transaction498    const sender = privateKey(senderSeed);499    const tx = api.tx.unique.confirmSponsorship(collectionId);500    const events = await submitTransactionAsync(sender, tx);501    const result = getGenericResult(events);502503    // Get the collection504    const collection = await queryCollectionExpectSuccess(api, collectionId);505506    // What to expect507    expect(result.success).to.be.true;508    expect(collection.sponsorship.toJSON()).to.be.deep.equal({509      confirmed: sender.address,510    });511  });512}513514515export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {516  await usingApi(async (api) => {517518    // Run the transaction519    const sender = privateKey(senderSeed);520    const tx = api.tx.unique.confirmSponsorship(collectionId);521    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;522  });523}524525export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {526527  await usingApi(async (api) => {528    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {537538  await usingApi(async (api) => {539    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);540    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;541    const result = getGenericResult(events);542543    expect(result.success).to.be.false;544  });545}546547export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {548  await usingApi(async (api) => {549    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);550    const events = await submitTransactionAsync(sender, tx);551    const result = getGenericResult(events);552553    expect(result.success).to.be.true;554  });555}556557export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {558  await usingApi(async (api) => {559    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);560    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;561    const result = getGenericResult(events);562563    expect(result.success).to.be.false;564  });565}566567export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {568569  await usingApi(async (api) => {570571    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);572    const events = await submitTransactionAsync(sender, tx);573    const result = getGenericResult(events);574575    expect(result.success).to.be.true;576  });577}578579export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {580581  await usingApi(async (api) => {582583    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);584    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;585    const result = getGenericResult(events);586587    expect(result.success).to.be.false;588  });589}590591export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {592  await usingApi(async (api) => {593    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);594    const events = await submitTransactionAsync(sender, tx);595    const result = getGenericResult(events);596597    expect(result.success).to.be.true;598  });599}600601export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {602  await usingApi(async (api) => {603    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);604    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;605    const result = getGenericResult(events);606607    expect(result.success).to.be.false;608  });609}610611export async function getNextSponsored(612  api: ApiPromise,613  collectionId: number,614  account: string | CrossAccountId,615  tokenId: number,616): Promise<number> {617  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));618}619620export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {621  await usingApi(async (api) => {622    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);623    const events = await submitTransactionAsync(sender, tx);624    const result = getGenericResult(events);625626    expect(result.success).to.be.true;627  });628}629630export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {631  let allowlisted = false;632  await usingApi(async (api) => {633    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;634  });635  return allowlisted;636}637638export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());641    const events = await submitTransactionAsync(sender, tx);642    const result = getGenericResult(events);643644    expect(result.success).to.be.true;645  });646}647648export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());661    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662    const result = getGenericResult(events);663664    expect(result.success).to.be.false;665  });666}667668export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {669  await usingApi(async (api) => {670    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));671    const events = await submitTransactionAsync(sender, tx);672    const result = getGenericResult(events);673674    expect(result.success).to.be.true;675  });676}677678export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {679  await usingApi(async (api) => {680    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));681    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;682  });683}684685export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {686  await usingApi(async (api) => {687    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));688    const events = await submitTransactionAsync(sender, tx);689    const result = getGenericResult(events);690691    expect(result.success).to.be.true;692  });693}694695export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {696  await usingApi(async (api) => {697    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));698    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;699  });700}701702export interface CreateFungibleData {703  readonly Value: bigint;704}705706export interface CreateReFungibleData { }707export interface CreateNftData { }708709export type CreateItemData = {710  NFT: CreateNftData;711} | {712  Fungible: CreateFungibleData;713} | {714  ReFungible: CreateReFungibleData;715};716717export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {718  await usingApi(async (api) => {719    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);720    // if burning token by admin - use adminButnItemExpectSuccess721    expect(balanceBefore >= BigInt(value)).to.be.true;722723    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);724    const events = await submitTransactionAsync(sender, tx);725    const result = getGenericResult(events);726    expect(result.success).to.be.true;727728    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);729    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);730  });731}732733export async function734approveExpectSuccess(735  collectionId: number,736  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,737) {738  await usingApi(async (api: ApiPromise) => {739    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);740    const events = await submitTransactionAsync(owner, approveUniqueTx);741    const result = getGenericResult(events);742    expect(result.success).to.be.true;743744    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));745  });746}747748export async function adminApproveFromExpectSuccess(749  collectionId: number,750  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,751) {752  await usingApi(async (api: ApiPromise) => {753    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);754    const events = await submitTransactionAsync(admin, approveUniqueTx);755    const result = getGenericResult(events);756    expect(result.success).to.be.true;757758    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));759  });760}761762export async function763transferFromExpectSuccess(764  collectionId: number,765  tokenId: number,766  accountApproved: IKeyringPair,767  accountFrom: IKeyringPair | CrossAccountId,768  accountTo: IKeyringPair | CrossAccountId,769  value: number | bigint = 1,770  type = 'NFT',771) {772  await usingApi(async (api: ApiPromise) => {773    const from = normalizeAccountId(accountFrom);774    const to = normalizeAccountId(accountTo);775    let balanceBefore = 0n;776    if (type === 'Fungible') {777      balanceBefore = await getBalance(api, collectionId, to, tokenId);778    }779    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);780    const events = await submitTransactionAsync(accountApproved, transferFromTx);781    const result = getCreateItemResult(events);782    // tslint:disable-next-line:no-unused-expression783    expect(result.success).to.be.true;784    if (type === 'NFT') {785      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);786    }787    if (type === 'Fungible') {788      const balanceAfter = await getBalance(api, collectionId, to, tokenId);789      if (JSON.stringify(to) !== JSON.stringify(from)) {790        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));791      } else {792        expect(balanceAfter).to.be.equal(balanceBefore);793      }794    }795    if (type === 'ReFungible') {796      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));797    }798  });799}800801export async function802transferFromExpectFail(803  collectionId: number,804  tokenId: number,805  accountApproved: IKeyringPair,806  accountFrom: IKeyringPair,807  accountTo: IKeyringPair,808  value: number | bigint = 1,809) {810  await usingApi(async (api: ApiPromise) => {811    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);812    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;813    const result = getCreateCollectionResult(events);814    // tslint:disable-next-line:no-unused-expression815    expect(result.success).to.be.false;816  });817}818819/* eslint no-async-promise-executor: "off" */820async function getBlockNumber(api: ApiPromise): Promise<number> {821  return new Promise<number>(async (resolve) => {822    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {823      unsubscribe();824      resolve(head.number.toNumber());825    });826  });827}828829export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {830  await usingApi(async (api) => {831    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));832    const events = await submitTransactionAsync(sender, changeAdminTx);833    const result = getCreateCollectionResult(events);834    expect(result.success).to.be.true;835  });836}837838export async function839getFreeBalance(account: IKeyringPair): Promise<bigint> {840  let balance = 0n;841  await usingApi(async (api) => {842    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());843  });844845  return balance;846}847848export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {849  const tx = api.tx.balances.transfer(target, amount);850  const events = await submitTransactionAsync(source, tx);851  const result = getGenericResult(events);852  expect(result.success).to.be.true;853}854855export async function856scheduleTransferExpectSuccess(857  collectionId: number,858  tokenId: number,859  sender: IKeyringPair,860  recipient: IKeyringPair,861  value: number | bigint = 1,862  blockSchedule: number,863) {864  await usingApi(async (api: ApiPromise) => {865    const blockNumber: number | undefined = await getBlockNumber(api);866    const expectedBlockNumber = blockNumber + blockSchedule;867868    expect(blockNumber).to.be.greaterThan(0);869    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);870    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);871872    await submitTransactionAsync(sender, scheduleTx);873874    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();875876    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));877878    // sleep for 4 blocks879    await waitNewBlocks(blockSchedule + 1);880881    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();882883    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));884    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);885  });886}887888889export async function890transferExpectSuccess(891  collectionId: number,892  tokenId: number,893  sender: IKeyringPair,894  recipient: IKeyringPair | CrossAccountId,895  value: number | bigint = 1,896  type = 'NFT',897) {898  await usingApi(async (api: ApiPromise) => {899    const from = normalizeAccountId(sender);900    const to = normalizeAccountId(recipient);901902    let balanceBefore = 0n;903    if (type === 'Fungible') {904      balanceBefore = await getBalance(api, collectionId, to, tokenId);905    }906    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);907    const events = await submitTransactionAsync(sender, transferTx);908    const result = getTransferResult(events);909    // tslint:disable-next-line:no-unused-expression910    expect(result.success).to.be.true;911    expect(result.collectionId).to.be.equal(collectionId);912    expect(result.itemId).to.be.equal(tokenId);913    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));914    expect(result.recipient).to.be.deep.equal(to);915    expect(result.value).to.be.equal(BigInt(value));916    if (type === 'NFT') {917      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);918    }919    if (type === 'Fungible') {920      const balanceAfter = await getBalance(api, collectionId, to, tokenId);921      if (JSON.stringify(to) !== JSON.stringify(from)) {922        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));923      } else {924        expect(balanceAfter).to.be.equal(balanceBefore);925      }926    }927    if (type === 'ReFungible') {928      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;929    }930  });931}932933export async function934transferExpectFailure(935  collectionId: number,936  tokenId: number,937  sender: IKeyringPair,938  recipient: IKeyringPair,939  value: number | bigint = 1,940) {941  await usingApi(async (api: ApiPromise) => {942    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);943    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;944    const result = getGenericResult(events);945    // if (events && Array.isArray(events)) {946    //   const result = getCreateCollectionResult(events);947    // tslint:disable-next-line:no-unused-expression948    expect(result.success).to.be.false;949    //}950  });951}952953export async function954approveExpectFail(955  collectionId: number,956  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,957) {958  await usingApi(async (api: ApiPromise) => {959    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);960    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;961    const result = getCreateCollectionResult(events);962    // tslint:disable-next-line:no-unused-expression963    expect(result.success).to.be.false;964  });965}966967export async function getBalance(968  api: ApiPromise,969  collectionId: number,970  owner: string | CrossAccountId,971  token: number,972): Promise<bigint> {973  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();974}975export async function getTokenOwner(976  api: ApiPromise,977  collectionId: number,978  token: number,979): Promise<CrossAccountId> {980  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);981}982export async function isTokenExists(983  api: ApiPromise,984  collectionId: number,985  token: number,986): Promise<boolean> {987  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();988}989export async function getLastTokenId(990  api: ApiPromise,991  collectionId: number,992): Promise<number> {993  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();994}995export async function getAdminList(996  api: ApiPromise,997  collectionId: number,998): Promise<string[]> {999  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1000}1001export async function getVariableMetadata(1002  api: ApiPromise,1003  collectionId: number,1004  tokenId: number,1005): Promise<number[]> {1006  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1007}1008export async function getConstMetadata(1009  api: ApiPromise,1010  collectionId: number,1011  tokenId: number,1012): Promise<number[]> {1013  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1014}10151016export async function createFungibleItemExpectSuccess(1017  sender: IKeyringPair,1018  collectionId: number,1019  data: CreateFungibleData,1020  owner: CrossAccountId | string = sender.address,1021) {1022  return await usingApi(async (api) => {1023    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10241025    const events = await submitTransactionAsync(sender, tx);1026    const result = getCreateItemResult(events);10271028    expect(result.success).to.be.true;1029    return result.itemId;1030  });1031}10321033export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1034  let newItemId = 0;1035  await usingApi(async (api) => {1036    const to = normalizeAccountId(owner);1037    const itemCountBefore = await getLastTokenId(api, collectionId);1038    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10391040    let tx;1041    if (createMode === 'Fungible') {1042      const createData = {fungible: {value: 10}};1043      tx = api.tx.unique.createItem(collectionId, to, createData as any);1044    } else if (createMode === 'ReFungible') {1045      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1046      tx = api.tx.unique.createItem(collectionId, to, createData as any);1047    } else {1048      const createData = {nft: {const_data: [], variable_data: []}};1049      tx = api.tx.unique.createItem(collectionId, to, createData as any);1050    }10511052    const events = await submitTransactionAsync(sender, tx);1053    const result = getCreateItemResult(events);10541055    const itemCountAfter = await getLastTokenId(api, collectionId);1056    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10571058    // What to expect1059    // tslint:disable-next-line:no-unused-expression1060    expect(result.success).to.be.true;1061    if (createMode === 'Fungible') {1062      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1063    } else {1064      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1065    }1066    expect(collectionId).to.be.equal(result.collectionId);1067    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1068    expect(to).to.be.deep.equal(result.recipient);1069    newItemId = result.itemId;1070  });1071  return newItemId;1072}10731074export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1075  await usingApi(async (api) => {1076    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10771078    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079    const result = getCreateItemResult(events);10801081    expect(result.success).to.be.false;1082  });1083}10841085export async function setPublicAccessModeExpectSuccess(1086  sender: IKeyringPair, collectionId: number,1087  accessMode: 'Normal' | 'AllowList',1088) {1089  await usingApi(async (api) => {10901091    // Run the transaction1092    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1093    const events = await submitTransactionAsync(sender, tx);1094    const result = getGenericResult(events);10951096    // Get the collection1097    const collection = await queryCollectionExpectSuccess(api, collectionId);10981099    // What to expect1100    // tslint:disable-next-line:no-unused-expression1101    expect(result.success).to.be.true;1102    expect(collection.access.toHuman()).to.be.equal(accessMode);1103  });1104}11051106export async function setPublicAccessModeExpectFail(1107  sender: IKeyringPair, collectionId: number,1108  accessMode: 'Normal' | 'AllowList',1109) {1110  await usingApi(async (api) => {11111112    // Run the transaction1113    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1114    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1115    const result = getGenericResult(events);11161117    // What to expect1118    // tslint:disable-next-line:no-unused-expression1119    expect(result.success).to.be.false;1120  });1121}11221123export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1124  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1125}11261127export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1128  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1129}11301131export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1132  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1133}11341135export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1136  await usingApi(async (api) => {11371138    // Run the transaction1139    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1140    const events = await submitTransactionAsync(sender, tx);1141    const result = getGenericResult(events);1142    expect(result.success).to.be.true;11431144    // Get the collection1145    const collection = await queryCollectionExpectSuccess(api, collectionId);11461147    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1148  });1149}11501151export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1152  await setMintPermissionExpectSuccess(sender, collectionId, true);1153}11541155export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1156  await usingApi(async (api) => {1157    // Run the transaction1158    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1159    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1160    const result = getCreateCollectionResult(events);1161    // tslint:disable-next-line:no-unused-expression1162    expect(result.success).to.be.false;1163  });1164}11651166export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1167  await usingApi(async (api) => {1168    // Run the transaction1169    const tx = api.tx.unique.setChainLimits(limits);1170    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1171    const result = getCreateCollectionResult(events);1172    // tslint:disable-next-line:no-unused-expression1173    expect(result.success).to.be.false;1174  });1175}11761177export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1178  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1179}11801181export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1182  await usingApi(async (api) => {1183    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11841185    // Run the transaction1186    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1187    const events = await submitTransactionAsync(sender, tx);1188    const result = getGenericResult(events);1189    expect(result.success).to.be.true;11901191    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1192  });1193}11941195export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1196  await usingApi(async (api) => {11971198    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11991200    // Run the transaction1201    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1202    const events = await submitTransactionAsync(sender, tx);1203    const result = getGenericResult(events);1204    expect(result.success).to.be.true;12051206    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1207  });1208}12091210export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1211  await usingApi(async (api) => {12121213    // Run the transaction1214    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1215    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1216    const result = getGenericResult(events);12171218    // What to expect1219    // tslint:disable-next-line:no-unused-expression1220    expect(result.success).to.be.false;1221  });1222}12231224export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1225  await usingApi(async (api) => {1226    // Run the transaction1227    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1228    const events = await submitTransactionAsync(sender, tx);1229    const result = getGenericResult(events);12301231    // What to expect1232    // tslint:disable-next-line:no-unused-expression1233    expect(result.success).to.be.true;1234  });1235}12361237export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1238  await usingApi(async (api) => {1239    // Run the transaction1240    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1241    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1242    const result = getGenericResult(events);12431244    // What to expect1245    // tslint:disable-next-line:no-unused-expression1246    expect(result.success).to.be.false;1247  });1248}12491250export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1251  : Promise<UpDataStructsCollection | null> => {1252  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1253};12541255export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1256  // set global object - collectionsCount1257  return (await api.rpc.unique.collectionStats()).created.toNumber();1258};12591260export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1261  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1262}12631264export async function waitNewBlocks(blocksCount = 1): Promise<void> {1265  await usingApi(async (api) => {1266    const promise = new Promise<void>(async (resolve) => {1267      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1268        if (blocksCount > 0) {1269          blocksCount--;1270        } else {1271          unsubscribe();1272          resolve();1273        }1274      });1275    });1276    return promise;1277  });1278}
after · tests/src/util/helpers.ts
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, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord} from '@polkadot/types/interfaces';21import {IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsCollection} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  success: boolean;109  collectionId: number;110  itemId: number;111  sender?: CrossAccountId;112  recipient?: CrossAccountId;113  value: bigint;114}115116interface IReFungibleOwner {117  fraction: BN;118  owner: number[];119}120121interface IGetMessage {122  checkMsgUnqMethod: string;123  checkMsgTrsMethod: string;124  checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128  value: number;129}130131export interface IChainLimits {132  collectionNumbersLimit: number;133  accountTokenOwnershipLimit: number;134  collectionsAdminsLimit: number;135  customDataLimit: number;136  nftSponsorTransferTimeout: number;137  fungibleSponsorTransferTimeout: number;138  refungibleSponsorTransferTimeout: number;139  offchainSchemaLimit: number;140  variableOnChainSchemaLimit: number;141  constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145  owner: IReFungibleOwner[];146  constData: number[];147  variableData: number[];148}149150export function uniqueEventMessage(events: EventRecord[]): IGetMessage {151  let checkMsgUnqMethod = '';152  let checkMsgTrsMethod = '';153  let checkMsgSysMethod = '';154  events.forEach(({event: {method, section}}) => {155    if (section === 'common') {156      checkMsgUnqMethod = method;157    } else if (section === 'treasury') {158      checkMsgTrsMethod = method;159    } else if (section === 'system') {160      checkMsgSysMethod = method;161    } else { return null; }162  });163  const result: IGetMessage = {164    checkMsgUnqMethod,165    checkMsgTrsMethod,166    checkMsgSysMethod,167  };168  return result;169}170171export function getGenericResult(events: EventRecord[]): GenericResult {172  const result: GenericResult = {173    success: false,174  };175  events.forEach(({event: {method}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method === 'ExtrinsicSuccess') {178      result.success = true;179    }180  });181  return result;182}183184185186export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {187  let success = false;188  let collectionId = 0;189  events.forEach(({event: {data, method, section}}) => {190    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);191    if (method == 'ExtrinsicSuccess') {192      success = true;193    } else if ((section == 'common') && (method == 'CollectionCreated')) {194      collectionId = parseInt(data[0].toString(), 10);195    }196  });197  const result: CreateCollectionResult = {198    success,199    collectionId,200  };201  return result;202}203204export function getCreateItemResult(events: EventRecord[]): CreateItemResult {205  let success = false;206  let collectionId = 0;207  let itemId = 0;208  let recipient;209  events.forEach(({event: {data, method, section}}) => {210    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);211    if (method == 'ExtrinsicSuccess') {212      success = true;213    } else if ((section == 'common') && (method == 'ItemCreated')) {214      collectionId = parseInt(data[0].toString(), 10);215      itemId = parseInt(data[1].toString(), 10);216      recipient = normalizeAccountId(data[2].toJSON() as any);217    }218  });219  const result: CreateItemResult = {220    success,221    collectionId,222    itemId,223    recipient,224  };225  return result;226}227228export function getTransferResult(events: EventRecord[]): TransferResult {229  const result: TransferResult = {230    success: false,231    collectionId: 0,232    itemId: 0,233    value: 0n,234  };235236  events.forEach(({event: {data, method, section}}) => {237    if (method === 'ExtrinsicSuccess') {238      result.success = true;239    } else if (section === 'common' && method === 'Transfer') {240      result.collectionId = +data[0].toString();241      result.itemId = +data[1].toString();242      result.sender = normalizeAccountId(data[2].toJSON() as any);243      result.recipient = normalizeAccountId(data[3].toJSON() as any);244      result.value = BigInt(data[4].toString());245    }246  });247248  return result;249}250251interface Nft {252  type: 'NFT';253}254255interface Fungible {256  type: 'Fungible';257  decimalPoints: number;258}259260interface ReFungible {261  type: 'ReFungible';262}263264type CollectionMode = Nft | Fungible | ReFungible;265266export type CreateCollectionParams = {267  mode: CollectionMode,268  name: string,269  description: string,270  tokenPrefix: string,271  schemaVersion: string,272};273274const defaultCreateCollectionParams: CreateCollectionParams = {275  description: 'description',276  mode: {type: 'NFT'},277  name: 'name',278  tokenPrefix: 'prefix',279  schemaVersion: 'ImageURL',280};281282export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {283  const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};284285  let collectionId = 0;286  await usingApi(async (api) => {287    // Get number of collections before the transaction288    const collectionCountBefore = await getCreatedCollectionCount(api);289290    // Run the CreateCollection transaction291    const alicePrivateKey = privateKey('//Alice');292293    let modeprm = {};294    if (mode.type === 'NFT') {295      modeprm = {nft: null};296    } else if (mode.type === 'Fungible') {297      modeprm = {fungible: mode.decimalPoints};298    } else if (mode.type === 'ReFungible') {299      modeprm = {refungible: null};300    }301302    const tx = api.tx.unique.createCollectionEx({303      name: strToUTF16(name), 304      description: strToUTF16(description), 305      tokenPrefix: strToUTF16(tokenPrefix), 306      mode: modeprm as any,307      schemaVersion: schemaVersion,308    });309    const events = await submitTransactionAsync(alicePrivateKey, tx);310    const result = getCreateCollectionResult(events);311312    // Get number of collections after the transaction313    const collectionCountAfter = await getCreatedCollectionCount(api);314315    // Get the collection316    const collection = await queryCollectionExpectSuccess(api, result.collectionId);317318    // What to expect319    // tslint:disable-next-line:no-unused-expression320    expect(result.success).to.be.true;321    expect(result.collectionId).to.be.equal(collectionCountAfter);322    // tslint:disable-next-line:no-unused-expression323    expect(collection).to.be.not.null;324    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');325    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));326    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);327    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);328    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);329330    collectionId = result.collectionId;331  });332333  return collectionId;334}335336export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {337  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};338339  let modeprm = {};340  if (mode.type === 'NFT') {341    modeprm = {nft: null};342  } else if (mode.type === 'Fungible') {343    modeprm = {fungible: mode.decimalPoints};344  } else if (mode.type === 'ReFungible') {345    modeprm = {refungible: null};346  }347348  await usingApi(async (api) => {349    // Get number of collections before the transaction350    const collectionCountBefore = await getCreatedCollectionCount(api);351352    // Run the CreateCollection transaction353    const alicePrivateKey = privateKey('//Alice');354    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});355    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;356357    // Get number of collections after the transaction358    const collectionCountAfter = await getCreatedCollectionCount(api);359360    // What to expect361    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');362  });363}364365export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {366  let bal = 0n;367  let unused;368  do {369    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;370    const keyring = new Keyring({type: 'sr25519'});371    unused = keyring.addFromUri(`//${randomSeed}`);372    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();373  } while (bal !== 0n);374  return unused;375}376377export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {378  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();379}380381export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {382  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));383}384385export async function findNotExistingCollection(api: ApiPromise): Promise<number> {386  const totalNumber = await getCreatedCollectionCount(api);387  const newCollection: number = totalNumber + 1;388  return newCollection;389}390391function getDestroyResult(events: EventRecord[]): boolean {392  let success = false;393  events.forEach(({event: {method}}) => {394    if (method == 'ExtrinsicSuccess') {395      success = true;396    }397  });398  return success;399}400401export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {402  await usingApi(async (api) => {403    // Run the DestroyCollection transaction404    const alicePrivateKey = privateKey(senderSeed);405    const tx = api.tx.unique.destroyCollection(collectionId);406    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;407  });408}409410export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {411  await usingApi(async (api) => {412    // Run the DestroyCollection transaction413    const alicePrivateKey = privateKey(senderSeed);414    const tx = api.tx.unique.destroyCollection(collectionId);415    const events = await submitTransactionAsync(alicePrivateKey, tx);416    const result = getDestroyResult(events);417    expect(result).to.be.true;418419    // What to expect420    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;421  });422}423424export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {425  await usingApi(async (api) => {426    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);427    const events = await submitTransactionAsync(sender, tx);428    const result = getGenericResult(events);429430    expect(result.success).to.be.true;431  });432}433434export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {435  await usingApi(async (api) => {436    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);437    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;438    const result = getGenericResult(events);439440    expect(result.success).to.be.false;441  });442}443444export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const senderPrivateKey = privateKey(sender);449    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);450    const events = await submitTransactionAsync(senderPrivateKey, tx);451    const result = getGenericResult(events);452453    // Get the collection454    const collection = await queryCollectionExpectSuccess(api, collectionId);455456    // What to expect457    expect(result.success).to.be.true;458    expect(collection.sponsorship.toJSON()).to.deep.equal({459      unconfirmed: sponsor,460    });461  });462}463464export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {465  await usingApi(async (api) => {466467    // Run the transaction468    const alicePrivateKey = privateKey(sender);469    const tx = api.tx.unique.removeCollectionSponsor(collectionId);470    const events = await submitTransactionAsync(alicePrivateKey, tx);471    const result = getGenericResult(events);472473    // Get the collection474    const collection = await queryCollectionExpectSuccess(api, collectionId);475476    // What to expect477    expect(result.success).to.be.true;478    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});479  });480}481482export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {483  await usingApi(async (api) => {484485    // Run the transaction486    const alicePrivateKey = privateKey(senderSeed);487    const tx = api.tx.unique.removeCollectionSponsor(collectionId);488    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;489  });490}491492export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {493  await usingApi(async (api) => {494495    // Run the transaction496    const alicePrivateKey = privateKey(senderSeed);497    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);498    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;499  });500}501502export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {503  await usingApi(async (api) => {504505    // Run the transaction506    const sender = privateKey(senderSeed);507    const tx = api.tx.unique.confirmSponsorship(collectionId);508    const events = await submitTransactionAsync(sender, tx);509    const result = getGenericResult(events);510511    // Get the collection512    const collection = await queryCollectionExpectSuccess(api, collectionId);513514    // What to expect515    expect(result.success).to.be.true;516    expect(collection.sponsorship.toJSON()).to.be.deep.equal({517      confirmed: sender.address,518    });519  });520}521522523export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {524  await usingApi(async (api) => {525526    // Run the transaction527    const sender = privateKey(senderSeed);528    const tx = api.tx.unique.confirmSponsorship(collectionId);529    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530  });531}532533export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {534535  await usingApi(async (api) => {536    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);537    const events = await submitTransactionAsync(sender, tx);538    const result = getGenericResult(events);539540    expect(result.success).to.be.true;541  });542}543544export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {545546  await usingApi(async (api) => {547    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);548    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;549    const result = getGenericResult(events);550551    expect(result.success).to.be.false;552  });553}554555export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {556  await usingApi(async (api) => {557    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);558    const events = await submitTransactionAsync(sender, tx);559    const result = getGenericResult(events);560561    expect(result.success).to.be.true;562  });563}564565export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {566  await usingApi(async (api) => {567    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);568    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;569    const result = getGenericResult(events);570571    expect(result.success).to.be.false;572  });573}574575export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {576577  await usingApi(async (api) => {578579    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);580    const events = await submitTransactionAsync(sender, tx);581    const result = getGenericResult(events);582583    expect(result.success).to.be.true;584  });585}586587export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {588589  await usingApi(async (api) => {590591    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);592    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;593    const result = getGenericResult(events);594595    expect(result.success).to.be.false;596  });597}598599export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {600  await usingApi(async (api) => {601    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);602    const events = await submitTransactionAsync(sender, tx);603    const result = getGenericResult(events);604605    expect(result.success).to.be.true;606  });607}608609export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {610  await usingApi(async (api) => {611    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);612    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;613    const result = getGenericResult(events);614615    expect(result.success).to.be.false;616  });617}618619export async function getNextSponsored(620  api: ApiPromise,621  collectionId: number,622  account: string | CrossAccountId,623  tokenId: number,624): Promise<number> {625  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));626}627628export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {629  await usingApi(async (api) => {630    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    expect(result.success).to.be.true;635  });636}637638export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {639  let allowlisted = false;640  await usingApi(async (api) => {641    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;642  });643  return allowlisted;644}645646export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {647  await usingApi(async (api) => {648    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());649    const events = await submitTransactionAsync(sender, tx);650    const result = getGenericResult(events);651652    expect(result.success).to.be.true;653  });654}655656export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {657  await usingApi(async (api) => {658    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());659    const events = await submitTransactionAsync(sender, tx);660    const result = getGenericResult(events);661662    expect(result.success).to.be.true;663  });664}665666export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {667  await usingApi(async (api) => {668    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());669    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;670    const result = getGenericResult(events);671672    expect(result.success).to.be.false;673  });674}675676export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {677  await usingApi(async (api) => {678    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));679    const events = await submitTransactionAsync(sender, tx);680    const result = getGenericResult(events);681682    expect(result.success).to.be.true;683  });684}685686export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {687  await usingApi(async (api) => {688    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));689    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;690  });691}692693export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {694  await usingApi(async (api) => {695    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));696    const events = await submitTransactionAsync(sender, tx);697    const result = getGenericResult(events);698699    expect(result.success).to.be.true;700  });701}702703export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {704  await usingApi(async (api) => {705    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));706    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707  });708}709710export interface CreateFungibleData {711  readonly Value: bigint;712}713714export interface CreateReFungibleData { }715export interface CreateNftData { }716717export type CreateItemData = {718  NFT: CreateNftData;719} | {720  Fungible: CreateFungibleData;721} | {722  ReFungible: CreateReFungibleData;723};724725export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {726  await usingApi(async (api) => {727    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);728    // if burning token by admin - use adminButnItemExpectSuccess729    expect(balanceBefore >= BigInt(value)).to.be.true;730731    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);732    const events = await submitTransactionAsync(sender, tx);733    const result = getGenericResult(events);734    expect(result.success).to.be.true;735736    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);737    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);738  });739}740741export async function742approveExpectSuccess(743  collectionId: number,744  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,745) {746  await usingApi(async (api: ApiPromise) => {747    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);748    const events = await submitTransactionAsync(owner, approveUniqueTx);749    const result = getGenericResult(events);750    expect(result.success).to.be.true;751752    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));753  });754}755756export async function adminApproveFromExpectSuccess(757  collectionId: number,758  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,759) {760  await usingApi(async (api: ApiPromise) => {761    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);762    const events = await submitTransactionAsync(admin, approveUniqueTx);763    const result = getGenericResult(events);764    expect(result.success).to.be.true;765766    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));767  });768}769770export async function771transferFromExpectSuccess(772  collectionId: number,773  tokenId: number,774  accountApproved: IKeyringPair,775  accountFrom: IKeyringPair | CrossAccountId,776  accountTo: IKeyringPair | CrossAccountId,777  value: number | bigint = 1,778  type = 'NFT',779) {780  await usingApi(async (api: ApiPromise) => {781    const from = normalizeAccountId(accountFrom);782    const to = normalizeAccountId(accountTo);783    let balanceBefore = 0n;784    if (type === 'Fungible') {785      balanceBefore = await getBalance(api, collectionId, to, tokenId);786    }787    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);788    const events = await submitTransactionAsync(accountApproved, transferFromTx);789    const result = getCreateItemResult(events);790    // tslint:disable-next-line:no-unused-expression791    expect(result.success).to.be.true;792    if (type === 'NFT') {793      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);794    }795    if (type === 'Fungible') {796      const balanceAfter = await getBalance(api, collectionId, to, tokenId);797      if (JSON.stringify(to) !== JSON.stringify(from)) {798        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));799      } else {800        expect(balanceAfter).to.be.equal(balanceBefore);801      }802    }803    if (type === 'ReFungible') {804      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));805    }806  });807}808809export async function810transferFromExpectFail(811  collectionId: number,812  tokenId: number,813  accountApproved: IKeyringPair,814  accountFrom: IKeyringPair,815  accountTo: IKeyringPair,816  value: number | bigint = 1,817) {818  await usingApi(async (api: ApiPromise) => {819    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);820    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;821    const result = getCreateCollectionResult(events);822    // tslint:disable-next-line:no-unused-expression823    expect(result.success).to.be.false;824  });825}826827/* eslint no-async-promise-executor: "off" */828async function getBlockNumber(api: ApiPromise): Promise<number> {829  return new Promise<number>(async (resolve) => {830    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {831      unsubscribe();832      resolve(head.number.toNumber());833    });834  });835}836837export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {838  await usingApi(async (api) => {839    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));840    const events = await submitTransactionAsync(sender, changeAdminTx);841    const result = getCreateCollectionResult(events);842    expect(result.success).to.be.true;843  });844}845846export async function847getFreeBalance(account: IKeyringPair): Promise<bigint> {848  let balance = 0n;849  await usingApi(async (api) => {850    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());851  });852853  return balance;854}855856export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {857  const tx = api.tx.balances.transfer(target, amount);858  const events = await submitTransactionAsync(source, tx);859  const result = getGenericResult(events);860  expect(result.success).to.be.true;861}862863export async function864scheduleTransferExpectSuccess(865  collectionId: number,866  tokenId: number,867  sender: IKeyringPair,868  recipient: IKeyringPair,869  value: number | bigint = 1,870  blockSchedule: number,871) {872  await usingApi(async (api: ApiPromise) => {873    const blockNumber: number | undefined = await getBlockNumber(api);874    const expectedBlockNumber = blockNumber + blockSchedule;875876    expect(blockNumber).to.be.greaterThan(0);877    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);878    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);879880    await submitTransactionAsync(sender, scheduleTx);881882    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();883884    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));885886    // sleep for 4 blocks887    await waitNewBlocks(blockSchedule + 1);888889    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();890891    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));892    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);893  });894}895896897export async function898transferExpectSuccess(899  collectionId: number,900  tokenId: number,901  sender: IKeyringPair,902  recipient: IKeyringPair | CrossAccountId,903  value: number | bigint = 1,904  type = 'NFT',905) {906  await usingApi(async (api: ApiPromise) => {907    const from = normalizeAccountId(sender);908    const to = normalizeAccountId(recipient);909910    let balanceBefore = 0n;911    if (type === 'Fungible') {912      balanceBefore = await getBalance(api, collectionId, to, tokenId);913    }914    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);915    const events = await submitTransactionAsync(sender, transferTx);916    const result = getTransferResult(events);917    // tslint:disable-next-line:no-unused-expression918    expect(result.success).to.be.true;919    expect(result.collectionId).to.be.equal(collectionId);920    expect(result.itemId).to.be.equal(tokenId);921    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));922    expect(result.recipient).to.be.deep.equal(to);923    expect(result.value).to.be.equal(BigInt(value));924    if (type === 'NFT') {925      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);926    }927    if (type === 'Fungible') {928      const balanceAfter = await getBalance(api, collectionId, to, tokenId);929      if (JSON.stringify(to) !== JSON.stringify(from)) {930        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));931      } else {932        expect(balanceAfter).to.be.equal(balanceBefore);933      }934    }935    if (type === 'ReFungible') {936      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;937    }938  });939}940941export async function942transferExpectFailure(943  collectionId: number,944  tokenId: number,945  sender: IKeyringPair,946  recipient: IKeyringPair,947  value: number | bigint = 1,948) {949  await usingApi(async (api: ApiPromise) => {950    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);951    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;952    const result = getGenericResult(events);953    // if (events && Array.isArray(events)) {954    //   const result = getCreateCollectionResult(events);955    // tslint:disable-next-line:no-unused-expression956    expect(result.success).to.be.false;957    //}958  });959}960961export async function962approveExpectFail(963  collectionId: number,964  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,965) {966  await usingApi(async (api: ApiPromise) => {967    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);968    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;969    const result = getCreateCollectionResult(events);970    // tslint:disable-next-line:no-unused-expression971    expect(result.success).to.be.false;972  });973}974975export async function getBalance(976  api: ApiPromise,977  collectionId: number,978  owner: string | CrossAccountId,979  token: number,980): Promise<bigint> {981  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();982}983export async function getTokenOwner(984  api: ApiPromise,985  collectionId: number,986  token: number,987): Promise<CrossAccountId> {988  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);989}990export async function isTokenExists(991  api: ApiPromise,992  collectionId: number,993  token: number,994): Promise<boolean> {995  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();996}997export async function getLastTokenId(998  api: ApiPromise,999  collectionId: number,1000): Promise<number> {1001  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1002}1003export async function getAdminList(1004  api: ApiPromise,1005  collectionId: number,1006): Promise<string[]> {1007  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1008}1009export async function getVariableMetadata(1010  api: ApiPromise,1011  collectionId: number,1012  tokenId: number,1013): Promise<number[]> {1014  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1015}1016export async function getConstMetadata(1017  api: ApiPromise,1018  collectionId: number,1019  tokenId: number,1020): Promise<number[]> {1021  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1022}10231024export async function createFungibleItemExpectSuccess(1025  sender: IKeyringPair,1026  collectionId: number,1027  data: CreateFungibleData,1028  owner: CrossAccountId | string = sender.address,1029) {1030  return await usingApi(async (api) => {1031    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10321033    const events = await submitTransactionAsync(sender, tx);1034    const result = getCreateItemResult(events);10351036    expect(result.success).to.be.true;1037    return result.itemId;1038  });1039}10401041export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1042  let newItemId = 0;1043  await usingApi(async (api) => {1044    const to = normalizeAccountId(owner);1045    const itemCountBefore = await getLastTokenId(api, collectionId);1046    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10471048    let tx;1049    if (createMode === 'Fungible') {1050      const createData = {fungible: {value: 10}};1051      tx = api.tx.unique.createItem(collectionId, to, createData as any);1052    } else if (createMode === 'ReFungible') {1053      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1054      tx = api.tx.unique.createItem(collectionId, to, createData as any);1055    } else {1056      const createData = {nft: {const_data: [], variable_data: []}};1057      tx = api.tx.unique.createItem(collectionId, to, createData as any);1058    }10591060    const events = await submitTransactionAsync(sender, tx);1061    const result = getCreateItemResult(events);10621063    const itemCountAfter = await getLastTokenId(api, collectionId);1064    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10651066    // What to expect1067    // tslint:disable-next-line:no-unused-expression1068    expect(result.success).to.be.true;1069    if (createMode === 'Fungible') {1070      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1071    } else {1072      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1073    }1074    expect(collectionId).to.be.equal(result.collectionId);1075    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1076    expect(to).to.be.deep.equal(result.recipient);1077    newItemId = result.itemId;1078  });1079  return newItemId;1080}10811082export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1083  await usingApi(async (api) => {1084    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10851086    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1087    const result = getCreateItemResult(events);10881089    expect(result.success).to.be.false;1090  });1091}10921093export async function setPublicAccessModeExpectSuccess(1094  sender: IKeyringPair, collectionId: number,1095  accessMode: 'Normal' | 'AllowList',1096) {1097  await usingApi(async (api) => {10981099    // Run the transaction1100    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1101    const events = await submitTransactionAsync(sender, tx);1102    const result = getGenericResult(events);11031104    // Get the collection1105    const collection = await queryCollectionExpectSuccess(api, collectionId);11061107    // What to expect1108    // tslint:disable-next-line:no-unused-expression1109    expect(result.success).to.be.true;1110    expect(collection.access.toHuman()).to.be.equal(accessMode);1111  });1112}11131114export async function setPublicAccessModeExpectFail(1115  sender: IKeyringPair, collectionId: number,1116  accessMode: 'Normal' | 'AllowList',1117) {1118  await usingApi(async (api) => {11191120    // Run the transaction1121    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1122    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1123    const result = getGenericResult(events);11241125    // What to expect1126    // tslint:disable-next-line:no-unused-expression1127    expect(result.success).to.be.false;1128  });1129}11301131export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1132  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1133}11341135export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1136  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1137}11381139export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1140  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1141}11421143export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1144  await usingApi(async (api) => {11451146    // Run the transaction1147    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1148    const events = await submitTransactionAsync(sender, tx);1149    const result = getGenericResult(events);1150    expect(result.success).to.be.true;11511152    // Get the collection1153    const collection = await queryCollectionExpectSuccess(api, collectionId);11541155    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1156  });1157}11581159export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1160  await setMintPermissionExpectSuccess(sender, collectionId, true);1161}11621163export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1164  await usingApi(async (api) => {1165    // Run the transaction1166    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1167    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1168    const result = getCreateCollectionResult(events);1169    // tslint:disable-next-line:no-unused-expression1170    expect(result.success).to.be.false;1171  });1172}11731174export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1175  await usingApi(async (api) => {1176    // Run the transaction1177    const tx = api.tx.unique.setChainLimits(limits);1178    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179    const result = getCreateCollectionResult(events);1180    // tslint:disable-next-line:no-unused-expression1181    expect(result.success).to.be.false;1182  });1183}11841185export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1186  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1187}11881189export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1190  await usingApi(async (api) => {1191    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11921193    // Run the transaction1194    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1195    const events = await submitTransactionAsync(sender, tx);1196    const result = getGenericResult(events);1197    expect(result.success).to.be.true;11981199    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1200  });1201}12021203export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1204  await usingApi(async (api) => {12051206    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12071208    // Run the transaction1209    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1210    const events = await submitTransactionAsync(sender, tx);1211    const result = getGenericResult(events);1212    expect(result.success).to.be.true;12131214    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1215  });1216}12171218export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1219  await usingApi(async (api) => {12201221    // Run the transaction1222    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1223    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1224    const result = getGenericResult(events);12251226    // What to expect1227    // tslint:disable-next-line:no-unused-expression1228    expect(result.success).to.be.false;1229  });1230}12311232export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1233  await usingApi(async (api) => {1234    // Run the transaction1235    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1236    const events = await submitTransactionAsync(sender, tx);1237    const result = getGenericResult(events);12381239    // What to expect1240    // tslint:disable-next-line:no-unused-expression1241    expect(result.success).to.be.true;1242  });1243}12441245export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1246  await usingApi(async (api) => {1247    // Run the transaction1248    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1249    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1250    const result = getGenericResult(events);12511252    // What to expect1253    // tslint:disable-next-line:no-unused-expression1254    expect(result.success).to.be.false;1255  });1256}12571258export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1259  : Promise<UpDataStructsCollection | null> => {1260  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1261};12621263export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1264  // set global object - collectionsCount1265  return (await api.rpc.unique.collectionStats()).created.toNumber();1266};12671268export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1269  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1270}12711272export async function waitNewBlocks(blocksCount = 1): Promise<void> {1273  await usingApi(async (api) => {1274    const promise = new Promise<void>(async (resolve) => {1275      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1276        if (blocksCount > 0) {1277          blocksCount--;1278        } else {1279          unsubscribe();1280          resolve();1281        }1282      });1283    });1284    return promise;1285  });1286}