git.delta.rocks / unique-network / refs/commits / fb129ad11e28

difftreelog

test createCollectionEx

Yaroslav Bolyukin2022-01-11parent: #e637581.patch.diff
in: master

14 files changed

modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -67,9 +67,10 @@
     "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
     "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
     "testEnableDisableTransfers": "mocha --timeout 9999999 -r ts-node/register ./**/enableDisableTransfer.test.ts",
+    "polkadot-types-fetch-metadata": "curl -H 'Content-Type: application/json' -d '{\"id\":\"1\", \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\", \"params\":[]}' http://localhost:9933 > src/interfaces/metadata.json",
     "polkadot-types-from-defs": "ts-node ./node_modules/.bin/polkadot-types-from-defs --input src/interfaces/ --package .",
-    "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint ws://localhost:9944 --output src/interfaces/ --package .",
-    "polkadot-types": "yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
+    "polkadot-types-from-chain": "ts-node ./node_modules/.bin/polkadot-types-from-chain --endpoint src/interfaces/metadata.json --output src/interfaces/ --package .",
+    "polkadot-types": "yarn polkadot-types-fetch-metadata && yarn polkadot-types-from-defs && yarn polkadot-types-from-chain"
   },
   "author": "",
   "license": "SEE LICENSE IN ../LICENSE",
modifiedtests/src/check-event/createCollectionEvent.test.tsdiffbeforeafterboth
--- a/tests/src/check-event/createCollectionEvent.test.ts
+++ b/tests/src/check-event/createCollectionEvent.test.ts
@@ -27,7 +27,7 @@
   });
   it('Check event from createCollection(): ', async () => {
     await usingApi(async (api: ApiPromise) => {
-      const tx = api.tx.unique.createCollection([0x31], [0x32], '0x33', 'NFT');
+      const tx = api.tx.unique.createCollectionEx({name: [0x31], description: [0x32], tokenPrefix: '0x33', mode: 'NFT'});
       const events = await submitTransactionAsync(alice, tx);
       const msg = JSON.stringify(uniqueEventMessage(events));
       expect(msg).to.be.contain(checkSection);
modifiedtests/src/createCollection.test.tsdiffbeforeafterboth
--- a/tests/src/createCollection.test.ts
+++ b/tests/src/createCollection.test.ts
@@ -3,12 +3,11 @@
 // file 'LICENSE', which is part of this source code package.
 //
 
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {createCollectionExpectFailure, createCollectionExpectSuccess} from './util/helpers';
+import {expect} from 'chai';
+import privateKey from './substrate/privateKey';
+import usingApi, {executeTransaction, submitTransactionAsync} from './substrate/substrate-api';
+import {createCollectionExpectFailure, createCollectionExpectSuccess, getCreateCollectionResult, getDetailedCollectionInfo} from './util/helpers';
 
-chai.use(chaiAsPromised);
-
 describe('integration test: ext. createCollection():', () => {
   it('Create new NFT collection', async () => {
     await createCollectionExpectSuccess({name: 'A', description: 'B', tokenPrefix: 'C', mode: {type: 'NFT'}});
@@ -28,6 +27,45 @@
   it('Create new ReFungible collection', async () => {
     await createCollectionExpectSuccess({mode: {type: 'ReFungible'}});
   });
+  it('Create new collection with extra fields', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const bob = privateKey('//Bob');
+      const tx = api.tx.unique.createCollectionEx({
+        mode: {Fungible: 8},
+        access: 'AllowList',
+        name: [1],
+        description: [2],
+        tokenPrefix: '0x000000',
+        offchainSchema: '0x111111',
+        schemaVersion: 'Unique',
+        pendingSponsor: bob.address,
+        limits: {
+          accountTokenOwnershipLimit: 3,
+        },
+        variableOnChainSchema: '0x222222',
+        constOnChainSchema: '0x333333',
+        metaUpdatePermission: 'Admin',
+      });
+      const events = await submitTransactionAsync(alice, tx);
+      const result = getCreateCollectionResult(events);
+
+      const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+      expect(collection.owner.toString()).to.equal(alice.address);
+      expect(collection.mode.asFungible.toNumber()).to.equal(8);
+      expect(collection.access.isAllowList).to.be.true;
+      expect(collection.name.map(v => v.toNumber())).to.deep.equal([1]);
+      expect(collection.description.map(v => v.toNumber())).to.deep.equal([2]);
+      expect(collection.tokenPrefix.toString()).to.equal('0x000000');
+      expect(collection.offchainSchema.toString()).to.equal('0x111111');
+      expect(collection.schemaVersion.isUnique).to.be.true;
+      expect(collection.sponsorship.asUnconfirmed.toString()).to.equal(bob.address);
+      expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.equal(3);
+      expect(collection.variableOnChainSchema.toString()).to.equal('0x222222');
+      expect(collection.constOnChainSchema.toString()).to.equal('0x333333');
+      expect(collection.metaUpdatePermission.isAdmin).to.be.true;
+    });
+  });
 });
 
 describe('(!negative test!) integration test: ext. createCollection():', () => {
@@ -40,4 +78,11 @@
   it('(!negative test!) create new NFT collection whith incorrect data (token_prefix)', async () => {
     await createCollectionExpectFailure({tokenPrefix: 'A'.repeat(17), mode: {type: 'NFT'}});
   });
+  it('fails when bad limits are set', async () => {
+    await usingApi(async api => {
+      const alice = privateKey('//Alice');
+      const tx = api.tx.unique.createCollectionEx({mode: 'NFT', limits: {tokenLimit: 0}});
+      await expect(executeTransaction(api, alice, tx)).to.be.rejectedWith(/^common.CollectionTokenLimitExceeded$/);
+    });
+  });
 });
addedtests/src/interfaces/.gitignorediffbeforeafterboth
--- /dev/null
+++ b/tests/src/interfaces/.gitignore
@@ -0,0 +1 @@
+metadata.json
modifiedtests/src/interfaces/augment-api-consts.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-consts.ts
+++ b/tests/src/interfaces/augment-api-consts.ts
@@ -36,6 +36,9 @@
       [key: string]: Codec;
     };
     inflation: {
+      /**
+       * Number of blocks that pass between treasury balance updates due to inflation
+       **/
       inflationBlockInterval: u32 & AugmentedConst<ApiType>;
       /**
        * Generic const
modifiedtests/src/interfaces/augment-api-errors.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-errors.ts
+++ b/tests/src/interfaces/augment-api-errors.ts
@@ -61,14 +61,18 @@
        **/
       CantApproveMoreThanOwned: AugmentedError<ApiType>;
       /**
-       * Exceeded max admin amount
+       * Exceeded max admin count
        **/
-      CollectionAdminAmountExceeded: AugmentedError<ApiType>;
+      CollectionAdminCountExceeded: AugmentedError<ApiType>;
       /**
        * Collection description can not be longer than 255 char.
        **/
       CollectionDescriptionLimitExceeded: AugmentedError<ApiType>;
       /**
+       * Collection limit bounds per collection exceeded
+       **/
+      CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
+      /**
        * Collection name can not be longer than 63 char.
        **/
       CollectionNameLimitExceeded: AugmentedError<ApiType>;
@@ -97,6 +101,10 @@
        **/
       NoPermission: AugmentedError<ApiType>;
       /**
+       * Tried to enable permissions which are only permitted to be disabled
+       **/
+      OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
+      /**
        * Collection is not in mint mode.
        **/
       PublicMintingNotAllowed: AugmentedError<ApiType>;
@@ -227,7 +235,7 @@
       /**
        * Tried to set data for fungible item
        **/
-      FungibleItemsHaveData: AugmentedError<ApiType>;
+      FungibleItemsDontHaveData: AugmentedError<ApiType>;
       /**
        * Not default id passed as TokenId argument
        **/
@@ -381,6 +389,10 @@
     };
     system: {
       /**
+       * The origin filter prevent the call to be dispatched.
+       **/
+      CallFiltered: AugmentedError<ApiType>;
+      /**
        * Failed to extract the runtime version from the new runtime.
        * 
        * Either calling `Core_version` or decoding `RuntimeVersion` failed.
@@ -433,10 +445,6 @@
        **/
       CollectionDecimalPointLimitExceeded: AugmentedError<ApiType>;
       /**
-       * Collection limit bounds per collection exceeded
-       **/
-      CollectionLimitBoundsExceeded: AugmentedError<ApiType>;
-      /**
        * This address is not set as sponsor, use setCollectionSponsor first.
        **/
       ConfirmUnsetSponsorFail: AugmentedError<ApiType>;
@@ -444,10 +452,6 @@
        * Length of items properties must be greater than 0.
        **/
       EmptyArgument: AugmentedError<ApiType>;
-      /**
-       * Tried to enable permissions which are only permitted to be disabled
-       **/
-      OwnerPermissionsCantBeReverted: AugmentedError<ApiType>;
       /**
        * Generic error
        **/
modifiedtests/src/interfaces/augment-api-events.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-events.ts
+++ b/tests/src/interfaces/augment-api-events.ts
@@ -2,7 +2,7 @@
 /* eslint-disable */
 
 import type { EthereumLog, EvmCoreErrorExitReason } from './ethereum';
-import type { PalletCommonAccountBasicCrossAccountIdRepr } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode } from './unique';
 import type { ApiTypes } from '@polkadot/api/types';
 import type { Null, Option, Result, U256, U8aFixed, u128, u32, u64, u8 } from '@polkadot/types';
 import type { AccountId32, H160, H256 } from '@polkadot/types/interfaces/runtime';
@@ -12,48 +12,45 @@
   export interface AugmentedEvents<ApiType> {
     balances: {
       /**
-       * A balance was set by root. \[who, free, reserved\]
+       * A balance was set by root.
        **/
       BalanceSet: AugmentedEvent<ApiType, [AccountId32, u128, u128]>;
       /**
-       * Some amount was deposited into the account (e.g. for transaction fees). \[who,
-       * deposit\]
+       * Some amount was deposited (e.g. for transaction fees).
        **/
       Deposit: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
        * An account was removed whose balance was non-zero but below ExistentialDeposit,
-       * resulting in an outright loss. \[account, balance\]
+       * resulting in an outright loss.
        **/
       DustLost: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
-       * An account was created with some free balance. \[account, free_balance\]
+       * An account was created with some free balance.
        **/
       Endowed: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
-       * Some balance was reserved (moved from free to reserved). \[who, value\]
+       * Some balance was reserved (moved from free to reserved).
        **/
       Reserved: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
        * Some balance was moved from the reserve of the first account to the second account.
        * Final argument indicates the destination balance type.
-       * \[from, to, balance, destination_status\]
        **/
       ReserveRepatriated: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128, FrameSupportTokensMiscBalanceStatus]>;
       /**
-       * Some amount was removed from the account (e.g. for misbehavior). \[who,
-       * amount_slashed\]
+       * Some amount was removed from the account (e.g. for misbehavior).
        **/
       Slashed: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
-       * Transfer succeeded. \[from, to, value\]
+       * Transfer succeeded.
        **/
       Transfer: AugmentedEvent<ApiType, [AccountId32, AccountId32, u128]>;
       /**
-       * Some balance was unreserved (moved from reserved to free). \[who, value\]
+       * Some balance was unreserved (moved from reserved to free).
        **/
       Unreserved: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
-       * Some amount was withdrawn from the account (e.g. for transaction fees). \[who, value\]
+       * Some amount was withdrawn from the account (e.g. for transaction fees).
        **/
       Withdraw: AugmentedEvent<ApiType, [AccountId32, u128]>;
       /**
@@ -87,6 +84,14 @@
        **/
       CollectionCreated: AugmentedEvent<ApiType, [u32, u8, AccountId32]>;
       /**
+       * New collection was destroyed
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique identifier of collection.
+       **/
+      CollectionDestroyed: AugmentedEvent<ApiType, [u32]>;
+      /**
        * New item was created.
        * 
        * # Arguments
@@ -289,7 +294,7 @@
       InvalidResponder: AugmentedEvent<ApiType, [XcmV1MultiLocation, u64, Option<XcmV1MultiLocation>]>;
       /**
        * Expected query response has been received but the expected origin location placed in
-       * storate by this runtime previously cannot be decoded. The query remains registered.
+       * storage by this runtime previously cannot be decoded. The query remains registered.
        * 
        * This is unexpected (since a location placed in storage in a previously executing
        * runtime should be readable prior to query timeout) and dangerous since the possibly
@@ -471,6 +476,148 @@
        **/
       [key: string]: AugmentedEvent<ApiType>;
     };
+    unique: {
+      /**
+       * Address was add to allow list
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * user:  Address.
+       **/
+      AllowListAddressAdded: AugmentedEvent<ApiType, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+      /**
+       * Address was remove from allow list
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * user:  Address.
+       **/
+      AllowListAddressRemoved: AugmentedEvent<ApiType, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+      /**
+       * Collection admin was added
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * admin:  Admin address.
+       **/
+      CollectionAdminAdded: AugmentedEvent<ApiType, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+      /**
+       * Collection admin was removed
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * admin:  Admin address.
+       **/
+      CollectionAdminRemoved: AugmentedEvent<ApiType, [u32, PalletCommonAccountBasicCrossAccountIdRepr]>;
+      /**
+       * Collection limits was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      CollectionLimitSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Collection owned was change
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * owner:  New owner address.
+       **/
+      CollectionOwnedChanged: AugmentedEvent<ApiType, [u32, AccountId32]>;
+      /**
+       * Collection sponsor was removed
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      CollectionSponsorRemoved: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Collection sponsor was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * owner:  New sponsor address.
+       **/
+      CollectionSponsorSet: AugmentedEvent<ApiType, [u32, AccountId32]>;
+      /**
+       * const on chain schema was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      ConstOnChainSchemaSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Mint permission	was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      MintPermissionSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Offchain schema was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      OffchainSchemaSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Public access mode was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * mode: New access state.
+       **/
+      PublicAccessModeSet: AugmentedEvent<ApiType, [u32, UpDataStructsAccessMode]>;
+      /**
+       * Schema version was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      SchemaVersionSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * New sponsor was confirm
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       * 
+       * * sponsor:  New sponsor address.
+       **/
+      SponsorshipConfirmed: AugmentedEvent<ApiType, [u32, AccountId32]>;
+      /**
+       * Variable on chain schema was set
+       * 
+       * # Arguments
+       * 
+       * * collection_id: Globally unique collection identifier.
+       **/
+      VariableOnChainSchemaSet: AugmentedEvent<ApiType, [u32]>;
+      /**
+       * Generic event
+       **/
+      [key: string]: AugmentedEvent<ApiType>;
+    };
     vesting: {
       /**
        * Claimed vesting. \[who, locked_amount\]
modifiedtests/src/interfaces/augment-api-query.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-query.ts
+++ b/tests/src/interfaces/augment-api-query.ts
@@ -163,10 +163,22 @@
     };
     inflation: {
       /**
-       * Current block inflation
+       * Current inflation for `InflationBlockInterval` number of blocks
        **/
       blockInflation: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
       /**
+       * Next target (relay) block when inflation will be applied
+       **/
+      nextInflationBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
+       * Next target (relay) block when inflation is recalculated
+       **/
+      nextRecalculationBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
+       * Relay block when inflation has started
+       **/
+      startBlock: AugmentedQuery<ApiType, () => Observable<u32>, []> & QueryableStorageEntry<ApiType, []>;
+      /**
        * starting year total issuance
        **/
       startingYearTotalIssuance: AugmentedQuery<ApiType, () => Observable<u128>, []> & QueryableStorageEntry<ApiType, []>;
modifiedtests/src/interfaces/augment-api-tx.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-api-tx.ts
+++ b/tests/src/interfaces/augment-api-tx.ts
@@ -3,12 +3,12 @@
 
 import type { EthereumTransactionLegacyTransaction } from './ethereum';
 import type { CumulusPrimitivesParachainInherentParachainInherentData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, UpDataStructsAccessMode, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion } from './unique';
 import type { ApiTypes, SubmittableExtrinsic } from '@polkadot/api/types';
 import type { Bytes, Compact, Option, U256, Vec, bool, u128, u16, u32, u64 } from '@polkadot/types';
 import type { Extrinsic } from '@polkadot/types/interfaces/extrinsics';
 import type { AccountId32, Call, H160, H256, MultiAddress, Perbill } from '@polkadot/types/interfaces/runtime';
-import type { SpCoreChangesTrieChangesTrieConfiguration, XcmV1MultiLocation, XcmV2WeightLimit, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from '@polkadot/types/lookup';
+import type { XcmV1MultiLocation, XcmV2WeightLimit, XcmVersionedMultiAssets, XcmVersionedMultiLocation, XcmVersionedXcm } from '@polkadot/types/lookup';
 import type { AnyNumber, ITuple } from '@polkadot/types/types';
 
 declare module '@polkadot/api/types/submittable' {
@@ -38,16 +38,6 @@
        * it will reset the account nonce (`frame_system::AccountNonce`).
        * 
        * The dispatch origin for this call is `root`.
-       * 
-       * # <weight>
-       * - Independent of the arguments.
-       * - Contains a limited number of reads and writes.
-       * ---------------------
-       * - Base Weight:
-       * - Creating: 27.56 µs
-       * - Killing: 35.11 µs
-       * - DB Weight: 1 Read, 1 Write to `who`
-       * # </weight>
        **/
       setBalance: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, newFree: Compact<u128> | AnyNumber | Uint8Array, newReserved: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, Compact<u128>, Compact<u128>]>;
       /**
@@ -75,8 +65,6 @@
        * - `transfer_keep_alive` works the same way as `transfer`, but has an additional check
        * that the transfer will not kill the origin account.
        * ---------------------------------
-       * - Base Weight: 73.64 µs, worst case scenario (account created, account removed)
-       * - DB Weight: 1 Read and 1 Write to destination account
        * - Origin account is already in memory, so no DB operations for them.
        * # </weight>
        **/
@@ -108,11 +96,6 @@
        * 99% of the time you want [`transfer`] instead.
        * 
        * [`transfer`]: struct.Pallet.html#method.transfer
-       * # <weight>
-       * - Cheaper than transfer because account cannot be killed.
-       * - Base Weight: 51.4 µs
-       * - DB Weight: 1 Read and 1 Write to dest (sender is in overlay already)
-       * #</weight>
        **/
       transferKeepAlive: AugmentedSubmittable<(dest: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, value: Compact<u128> | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, Compact<u128>]>;
       /**
@@ -197,6 +180,20 @@
     };
     inflation: {
       /**
+       * This method sets the inflation start date. Can be only called once.
+       * Inflation start block can be backdated and will catch up. The method will create Treasury
+       * account if it does not exist and perform the first inflation deposit.
+       * 
+       * # Permissions
+       * 
+       * * Root
+       * 
+       * # Arguments
+       * 
+       * * inflation_start_relay_block: The relay chain block at which inflation should start
+       **/
+      startInflation: AugmentedSubmittable<(inflationStartRelayBlock: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u32]>;
+      /**
        * Generic tx
        **/
       [key: string]: SubmittableExtrinsicFunction<ApiType>;
@@ -374,7 +371,7 @@
        * - Weight of derivative `call` execution + 10,000.
        * # </weight>
        **/
-       sudo: AugmentedSubmittable<(call: Call) => SubmittableExtrinsic<ApiType>, [Call]>;
+      sudo: AugmentedSubmittable<(call: Call | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Call]>;
       /**
        * Authenticates the sudo key and dispatches a function call with `Signed` origin from
        * a given account.
@@ -388,7 +385,7 @@
        * - Weight of derivative `call` execution + 10,000.
        * # </weight>
        **/
-      sudoAs: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, ) => SubmittableExtrinsic<ApiType>, [MultiAddress, Call]>;
+      sudoAs: AugmentedSubmittable<(who: MultiAddress | { Id: any } | { Index: any } | { Raw: any } | { Address32: any } | { Address20: any } | string | Uint8Array, call: Call | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [MultiAddress, Call]>;
       /**
        * Authenticates the sudo key and dispatches a function call with `Root` origin.
        * This function does not check the weight of the call, and instead allows the
@@ -401,7 +398,7 @@
        * - The weight of this call is defined by the caller.
        * # </weight>
        **/
-       sudoUncheckedWeight: AugmentedSubmittable<(call: Call, weight: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Call, u64]>;
+      sudoUncheckedWeight: AugmentedSubmittable<(call: Call | string | Uint8Array, weight: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Call, u64]>;
       /**
        * Generic tx
        **/
@@ -417,24 +414,10 @@
        * 
        * **NOTE:** We rely on the Root origin to provide us the number of subkeys under
        * the prefix we are removing to accurately calculate the weight of this function.
-       * 
-       * # <weight>
-       * - `O(P)` where `P` amount of keys with prefix `prefix`
-       * - `P` storage deletions.
-       * - Base Weight: 0.834 * P µs
-       * - Writes: Number of subkeys + 1
-       * # </weight>
        **/
       killPrefix: AugmentedSubmittable<(prefix: Bytes | string | Uint8Array, subkeys: u32 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes, u32]>;
       /**
        * Kill some items from storage.
-       * 
-       * # <weight>
-       * - `O(IK)` where `I` length of `keys` and `K` length of one key
-       * - `I` storage deletions.
-       * - Base Weight: .378 * i µs
-       * - Writes: Number of items
-       * # </weight>
        **/
       killStorage: AugmentedSubmittable<(keys: Vec<Bytes> | (Bytes | string | Uint8Array)[]) => SubmittableExtrinsic<ApiType>, [Vec<Bytes>]>;
       /**
@@ -454,19 +437,6 @@
        * # </weight>
        **/
       remarkWithEvent: AugmentedSubmittable<(remark: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>;
-      /**
-       * Set the new changes trie configuration.
-       * 
-       * # <weight>
-       * - `O(1)`
-       * - 1 storage write or delete (codec `O(1)`).
-       * - 1 call to `deposit_log`: Uses `append` API, so O(1)
-       * - Base Weight: 7.218 µs
-       * - DB Weight:
-       * - Writes: Changes Trie, System Digest
-       * # </weight>
-       **/
-      setChangesTrieConfig: AugmentedSubmittable<(changesTrieConfig: Option<SpCoreChangesTrieChangesTrieConfiguration> | null | object | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Option<SpCoreChangesTrieChangesTrieConfiguration>]>;
       /**
        * Set the new runtime code.
        * 
@@ -496,25 +466,10 @@
       setCodeWithoutChecks: AugmentedSubmittable<(code: Bytes | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Bytes]>;
       /**
        * Set the number of pages in the WebAssembly environment's heap.
-       * 
-       * # <weight>
-       * - `O(1)`
-       * - 1 storage write.
-       * - Base Weight: 1.405 µs
-       * - 1 write to HEAP_PAGES
-       * - 1 digest item
-       * # </weight>
        **/
       setHeapPages: AugmentedSubmittable<(pages: u64 | AnyNumber | Uint8Array) => SubmittableExtrinsic<ApiType>, [u64]>;
       /**
        * Set some items of storage.
-       * 
-       * # <weight>
-       * - `O(I)` where `I` length of `items`
-       * - `I` storage writes (`O(1)`).
-       * - Base Weight: 0.568 * i µs
-       * - Writes: Number of items
-       * # </weight>
        **/
       setStorage: AugmentedSubmittable<(items: Vec<ITuple<[Bytes, Bytes]>> | ([Bytes | string | Uint8Array, Bytes | string | Uint8Array])[]) => SubmittableExtrinsic<ApiType>, [Vec<ITuple<[Bytes, Bytes]>>]>;
       /**
@@ -718,6 +673,12 @@
        **/
       createCollection: AugmentedSubmittable<(collectionName: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], collectionDescription: Vec<u16> | (u16 | AnyNumber | Uint8Array)[], tokenPrefix: Bytes | string | Uint8Array, mode: UpDataStructsCollectionMode | { NFT: any } | { Fungible: any } | { ReFungible: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [Vec<u16>, Vec<u16>, Bytes, UpDataStructsCollectionMode]>;
       /**
+       * This method creates a collection
+       * 
+       * Prefer it to deprecated [`created_collection`] method
+       **/
+      createCollectionEx: AugmentedSubmittable<(data: UpDataStructsCreateCollectionData | { mode?: any; access?: any; name?: any; description?: any; tokenPrefix?: any; offchainSchema?: any; schemaVersion?: any; pendingSponsor?: any; limits?: any; variableOnChainSchema?: any; constOnChainSchema?: any; metaUpdatePermission?: any } | string | Uint8Array) => SubmittableExtrinsic<ApiType>, [UpDataStructsCreateCollectionData]>;
+      /**
        * This method creates a concrete instance of NFT Collection created with CreateCollection method.
        * 
        * # Permissions
modifiedtests/src/interfaces/augment-types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/augment-types.ts
+++ b/tests/src/interfaces/augment-types.ts
@@ -3,7 +3,7 @@
 
 import type { EthereumBlock, EthereumLog, EthereumReceipt, EthereumTransactionLegacyTransaction, EvmCoreErrorExitReason, FpRpcTransactionStatus } from './ethereum';
 import type { CumulusPalletDmpQueueConfigData, CumulusPalletDmpQueuePageIndexData, CumulusPalletParachainSystemRelayStateSnapshotMessagingStateSnapshot, CumulusPalletXcmpQueueInboundStatus, CumulusPalletXcmpQueueOutboundStatus, CumulusPalletXcmpQueueQueueConfigData, CumulusPrimitivesParachainInherentParachainInherentData, PolkadotParachainPrimitivesXcmpMessageFormat, PolkadotPrimitivesV1AbridgedHostConfiguration, PolkadotPrimitivesV1PersistedValidationData } from './polkadot';
-import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
+import type { PalletCommonAccountBasicCrossAccountIdRepr, PalletNonfungibleItemData, PalletRefungibleItemData, PalletUnqSchedulerCallSpec, PalletUnqSchedulerReleases, PalletUnqSchedulerScheduledV2, UpDataStructsAccessMode, UpDataStructsCollection, UpDataStructsCollectionId, UpDataStructsCollectionLimits, UpDataStructsCollectionMode, UpDataStructsCollectionStats, UpDataStructsCreateCollectionData, UpDataStructsCreateItemData, UpDataStructsMetaUpdatePermission, UpDataStructsSchemaVersion, UpDataStructsSponsorshipState, UpDataStructsTokenId } from './unique';
 import type { BitVec, Bool, Bytes, Data, I128, I16, I256, I32, I64, I8, Json, Null, Raw, StorageKey, Text, Type, U128, U16, U256, U32, U64, U8, USize, bool, i128, i16, i256, i32, i64, i8, u128, u16, u256, u32, u64, u8, usize } from '@polkadot/types';
 import type { AssetApproval, AssetApprovalKey, AssetBalance, AssetDestroyWitness, AssetDetails, AssetMetadata, TAssetBalance, TAssetDepositBalance } from '@polkadot/types/interfaces/assets';
 import type { BlockAttestations, IncludedBlocks, MoreAttestations } from '@polkadot/types/interfaces/attestations';
@@ -1021,6 +1021,7 @@
     UpDataStructsCollectionLimits: UpDataStructsCollectionLimits;
     UpDataStructsCollectionMode: UpDataStructsCollectionMode;
     UpDataStructsCollectionStats: UpDataStructsCollectionStats;
+    UpDataStructsCreateCollectionData: UpDataStructsCreateCollectionData;
     UpDataStructsCreateItemData: UpDataStructsCreateItemData;
     UpDataStructsMetaUpdatePermission: UpDataStructsMetaUpdatePermission;
     UpDataStructsSchemaVersion: UpDataStructsSchemaVersion;
modifiedtests/src/interfaces/unique/definitions.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/definitions.ts
+++ b/tests/src/interfaces/unique/definitions.ts
@@ -67,6 +67,20 @@
       constOnChainSchema: 'Vec<u8>',
       metaUpdatePermission: 'UpDataStructsMetaUpdatePermission',
     },
+    UpDataStructsCreateCollectionData: {
+      mode: 'UpDataStructsCollectionMode',
+      access: 'Option<UpDataStructsAccessMode>',
+      name: 'Vec<u16>',
+      description: 'Vec<u16>',
+      tokenPrefix: 'Vec<u8>',
+      offchainSchema: 'Vec<u8>',
+      schemaVersion: 'Option<UpDataStructsSchemaVersion>',
+      pendingSponsor: 'Option<AccountId>',
+      limits: 'Option<UpDataStructsCollectionLimits>',
+      variableOnChainSchema: 'Vec<u8>',
+      constOnChainSchema: 'Vec<u8>',
+      metaUpdatePermission: 'Option<UpDataStructsMetaUpdatePermission>',
+    },
     UpDataStructsCollectionStats: {
       created: 'u32',
       destroyed: 'u32',
@@ -76,7 +90,13 @@
     UpDataStructsTokenId: 'u32',
     PalletNonfungibleItemData: mkDummy('NftItemData'),
     PalletRefungibleItemData: mkDummy('RftItemData'),
-    UpDataStructsCollectionMode: mkDummy('CollectionMode'),
+    UpDataStructsCollectionMode: {
+      _enum: {
+        NFT: null,
+        Fungible: 'u32',
+        ReFungible: null,
+      },
+    },
     UpDataStructsCreateItemData: mkDummy('CreateItemData'),
     UpDataStructsCollectionLimits: {
       accountTokenOwnershipLimit: 'Option<u32>',
@@ -101,7 +121,9 @@
     UpDataStructsAccessMode: {
       _enum: ['Normal', 'AllowList'],
     },
-    UpDataStructsSchemaVersion: mkDummy('SchemaVersion'),
+    UpDataStructsSchemaVersion: {
+      _enum: ['ImageURL', 'Unique'],
+    },
 
     PalletUnqSchedulerScheduledV2: mkDummy('ScheduledV2'),
     PalletUnqSchedulerCallSpec: mkDummy('CallSpec'),
modifiedtests/src/interfaces/unique/types.tsdiffbeforeafterboth
--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -77,8 +77,11 @@
 }
 
 /** @name UpDataStructsCollectionMode */
-export interface UpDataStructsCollectionMode extends Struct {
-  readonly dummyCollectionMode: u32;
+export interface UpDataStructsCollectionMode extends Enum {
+  readonly isNft: boolean;
+  readonly isFungible: boolean;
+  readonly asFungible: u32;
+  readonly isReFungible: boolean;
 }
 
 /** @name UpDataStructsCollectionStats */
@@ -88,6 +91,22 @@
   readonly alive: u32;
 }
 
+/** @name UpDataStructsCreateCollectionData */
+export interface UpDataStructsCreateCollectionData extends Struct {
+  readonly mode: UpDataStructsCollectionMode;
+  readonly access: Option<UpDataStructsAccessMode>;
+  readonly name: Vec<u16>;
+  readonly description: Vec<u16>;
+  readonly tokenPrefix: Bytes;
+  readonly offchainSchema: Bytes;
+  readonly schemaVersion: Option<UpDataStructsSchemaVersion>;
+  readonly pendingSponsor: Option<AccountId>;
+  readonly limits: Option<UpDataStructsCollectionLimits>;
+  readonly variableOnChainSchema: Bytes;
+  readonly constOnChainSchema: Bytes;
+  readonly metaUpdatePermission: Option<UpDataStructsMetaUpdatePermission>;
+}
+
 /** @name UpDataStructsCreateItemData */
 export interface UpDataStructsCreateItemData extends Struct {
   readonly dummyCreateItemData: u32;
@@ -101,8 +120,9 @@
 }
 
 /** @name UpDataStructsSchemaVersion */
-export interface UpDataStructsSchemaVersion extends Struct {
-  readonly dummySchemaVersion: u32;
+export interface UpDataStructsSchemaVersion extends Enum {
+  readonly isImageUrl: boolean;
+  readonly isUnique: boolean;
 }
 
 /** @name UpDataStructsSponsorshipState */
modifiedtests/src/substrate/substrate-api.tsdiffbeforeafterboth
--- a/tests/src/substrate/substrate-api.ts
+++ b/tests/src/substrate/substrate-api.ts
@@ -95,6 +95,32 @@
   return TransactionStatus.Fail;
 }
 
+export function executeTransaction(api: ApiPromise, sender: IKeyringPair, transaction: SubmittableExtrinsic<'promise'>): Promise<EventRecord[]> {
+  return new Promise(async (res, rej) => {
+    try {
+      await transaction.signAndSend(sender, ({events, status}) => {
+        if (!status.isInBlock && !status.isFinalized) return;
+        for (const {event} of events) {
+          if (api.events.system.ExtrinsicSuccess.is(event)) {
+            res(events);
+          } else if (api.events.system.ExtrinsicFailed.is(event)) {
+            const {data: [error]} = event;
+            if (error.isModule) {
+              const decoded = api.registry.findMetaError(error.asModule);
+              const {method, section} = decoded;
+              rej(new Error(`${section}.${method}`));
+            } else {
+              rej(new Error(error.toString()));
+            }
+          }
+        }
+      });
+    } catch (e) {
+      rej(e);
+    }
+  });
+}
+
 export function
 submitTransactionAsync(sender: IKeyringPair, transaction: SubmittableExtrinsic<ApiTypes>): Promise<EventRecord[]> {
   /* eslint no-async-promise-executor: "off" */
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {UpDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23  Substrate: string,24} | {25  Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28  if (typeof input === 'string') {29    if (input.length === 48 || input.length === 47) {30      return {Substrate: input};31    } else if (input.length === 42 && input.startsWith('0x')) {32      return {Ethereum: input.toLowerCase()};33    } else if (input.length === 40 && !input.startsWith('0x')) {34      return {Ethereum: '0x' + input.toLowerCase()};35    } else {36      throw new Error(`Unknown address format: "${input}"`);37    }38  }39  if ('address' in input) {40    return {Substrate: input.address};41  }42  if ('Ethereum' in input) {43    return {44      Ethereum: input.Ethereum.toLowerCase(),45    };46  } else if ('ethereum' in input) {47    return {48      Ethereum: (input as any).ethereum.toLowerCase(),49    };50  } else if ('Substrate' in input) {51    return input;52  }else if ('substrate' in input) {53    return {54      Substrate: (input as any).substrate,55    };56  }5758  // AccountId59  return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62  input = normalizeAccountId(input);63  if ('Substrate' in input) {64    return input.Substrate;65  } else {66    return evmToAddress(input.Ethereum);67  }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78  success: boolean,79};8081interface CreateCollectionResult {82  success: boolean;83  collectionId: number;84}8586interface CreateItemResult {87  success: boolean;88  collectionId: number;89  itemId: number;90  recipient?: CrossAccountId;91}9293interface TransferResult {94  success: boolean;95  collectionId: number;96  itemId: number;97  sender?: CrossAccountId;98  recipient?: CrossAccountId;99  value: bigint;100}101102interface IReFungibleOwner {103  fraction: BN;104  owner: number[];105}106107interface IGetMessage {108  checkMsgUnqMethod: string;109  checkMsgTrsMethod: string;110  checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114  value: number;115}116117export interface IChainLimits {118  collectionNumbersLimit: number;119	accountTokenOwnershipLimit: number;120	collectionsAdminsLimit: number;121	customDataLimit: number;122	nftSponsorTransferTimeout: number;123	fungibleSponsorTransferTimeout: number;124	refungibleSponsorTransferTimeout: number;125	offchainSchemaLimit: number;126	variableOnChainSchemaLimit: number;127	constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131  owner: IReFungibleOwner[];132  constData: number[];133  variableData: number[];134}135136export function uniqueEventMessage(events: EventRecord[]): IGetMessage {137  let checkMsgUnqMethod = '';138  let checkMsgTrsMethod = '';139  let checkMsgSysMethod = '';140  events.forEach(({event: {method, section}}) => {141    if (section === 'common') {142      checkMsgUnqMethod = method;143    } else if (section === 'treasury') {144      checkMsgTrsMethod = method;145    } else if (section === 'system') {146      checkMsgSysMethod = method;147    } else { return null; }148  });149  const result: IGetMessage = {150    checkMsgUnqMethod,151    checkMsgTrsMethod,152    checkMsgSysMethod,153  };154  return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158  const result: GenericResult = {159    success: false,160  };161  events.forEach(({event: {method}}) => {162    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);163    if (method === 'ExtrinsicSuccess') {164      result.success = true;165    }166  });167  return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173  let success = false;174  let collectionId = 0;175  events.forEach(({event: {data, method, section}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method == 'ExtrinsicSuccess') {178      success = true;179    } else if ((section == 'common') && (method == 'CollectionCreated')) {180      collectionId = parseInt(data[0].toString(), 10);181    }182  });183  const result: CreateCollectionResult = {184    success,185    collectionId,186  };187  return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191  let success = false;192  let collectionId = 0;193  let itemId = 0;194  let recipient;195  events.forEach(({event: {data, method, section}}) => {196    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);197    if (method == 'ExtrinsicSuccess') {198      success = true;199    } else if ((section == 'common') && (method == 'ItemCreated')) {200      collectionId = parseInt(data[0].toString(), 10);201      itemId = parseInt(data[1].toString(), 10);202      recipient = normalizeAccountId(data[2].toJSON() as any);203    }204  });205  const result: CreateItemResult = {206    success,207    collectionId,208    itemId,209    recipient,210  };211  return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215  const result: TransferResult = {216    success: false,217    collectionId: 0,218    itemId: 0,219    value: 0n,220  };221222  events.forEach(({event: {data, method, section}}) => {223    if (method === 'ExtrinsicSuccess') {224      result.success = true;225    } else if (section === 'common' && method === 'Transfer') {226      result.collectionId = +data[0].toString();227      result.itemId = +data[1].toString();228      result.sender = normalizeAccountId(data[2].toJSON() as any);229      result.recipient = normalizeAccountId(data[3].toJSON() as any);230      result.value = BigInt(data[4].toString());231    }232  });233234  return result;235}236237interface Nft {238  type: 'NFT';239}240241interface Fungible {242  type: 'Fungible';243  decimalPoints: number;244}245246interface ReFungible {247  type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253  mode: CollectionMode,254  name: string,255  description: string,256  tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260  description: 'description',261  mode: {type: 'NFT'},262  name: 'name',263  tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269  let collectionId = 0;270  await usingApi(async (api) => {271    // Get number of collections before the transaction272    const collectionCountBefore = await getCreatedCollectionCount(api);273274    // Run the CreateCollection transaction275    const alicePrivateKey = privateKey('//Alice');276277    let modeprm = {};278    if (mode.type === 'NFT') {279      modeprm = {nft: null};280    } else if (mode.type === 'Fungible') {281      modeprm = {fungible: mode.decimalPoints};282    } else if (mode.type === 'ReFungible') {283      modeprm = {refungible: null};284    }285286    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287    const events = await submitTransactionAsync(alicePrivateKey, tx);288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const collectionCountAfter = await getCreatedCollectionCount(api);292293    // Get the collection294    const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296    // What to expect297    // tslint:disable-next-line:no-unused-expression298    expect(result.success).to.be.true;299    expect(result.collectionId).to.be.equal(collectionCountAfter);300    // tslint:disable-next-line:no-unused-expression301    expect(collection).to.be.not.null;302    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308    collectionId = result.collectionId;309  });310311  return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317  let modeprm = {};318  if (mode.type === 'NFT') {319    modeprm = {nft: null};320  } else if (mode.type === 'Fungible') {321    modeprm = {fungible: mode.decimalPoints};322  } else if (mode.type === 'ReFungible') {323    modeprm = {refungible: null};324  }325326  await usingApi(async (api) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334    const result = getCreateCollectionResult(events);335336    // Get number of collections after the transaction337    const collectionCountAfter = await getCreatedCollectionCount(api);338339    // What to expect340    // tslint:disable-next-line:no-unused-expression341    expect(result.success).to.be.false;342    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343  });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347  let bal = 0n;348  let unused;349  do {350    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351    const keyring = new Keyring({type: 'sr25519'});352    unused = keyring.addFromUri(`//${randomSeed}`);353    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354  } while (bal !== 0n);355  return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367  const totalNumber = await getCreatedCollectionCount(api);368  const newCollection: number = totalNumber + 1;369  return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373  let success = false;374  events.forEach(({event: {method}}) => {375    if (method == 'ExtrinsicSuccess') {376      success = true;377    }378  });379  return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383  await usingApi(async (api) => {384    // Run the DestroyCollection transaction385    const alicePrivateKey = privateKey(senderSeed);386    const tx = api.tx.unique.destroyCollection(collectionId);387    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388  });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392  await usingApi(async (api) => {393    // Run the DestroyCollection transaction394    const alicePrivateKey = privateKey(senderSeed);395    const tx = api.tx.unique.destroyCollection(collectionId);396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getDestroyResult(events);398    expect(result).to.be.true;399400    // What to expect401    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402  });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);408    const events = await submitTransactionAsync(sender, tx);409    const result = getGenericResult(events);410411    expect(result.success).to.be.true;412  });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416  await usingApi(async (api) => {417    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);418    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419    const result = getGenericResult(events);420421    expect(result.success).to.be.false;422  });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426  await usingApi(async (api) => {427428    // Run the transaction429    const senderPrivateKey = privateKey(sender);430    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);431    const events = await submitTransactionAsync(senderPrivateKey, tx);432    const result = getGenericResult(events);433434    // Get the collection435    const collection = await queryCollectionExpectSuccess(api, collectionId);436437    // What to expect438    expect(result.success).to.be.true;439    expect(collection.sponsorship.toJSON()).to.deep.equal({440      unconfirmed: sponsor,441    });442  });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446  await usingApi(async (api) => {447448    // Run the transaction449    const alicePrivateKey = privateKey(sender);450    const tx = api.tx.unique.removeCollectionSponsor(collectionId);451    const events = await submitTransactionAsync(alicePrivateKey, tx);452    const result = getGenericResult(events);453454    // Get the collection455    const collection = await queryCollectionExpectSuccess(api, collectionId);456457    // What to expect458    expect(result.success).to.be.true;459    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460  });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464  await usingApi(async (api) => {465466    // Run the transaction467    const alicePrivateKey = privateKey(senderSeed);468    const tx = api.tx.unique.removeCollectionSponsor(collectionId);469    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470  });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const alicePrivateKey = privateKey(senderSeed);478    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480  });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484  await usingApi(async (api) => {485486    // Run the transaction487    const sender = privateKey(senderSeed);488    const tx = api.tx.unique.confirmSponsorship(collectionId);489    const events = await submitTransactionAsync(sender, tx);490    const result = getGenericResult(events);491492    // Get the collection493    const collection = await queryCollectionExpectSuccess(api, collectionId);494495    // What to expect496    expect(result.success).to.be.true;497    expect(collection.sponsorship.toJSON()).to.be.deep.equal({498      confirmed: sender.address,499    });500  });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505  await usingApi(async (api) => {506507    // Run the transaction508    const sender = privateKey(senderSeed);509    const tx = api.tx.unique.confirmSponsorship(collectionId);510    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511  });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516  await usingApi(async (api) => {517    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);518    const events = await submitTransactionAsync(sender, tx);519    const result = getGenericResult(events);520521    expect(result.success).to.be.true;522  });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(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 expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530    const result = getGenericResult(events);531532    expect(result.success).to.be.false;533  });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537  await usingApi(async (api) => {538    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);539    const events = await submitTransactionAsync(sender, tx);540    const result = getGenericResult(events);541542    expect(result.success).to.be.true;543  });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550    const result = getGenericResult(events);551552    expect(result.success).to.be.false;553  });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558  await usingApi(async (api) => {559560    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);561    const events = await submitTransactionAsync(sender, tx);562    const result = getGenericResult(events);563564    expect(result.success).to.be.true;565  });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570  await usingApi(async (api) => {571572    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);573    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574    const result = getGenericResult(events);575576    expect(result.success).to.be.false;577  });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581  await usingApi(async (api) => {582    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);583    const events = await submitTransactionAsync(sender, tx);584    const result = getGenericResult(events);585586    expect(result.success).to.be.true;587  });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591  await usingApi(async (api) => {592    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594    const result = getGenericResult(events);595596    expect(result.success).to.be.false;597  });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601  await usingApi(async (api) => {602    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);603    const events = await submitTransactionAsync(sender, tx);604    const result = getGenericResult(events);605606    expect(result.success).to.be.true;607  });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611  let allowlisted = false;612  await usingApi(async (api) => {613    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;614  });615  return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619  await usingApi(async (api) => {620    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());621    const events = await submitTransactionAsync(sender, tx);622    const result = getGenericResult(events);623624    expect(result.success).to.be.true;625  });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629  await usingApi(async (api) => {630    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    expect(result.success).to.be.true;635  });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());641    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642    const result = getGenericResult(events);643644    expect(result.success).to.be.false;645  });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662  });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666  await usingApi(async (api) => {667    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679  });680}681682export interface CreateFungibleData {683  readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690  NFT: CreateNftData;691} | {692  Fungible: CreateFungibleData;693} | {694  ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698  await usingApi(async (api) => {699    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700    // if burning token by admin - use adminButnItemExpectSuccess701    expect(balanceBefore >= BigInt(value)).to.be.true;702703    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);704    const events = await submitTransactionAsync(sender, tx);705    const result = getGenericResult(events);706    expect(result.success).to.be.true;707708    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710  });711}712713export async function714approveExpectSuccess(715  collectionId: number,716  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718  await usingApi(async (api: ApiPromise) => {719    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720    const events = await submitTransactionAsync(owner, approveUniqueTx);721    const result = getGenericResult(events);722    expect(result.success).to.be.true;723724    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725  });726}727728export async function adminApproveFromExpectSuccess(729  collectionId: number,730  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732  await usingApi(async (api: ApiPromise) => {733    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734    const events = await submitTransactionAsync(admin, approveUniqueTx);735    const result = getGenericResult(events);736    expect(result.success).to.be.true;737738    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739  });740}741742export async function743transferFromExpectSuccess(744  collectionId: number,745  tokenId: number,746  accountApproved: IKeyringPair,747  accountFrom: IKeyringPair | CrossAccountId,748  accountTo: IKeyringPair | CrossAccountId,749  value: number | bigint = 1,750  type = 'NFT',751) {752  await usingApi(async (api: ApiPromise) => {753    const to = normalizeAccountId(accountTo);754    let balanceBefore = 0n;755    if (type === 'Fungible') {756      balanceBefore = await getBalance(api, collectionId, to, tokenId);757    }758    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759    const events = await submitTransactionAsync(accountApproved, transferFromTx);760    const result = getCreateItemResult(events);761    // tslint:disable-next-line:no-unused-expression762    expect(result.success).to.be.true;763    if (type === 'NFT') {764      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765    }766    if (type === 'Fungible') {767      const balanceAfter = await getBalance(api, collectionId, to, tokenId);768      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769    }770    if (type === 'ReFungible') {771      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772    }773  });774}775776export async function777transferFromExpectFail(778  collectionId: number,779  tokenId: number,780  accountApproved: IKeyringPair,781  accountFrom: IKeyringPair,782  accountTo: IKeyringPair,783  value: number | bigint = 1,784) {785  await usingApi(async (api: ApiPromise) => {786    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788    const result = getCreateCollectionResult(events);789    // tslint:disable-next-line:no-unused-expression790    expect(result.success).to.be.false;791  });792}793794/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {796  return new Promise<number>(async (resolve) => {797    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798      unsubscribe();799      resolve(head.number.toNumber());800    });801  });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805  await usingApi(async (api) => {806    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));807    const events = await submitTransactionAsync(sender, changeAdminTx);808    const result = getCreateCollectionResult(events);809    expect(result.success).to.be.true;810  });811}812813export async function814getFreeBalance(account: IKeyringPair) : Promise<bigint>815{816  let balance = 0n;817  await usingApi(async (api) => {818    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());819  });820821  return balance;822}823824export async function825scheduleTransferExpectSuccess(826  collectionId: number,827  tokenId: number,828  sender: IKeyringPair,829  recipient: IKeyringPair,830  value: number | bigint = 1,831  blockSchedule: number,832) {833  await usingApi(async (api: ApiPromise) => {834    const blockNumber: number | undefined = await getBlockNumber(api);835    const expectedBlockNumber = blockNumber + blockSchedule;836837    expect(blockNumber).to.be.greaterThan(0);838    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840841    await submitTransactionAsync(sender, scheduleTx);842843    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();844845    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847    // sleep for 4 blocks848    await waitNewBlocks(blockSchedule + 1);849850    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854  });855}856857858export async function859transferExpectSuccess(860  collectionId: number,861  tokenId: number,862  sender: IKeyringPair,863  recipient: IKeyringPair | CrossAccountId,864  value: number | bigint = 1,865  type = 'NFT',866) {867  await usingApi(async (api: ApiPromise) => {868    const to = normalizeAccountId(recipient);869870    let balanceBefore = 0n;871    if (type === 'Fungible') {872      balanceBefore = await getBalance(api, collectionId, to, tokenId);873    }874    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);875    const events = await submitTransactionAsync(sender, transferTx);876    const result = getTransferResult(events);877    // tslint:disable-next-line:no-unused-expression878    expect(result.success).to.be.true;879    expect(result.collectionId).to.be.equal(collectionId);880    expect(result.itemId).to.be.equal(tokenId);881    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));882    expect(result.recipient).to.be.deep.equal(to);883    expect(result.value).to.be.equal(BigInt(value));884    if (type === 'NFT') {885      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);886    }887    if (type === 'Fungible') {888      const balanceAfter = await getBalance(api, collectionId, to, tokenId);889      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890    }891    if (type === 'ReFungible') {892      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;893    }894  });895}896897export async function898transferExpectFailure(899  collectionId: number,900  tokenId: number,901  sender: IKeyringPair,902  recipient: IKeyringPair,903  value: number | bigint = 1,904) {905  await usingApi(async (api: ApiPromise) => {906    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);907    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;908    const result = getGenericResult(events);909    // if (events && Array.isArray(events)) {910    //   const result = getCreateCollectionResult(events);911    // tslint:disable-next-line:no-unused-expression912    expect(result.success).to.be.false;913    //}914  });915}916917export async function918approveExpectFail(919  collectionId: number,920  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,921) {922  await usingApi(async (api: ApiPromise) => {923    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);924    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;925    const result = getCreateCollectionResult(events);926    // tslint:disable-next-line:no-unused-expression927    expect(result.success).to.be.false;928  });929}930931export async function getBalance(932  api: ApiPromise,933  collectionId: number,934  owner: string | CrossAccountId,935  token: number,936): Promise<bigint> {937  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();938}939export async function getTokenOwner(940  api: ApiPromise,941  collectionId: number,942  token: number,943): Promise<CrossAccountId> {944  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);945}946export async function isTokenExists(947  api: ApiPromise,948  collectionId: number,949  token: number,950): Promise<boolean> {951  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();952}953export async function getLastTokenId(954  api: ApiPromise,955  collectionId: number,956): Promise<number> {957  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();958}959export async function getAdminList(960  api: ApiPromise,961  collectionId: number,962): Promise<string[]> {963  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;964}965export async function getVariableMetadata(966  api: ApiPromise,967  collectionId: number,968  tokenId: number,969): Promise<number[]> {970  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];971}972export async function getConstMetadata(973  api: ApiPromise,974  collectionId: number,975  tokenId: number,976): Promise<number[]> {977  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];978}979980export async function createFungibleItemExpectSuccess(981  sender: IKeyringPair,982  collectionId: number,983  data: CreateFungibleData,984  owner: CrossAccountId | string = sender.address,985) {986  return await usingApi(async (api) => {987    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});988989    const events = await submitTransactionAsync(sender, tx);990    const result = getCreateItemResult(events);991992    expect(result.success).to.be.true;993    return result.itemId;994  });995}996997export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {998  let newItemId = 0;999  await usingApi(async (api) => {1000    const to = normalizeAccountId(owner);1001    const itemCountBefore = await getLastTokenId(api, collectionId);1002    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10031004    let tx;1005    if (createMode === 'Fungible') {1006      const createData = {fungible: {value: 10}};1007      tx = api.tx.unique.createItem(collectionId, to, createData as any);1008    } else if (createMode === 'ReFungible') {1009      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1010      tx = api.tx.unique.createItem(collectionId, to, createData as any);1011    } else {1012      const createData = {nft: {const_data: [], variable_data: []}};1013      tx = api.tx.unique.createItem(collectionId, to, createData as any);1014    }10151016    const events = await submitTransactionAsync(sender, tx);1017    const result = getCreateItemResult(events);10181019    const itemCountAfter = await getLastTokenId(api, collectionId);1020    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10211022    // What to expect1023    // tslint:disable-next-line:no-unused-expression1024    expect(result.success).to.be.true;1025    if (createMode === 'Fungible') {1026      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1027    } else {1028      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1029    }1030    expect(collectionId).to.be.equal(result.collectionId);1031    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1032    expect(to).to.be.deep.equal(result.recipient);1033    newItemId = result.itemId;1034  });1035  return newItemId;1036}10371038export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1039  await usingApi(async (api) => {1040    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10411042    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1043    const result = getCreateItemResult(events);10441045    expect(result.success).to.be.false;1046  });1047}10481049export async function setPublicAccessModeExpectSuccess(1050  sender: IKeyringPair, collectionId: number,1051  accessMode: 'Normal' | 'AllowList',1052) {1053  await usingApi(async (api) => {10541055    // Run the transaction1056    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1057    const events = await submitTransactionAsync(sender, tx);1058    const result = getGenericResult(events);10591060    // Get the collection1061    const collection = await queryCollectionExpectSuccess(api, collectionId);10621063    // What to expect1064    // tslint:disable-next-line:no-unused-expression1065    expect(result.success).to.be.true;1066    expect(collection.access.toHuman()).to.be.equal(accessMode);1067  });1068}10691070export async function setPublicAccessModeExpectFail(1071  sender: IKeyringPair, collectionId: number,1072  accessMode: 'Normal' | 'AllowList',1073) {1074  await usingApi(async (api) => {10751076    // Run the transaction1077    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1078    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079    const result = getGenericResult(events);10801081    // What to expect1082    // tslint:disable-next-line:no-unused-expression1083    expect(result.success).to.be.false;1084  });1085}10861087export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1088  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1089}10901091export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1092  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1093}10941095export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1096  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1097}10981099export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1100  await usingApi(async (api) => {11011102    // Run the transaction1103    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1104    const events = await submitTransactionAsync(sender, tx);1105    const result = getGenericResult(events);1106    expect(result.success).to.be.true;11071108    // Get the collection1109    const collection = await queryCollectionExpectSuccess(api, collectionId);11101111    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1112  });1113}11141115export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1116  await setMintPermissionExpectSuccess(sender, collectionId, true);1117}11181119export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1120  await usingApi(async (api) => {1121    // Run the transaction1122    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1123    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1124    const result = getCreateCollectionResult(events);1125    // tslint:disable-next-line:no-unused-expression1126    expect(result.success).to.be.false;1127  });1128}11291130export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1131  await usingApi(async (api) => {1132    // Run the transaction1133    const tx = api.tx.unique.setChainLimits(limits);1134    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1135    const result = getCreateCollectionResult(events);1136    // tslint:disable-next-line:no-unused-expression1137    expect(result.success).to.be.false;1138  });1139}11401141export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1142  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1143}11441145export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1146  await usingApi(async (api) => {1147    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11481149    // Run the transaction1150    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1151    const events = await submitTransactionAsync(sender, tx);1152    const result = getGenericResult(events);1153    expect(result.success).to.be.true;11541155    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1156  });1157}11581159export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1160  await usingApi(async (api) => {11611162    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11631164    // Run the transaction1165    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1166    const events = await submitTransactionAsync(sender, tx);1167    const result = getGenericResult(events);1168    expect(result.success).to.be.true;11691170    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1171  });1172}11731174export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1175  await usingApi(async (api) => {11761177    // Run the transaction1178    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1179    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1180    const result = getGenericResult(events);11811182    // What to expect1183    // tslint:disable-next-line:no-unused-expression1184    expect(result.success).to.be.false;1185  });1186}11871188export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1189  await usingApi(async (api) => {1190    // Run the transaction1191    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1192    const events = await submitTransactionAsync(sender, tx);1193    const result = getGenericResult(events);11941195    // What to expect1196    // tslint:disable-next-line:no-unused-expression1197    expect(result.success).to.be.true;1198  });1199}12001201export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1202  await usingApi(async (api) => {1203    // Run the transaction1204    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1205    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1206    const result = getGenericResult(events);12071208    // What to expect1209    // tslint:disable-next-line:no-unused-expression1210    expect(result.success).to.be.false;1211  });1212}12131214export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1215  : Promise<UpDataStructsCollection | null> => {1216  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1217};12181219export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1220  // set global object - collectionsCount1221  return (await api.rpc.unique.collectionStats()).created.toNumber();1222};12231224export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1225  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1226}12271228export async function waitNewBlocks(blocksCount = 1): Promise<void> {1229  await usingApi(async (api) => {1230    const promise = new Promise<void>(async (resolve) => {1231      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1232        if (blocksCount > 0) {1233          blocksCount--;1234        } else {1235          unsubscribe();1236          resolve();1237        }1238      });1239    });1240    return promise;1241  });1242}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {UpDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23  Substrate: string,24} | {25  Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28  if (typeof input === 'string') {29    if (input.length === 48 || input.length === 47) {30      return {Substrate: input};31    } else if (input.length === 42 && input.startsWith('0x')) {32      return {Ethereum: input.toLowerCase()};33    } else if (input.length === 40 && !input.startsWith('0x')) {34      return {Ethereum: '0x' + input.toLowerCase()};35    } else {36      throw new Error(`Unknown address format: "${input}"`);37    }38  }39  if ('address' in input) {40    return {Substrate: input.address};41  }42  if ('Ethereum' in input) {43    return {44      Ethereum: input.Ethereum.toLowerCase(),45    };46  } else if ('ethereum' in input) {47    return {48      Ethereum: (input as any).ethereum.toLowerCase(),49    };50  } else if ('Substrate' in input) {51    return input;52  } else if ('substrate' in input) {53    return {54      Substrate: (input as any).substrate,55    };56  }5758  // AccountId59  return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62  input = normalizeAccountId(input);63  if ('Substrate' in input) {64    return input.Substrate;65  } else {66    return evmToAddress(input.Ethereum);67  }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78  success: boolean,79};8081interface CreateCollectionResult {82  success: boolean;83  collectionId: number;84}8586interface CreateItemResult {87  success: boolean;88  collectionId: number;89  itemId: number;90  recipient?: CrossAccountId;91}9293interface TransferResult {94  success: boolean;95  collectionId: number;96  itemId: number;97  sender?: CrossAccountId;98  recipient?: CrossAccountId;99  value: bigint;100}101102interface IReFungibleOwner {103  fraction: BN;104  owner: number[];105}106107interface IGetMessage {108  checkMsgUnqMethod: string;109  checkMsgTrsMethod: string;110  checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114  value: number;115}116117export interface IChainLimits {118  collectionNumbersLimit: number;119  accountTokenOwnershipLimit: number;120  collectionsAdminsLimit: number;121  customDataLimit: number;122  nftSponsorTransferTimeout: number;123  fungibleSponsorTransferTimeout: number;124  refungibleSponsorTransferTimeout: number;125  offchainSchemaLimit: number;126  variableOnChainSchemaLimit: number;127  constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131  owner: IReFungibleOwner[];132  constData: number[];133  variableData: number[];134}135136export function uniqueEventMessage(events: EventRecord[]): IGetMessage {137  let checkMsgUnqMethod = '';138  let checkMsgTrsMethod = '';139  let checkMsgSysMethod = '';140  events.forEach(({event: {method, section}}) => {141    if (section === 'common') {142      checkMsgUnqMethod = method;143    } else if (section === 'treasury') {144      checkMsgTrsMethod = method;145    } else if (section === 'system') {146      checkMsgSysMethod = method;147    } else { return null; }148  });149  const result: IGetMessage = {150    checkMsgUnqMethod,151    checkMsgTrsMethod,152    checkMsgSysMethod,153  };154  return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158  const result: GenericResult = {159    success: false,160  };161  events.forEach(({event: {method}}) => {162    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);163    if (method === 'ExtrinsicSuccess') {164      result.success = true;165    }166  });167  return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173  let success = false;174  let collectionId = 0;175  events.forEach(({event: {data, method, section}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method == 'ExtrinsicSuccess') {178      success = true;179    } else if ((section == 'common') && (method == 'CollectionCreated')) {180      collectionId = parseInt(data[0].toString(), 10);181    }182  });183  const result: CreateCollectionResult = {184    success,185    collectionId,186  };187  return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191  let success = false;192  let collectionId = 0;193  let itemId = 0;194  let recipient;195  events.forEach(({event: {data, method, section}}) => {196    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);197    if (method == 'ExtrinsicSuccess') {198      success = true;199    } else if ((section == 'common') && (method == 'ItemCreated')) {200      collectionId = parseInt(data[0].toString(), 10);201      itemId = parseInt(data[1].toString(), 10);202      recipient = normalizeAccountId(data[2].toJSON() as any);203    }204  });205  const result: CreateItemResult = {206    success,207    collectionId,208    itemId,209    recipient,210  };211  return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215  const result: TransferResult = {216    success: false,217    collectionId: 0,218    itemId: 0,219    value: 0n,220  };221222  events.forEach(({event: {data, method, section}}) => {223    if (method === 'ExtrinsicSuccess') {224      result.success = true;225    } else if (section === 'common' && method === 'Transfer') {226      result.collectionId = +data[0].toString();227      result.itemId = +data[1].toString();228      result.sender = normalizeAccountId(data[2].toJSON() as any);229      result.recipient = normalizeAccountId(data[3].toJSON() as any);230      result.value = BigInt(data[4].toString());231    }232  });233234  return result;235}236237interface Nft {238  type: 'NFT';239}240241interface Fungible {242  type: 'Fungible';243  decimalPoints: number;244}245246interface ReFungible {247  type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253  mode: CollectionMode,254  name: string,255  description: string,256  tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260  description: 'description',261  mode: {type: 'NFT'},262  name: 'name',263  tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269  let collectionId = 0;270  await usingApi(async (api) => {271    // Get number of collections before the transaction272    const collectionCountBefore = await getCreatedCollectionCount(api);273274    // Run the CreateCollection transaction275    const alicePrivateKey = privateKey('//Alice');276277    let modeprm = {};278    if (mode.type === 'NFT') {279      modeprm = {nft: null};280    } else if (mode.type === 'Fungible') {281      modeprm = {fungible: mode.decimalPoints};282    } else if (mode.type === 'ReFungible') {283      modeprm = {refungible: null};284    }285286    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});287    const events = await submitTransactionAsync(alicePrivateKey, tx);288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const collectionCountAfter = await getCreatedCollectionCount(api);292293    // Get the collection294    const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296    // What to expect297    // tslint:disable-next-line:no-unused-expression298    expect(result.success).to.be.true;299    expect(result.collectionId).to.be.equal(collectionCountAfter);300    // tslint:disable-next-line:no-unused-expression301    expect(collection).to.be.not.null;302    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308    collectionId = result.collectionId;309  });310311  return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317  let modeprm = {};318  if (mode.type === 'NFT') {319    modeprm = {nft: null};320  } else if (mode.type === 'Fungible') {321    modeprm = {fungible: mode.decimalPoints};322  } else if (mode.type === 'ReFungible') {323    modeprm = {refungible: null};324  }325326  await usingApi(async (api) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});333    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334    const result = getCreateCollectionResult(events);335336    // Get number of collections after the transaction337    const collectionCountAfter = await getCreatedCollectionCount(api);338339    // What to expect340    // tslint:disable-next-line:no-unused-expression341    expect(result.success).to.be.false;342    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343  });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347  let bal = 0n;348  let unused;349  do {350    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351    const keyring = new Keyring({type: 'sr25519'});352    unused = keyring.addFromUri(`//${randomSeed}`);353    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354  } while (bal !== 0n);355  return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367  const totalNumber = await getCreatedCollectionCount(api);368  const newCollection: number = totalNumber + 1;369  return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373  let success = false;374  events.forEach(({event: {method}}) => {375    if (method == 'ExtrinsicSuccess') {376      success = true;377    }378  });379  return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383  await usingApi(async (api) => {384    // Run the DestroyCollection transaction385    const alicePrivateKey = privateKey(senderSeed);386    const tx = api.tx.unique.destroyCollection(collectionId);387    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388  });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392  await usingApi(async (api) => {393    // Run the DestroyCollection transaction394    const alicePrivateKey = privateKey(senderSeed);395    const tx = api.tx.unique.destroyCollection(collectionId);396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getDestroyResult(events);398    expect(result).to.be.true;399400    // What to expect401    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402  });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);408    const events = await submitTransactionAsync(sender, tx);409    const result = getGenericResult(events);410411    expect(result.success).to.be.true;412  });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416  await usingApi(async (api) => {417    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);418    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419    const result = getGenericResult(events);420421    expect(result.success).to.be.false;422  });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426  await usingApi(async (api) => {427428    // Run the transaction429    const senderPrivateKey = privateKey(sender);430    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);431    const events = await submitTransactionAsync(senderPrivateKey, tx);432    const result = getGenericResult(events);433434    // Get the collection435    const collection = await queryCollectionExpectSuccess(api, collectionId);436437    // What to expect438    expect(result.success).to.be.true;439    expect(collection.sponsorship.toJSON()).to.deep.equal({440      unconfirmed: sponsor,441    });442  });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446  await usingApi(async (api) => {447448    // Run the transaction449    const alicePrivateKey = privateKey(sender);450    const tx = api.tx.unique.removeCollectionSponsor(collectionId);451    const events = await submitTransactionAsync(alicePrivateKey, tx);452    const result = getGenericResult(events);453454    // Get the collection455    const collection = await queryCollectionExpectSuccess(api, collectionId);456457    // What to expect458    expect(result.success).to.be.true;459    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460  });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464  await usingApi(async (api) => {465466    // Run the transaction467    const alicePrivateKey = privateKey(senderSeed);468    const tx = api.tx.unique.removeCollectionSponsor(collectionId);469    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470  });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const alicePrivateKey = privateKey(senderSeed);478    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480  });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484  await usingApi(async (api) => {485486    // Run the transaction487    const sender = privateKey(senderSeed);488    const tx = api.tx.unique.confirmSponsorship(collectionId);489    const events = await submitTransactionAsync(sender, tx);490    const result = getGenericResult(events);491492    // Get the collection493    const collection = await queryCollectionExpectSuccess(api, collectionId);494495    // What to expect496    expect(result.success).to.be.true;497    expect(collection.sponsorship.toJSON()).to.be.deep.equal({498      confirmed: sender.address,499    });500  });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505  await usingApi(async (api) => {506507    // Run the transaction508    const sender = privateKey(senderSeed);509    const tx = api.tx.unique.confirmSponsorship(collectionId);510    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511  });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516  await usingApi(async (api) => {517    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);518    const events = await submitTransactionAsync(sender, tx);519    const result = getGenericResult(events);520521    expect(result.success).to.be.true;522  });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(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 expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530    const result = getGenericResult(events);531532    expect(result.success).to.be.false;533  });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537  await usingApi(async (api) => {538    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);539    const events = await submitTransactionAsync(sender, tx);540    const result = getGenericResult(events);541542    expect(result.success).to.be.true;543  });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550    const result = getGenericResult(events);551552    expect(result.success).to.be.false;553  });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558  await usingApi(async (api) => {559560    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);561    const events = await submitTransactionAsync(sender, tx);562    const result = getGenericResult(events);563564    expect(result.success).to.be.true;565  });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570  await usingApi(async (api) => {571572    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);573    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574    const result = getGenericResult(events);575576    expect(result.success).to.be.false;577  });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581  await usingApi(async (api) => {582    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);583    const events = await submitTransactionAsync(sender, tx);584    const result = getGenericResult(events);585586    expect(result.success).to.be.true;587  });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591  await usingApi(async (api) => {592    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594    const result = getGenericResult(events);595596    expect(result.success).to.be.false;597  });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601  await usingApi(async (api) => {602    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);603    const events = await submitTransactionAsync(sender, tx);604    const result = getGenericResult(events);605606    expect(result.success).to.be.true;607  });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611  let allowlisted = false;612  await usingApi(async (api) => {613    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;614  });615  return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619  await usingApi(async (api) => {620    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());621    const events = await submitTransactionAsync(sender, tx);622    const result = getGenericResult(events);623624    expect(result.success).to.be.true;625  });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629  await usingApi(async (api) => {630    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    expect(result.success).to.be.true;635  });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());641    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642    const result = getGenericResult(events);643644    expect(result.success).to.be.false;645  });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662  });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666  await usingApi(async (api) => {667    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679  });680}681682export interface CreateFungibleData {683  readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690  NFT: CreateNftData;691} | {692  Fungible: CreateFungibleData;693} | {694  ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698  await usingApi(async (api) => {699    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700    // if burning token by admin - use adminButnItemExpectSuccess701    expect(balanceBefore >= BigInt(value)).to.be.true;702703    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);704    const events = await submitTransactionAsync(sender, tx);705    const result = getGenericResult(events);706    expect(result.success).to.be.true;707708    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710  });711}712713export async function714approveExpectSuccess(715  collectionId: number,716  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718  await usingApi(async (api: ApiPromise) => {719    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720    const events = await submitTransactionAsync(owner, approveUniqueTx);721    const result = getGenericResult(events);722    expect(result.success).to.be.true;723724    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725  });726}727728export async function adminApproveFromExpectSuccess(729  collectionId: number,730  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732  await usingApi(async (api: ApiPromise) => {733    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734    const events = await submitTransactionAsync(admin, approveUniqueTx);735    const result = getGenericResult(events);736    expect(result.success).to.be.true;737738    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739  });740}741742export async function743transferFromExpectSuccess(744  collectionId: number,745  tokenId: number,746  accountApproved: IKeyringPair,747  accountFrom: IKeyringPair | CrossAccountId,748  accountTo: IKeyringPair | CrossAccountId,749  value: number | bigint = 1,750  type = 'NFT',751) {752  await usingApi(async (api: ApiPromise) => {753    const to = normalizeAccountId(accountTo);754    let balanceBefore = 0n;755    if (type === 'Fungible') {756      balanceBefore = await getBalance(api, collectionId, to, tokenId);757    }758    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759    const events = await submitTransactionAsync(accountApproved, transferFromTx);760    const result = getCreateItemResult(events);761    // tslint:disable-next-line:no-unused-expression762    expect(result.success).to.be.true;763    if (type === 'NFT') {764      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765    }766    if (type === 'Fungible') {767      const balanceAfter = await getBalance(api, collectionId, to, tokenId);768      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769    }770    if (type === 'ReFungible') {771      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772    }773  });774}775776export async function777transferFromExpectFail(778  collectionId: number,779  tokenId: number,780  accountApproved: IKeyringPair,781  accountFrom: IKeyringPair,782  accountTo: IKeyringPair,783  value: number | bigint = 1,784) {785  await usingApi(async (api: ApiPromise) => {786    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788    const result = getCreateCollectionResult(events);789    // tslint:disable-next-line:no-unused-expression790    expect(result.success).to.be.false;791  });792}793794/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {796  return new Promise<number>(async (resolve) => {797    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798      unsubscribe();799      resolve(head.number.toNumber());800    });801  });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805  await usingApi(async (api) => {806    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));807    const events = await submitTransactionAsync(sender, changeAdminTx);808    const result = getCreateCollectionResult(events);809    expect(result.success).to.be.true;810  });811}812813export async function814getFreeBalance(account: IKeyringPair): Promise<bigint> {815  let balance = 0n;816  await usingApi(async (api) => {817    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());818  });819820  return balance;821}822823export async function824scheduleTransferExpectSuccess(825  collectionId: number,826  tokenId: number,827  sender: IKeyringPair,828  recipient: IKeyringPair,829  value: number | bigint = 1,830  blockSchedule: number,831) {832  await usingApi(async (api: ApiPromise) => {833    const blockNumber: number | undefined = await getBlockNumber(api);834    const expectedBlockNumber = blockNumber + blockSchedule;835836    expect(blockNumber).to.be.greaterThan(0);837    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);838    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);839840    await submitTransactionAsync(sender, scheduleTx);841842    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();843844    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));845846    // sleep for 4 blocks847    await waitNewBlocks(blockSchedule + 1);848849    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();850851    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));852    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);853  });854}855856857export async function858transferExpectSuccess(859  collectionId: number,860  tokenId: number,861  sender: IKeyringPair,862  recipient: IKeyringPair | CrossAccountId,863  value: number | bigint = 1,864  type = 'NFT',865) {866  await usingApi(async (api: ApiPromise) => {867    const to = normalizeAccountId(recipient);868869    let balanceBefore = 0n;870    if (type === 'Fungible') {871      balanceBefore = await getBalance(api, collectionId, to, tokenId);872    }873    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);874    const events = await submitTransactionAsync(sender, transferTx);875    const result = getTransferResult(events);876    // tslint:disable-next-line:no-unused-expression877    expect(result.success).to.be.true;878    expect(result.collectionId).to.be.equal(collectionId);879    expect(result.itemId).to.be.equal(tokenId);880    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));881    expect(result.recipient).to.be.deep.equal(to);882    expect(result.value).to.be.equal(BigInt(value));883    if (type === 'NFT') {884      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);885    }886    if (type === 'Fungible') {887      const balanceAfter = await getBalance(api, collectionId, to, tokenId);888      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));889    }890    if (type === 'ReFungible') {891      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;892    }893  });894}895896export async function897transferExpectFailure(898  collectionId: number,899  tokenId: number,900  sender: IKeyringPair,901  recipient: IKeyringPair,902  value: number | bigint = 1,903) {904  await usingApi(async (api: ApiPromise) => {905    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);906    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;907    const result = getGenericResult(events);908    // if (events && Array.isArray(events)) {909    //   const result = getCreateCollectionResult(events);910    // tslint:disable-next-line:no-unused-expression911    expect(result.success).to.be.false;912    //}913  });914}915916export async function917approveExpectFail(918  collectionId: number,919  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,920) {921  await usingApi(async (api: ApiPromise) => {922    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);923    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;924    const result = getCreateCollectionResult(events);925    // tslint:disable-next-line:no-unused-expression926    expect(result.success).to.be.false;927  });928}929930export async function getBalance(931  api: ApiPromise,932  collectionId: number,933  owner: string | CrossAccountId,934  token: number,935): Promise<bigint> {936  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();937}938export async function getTokenOwner(939  api: ApiPromise,940  collectionId: number,941  token: number,942): Promise<CrossAccountId> {943  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);944}945export async function isTokenExists(946  api: ApiPromise,947  collectionId: number,948  token: number,949): Promise<boolean> {950  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();951}952export async function getLastTokenId(953  api: ApiPromise,954  collectionId: number,955): Promise<number> {956  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();957}958export async function getAdminList(959  api: ApiPromise,960  collectionId: number,961): Promise<string[]> {962  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;963}964export async function getVariableMetadata(965  api: ApiPromise,966  collectionId: number,967  tokenId: number,968): Promise<number[]> {969  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];970}971export async function getConstMetadata(972  api: ApiPromise,973  collectionId: number,974  tokenId: number,975): Promise<number[]> {976  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];977}978979export async function createFungibleItemExpectSuccess(980  sender: IKeyringPair,981  collectionId: number,982  data: CreateFungibleData,983  owner: CrossAccountId | string = sender.address,984) {985  return await usingApi(async (api) => {986    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});987988    const events = await submitTransactionAsync(sender, tx);989    const result = getCreateItemResult(events);990991    expect(result.success).to.be.true;992    return result.itemId;993  });994}995996export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {997  let newItemId = 0;998  await usingApi(async (api) => {999    const to = normalizeAccountId(owner);1000    const itemCountBefore = await getLastTokenId(api, collectionId);1001    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10021003    let tx;1004    if (createMode === 'Fungible') {1005      const createData = {fungible: {value: 10}};1006      tx = api.tx.unique.createItem(collectionId, to, createData as any);1007    } else if (createMode === 'ReFungible') {1008      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1009      tx = api.tx.unique.createItem(collectionId, to, createData as any);1010    } else {1011      const createData = {nft: {const_data: [], variable_data: []}};1012      tx = api.tx.unique.createItem(collectionId, to, createData as any);1013    }10141015    const events = await submitTransactionAsync(sender, tx);1016    const result = getCreateItemResult(events);10171018    const itemCountAfter = await getLastTokenId(api, collectionId);1019    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10201021    // What to expect1022    // tslint:disable-next-line:no-unused-expression1023    expect(result.success).to.be.true;1024    if (createMode === 'Fungible') {1025      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1026    } else {1027      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1028    }1029    expect(collectionId).to.be.equal(result.collectionId);1030    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1031    expect(to).to.be.deep.equal(result.recipient);1032    newItemId = result.itemId;1033  });1034  return newItemId;1035}10361037export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1038  await usingApi(async (api) => {1039    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10401041    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1042    const result = getCreateItemResult(events);10431044    expect(result.success).to.be.false;1045  });1046}10471048export async function setPublicAccessModeExpectSuccess(1049  sender: IKeyringPair, collectionId: number,1050  accessMode: 'Normal' | 'AllowList',1051) {1052  await usingApi(async (api) => {10531054    // Run the transaction1055    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1056    const events = await submitTransactionAsync(sender, tx);1057    const result = getGenericResult(events);10581059    // Get the collection1060    const collection = await queryCollectionExpectSuccess(api, collectionId);10611062    // What to expect1063    // tslint:disable-next-line:no-unused-expression1064    expect(result.success).to.be.true;1065    expect(collection.access.toHuman()).to.be.equal(accessMode);1066  });1067}10681069export async function setPublicAccessModeExpectFail(1070  sender: IKeyringPair, collectionId: number,1071  accessMode: 'Normal' | 'AllowList',1072) {1073  await usingApi(async (api) => {10741075    // Run the transaction1076    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1077    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1078    const result = getGenericResult(events);10791080    // What to expect1081    // tslint:disable-next-line:no-unused-expression1082    expect(result.success).to.be.false;1083  });1084}10851086export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1087  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1088}10891090export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1091  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1092}10931094export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1095  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1096}10971098export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1099  await usingApi(async (api) => {11001101    // Run the transaction1102    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1103    const events = await submitTransactionAsync(sender, tx);1104    const result = getGenericResult(events);1105    expect(result.success).to.be.true;11061107    // Get the collection1108    const collection = await queryCollectionExpectSuccess(api, collectionId);11091110    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1111  });1112}11131114export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1115  await setMintPermissionExpectSuccess(sender, collectionId, true);1116}11171118export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1119  await usingApi(async (api) => {1120    // Run the transaction1121    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1122    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1123    const result = getCreateCollectionResult(events);1124    // tslint:disable-next-line:no-unused-expression1125    expect(result.success).to.be.false;1126  });1127}11281129export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1130  await usingApi(async (api) => {1131    // Run the transaction1132    const tx = api.tx.unique.setChainLimits(limits);1133    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1134    const result = getCreateCollectionResult(events);1135    // tslint:disable-next-line:no-unused-expression1136    expect(result.success).to.be.false;1137  });1138}11391140export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1141  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1142}11431144export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1145  await usingApi(async (api) => {1146    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11471148    // Run the transaction1149    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1150    const events = await submitTransactionAsync(sender, tx);1151    const result = getGenericResult(events);1152    expect(result.success).to.be.true;11531154    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1155  });1156}11571158export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1159  await usingApi(async (api) => {11601161    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11621163    // Run the transaction1164    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1165    const events = await submitTransactionAsync(sender, tx);1166    const result = getGenericResult(events);1167    expect(result.success).to.be.true;11681169    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1170  });1171}11721173export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1174  await usingApi(async (api) => {11751176    // Run the transaction1177    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1178    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1179    const result = getGenericResult(events);11801181    // What to expect1182    // tslint:disable-next-line:no-unused-expression1183    expect(result.success).to.be.false;1184  });1185}11861187export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1188  await usingApi(async (api) => {1189    // Run the transaction1190    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1191    const events = await submitTransactionAsync(sender, tx);1192    const result = getGenericResult(events);11931194    // What to expect1195    // tslint:disable-next-line:no-unused-expression1196    expect(result.success).to.be.true;1197  });1198}11991200export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1201  await usingApi(async (api) => {1202    // Run the transaction1203    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1204    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1205    const result = getGenericResult(events);12061207    // What to expect1208    // tslint:disable-next-line:no-unused-expression1209    expect(result.success).to.be.false;1210  });1211}12121213export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1214  : Promise<UpDataStructsCollection | null> => {1215  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1216};12171218export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1219  // set global object - collectionsCount1220  return (await api.rpc.unique.collectionStats()).created.toNumber();1221};12221223export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1224  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1225}12261227export async function waitNewBlocks(blocksCount = 1): Promise<void> {1228  await usingApi(async (api) => {1229    const promise = new Promise<void>(async (resolve) => {1230      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1231        if (blocksCount > 0) {1232          blocksCount--;1233        } else {1234          unsubscribe();1235          resolve();1236        }1237      });1238    });1239    return promise;1240  });1241}