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

difftreelog

Check both unstakeAll and unstakePartial

Max Andreev2023-02-13parent: #7976517.patch.diff
in: master

2 files changed

modifiedtests/src/sub/appPromotion/appPromotion.test.tsdiffbeforeafterboth
--- a/tests/src/sub/appPromotion/appPromotion.test.ts
+++ b/tests/src/sub/appPromotion/appPromotion.test.ts
@@ -147,113 +147,172 @@
     });
   });
 
-  describe('unstake extrinsic', () => {
-    itSub('should move tokens to "pendingUnstake" map and subtract it from totalStaked', async ({helper}) => {
-      const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
-      const totalStakedBefore = await helper.staking.getTotalStaked();
-      await helper.staking.stake(staker, 900n * nominal);
-      await helper.staking.unstakeAll(staker);
+  describe('Unstaking', () => {
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should move tokens to "pendingUnstake" and subtract it from totalStaked`, async ({helper}) => {
+        const [staker, recepient] = [accounts.pop()!, accounts.pop()!];
+        const totalStakedBefore = await helper.staking.getTotalStaked();
+        const STAKE_AMOUNT = 900n * nominal;
+
+        await helper.staking.stake(staker, STAKE_AMOUNT);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, STAKE_AMOUNT);
 
-      // Right after unstake tokens are still locked
-      expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: 900n * nominal, reasons: 'All'}]);
-      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 900n * nominal, feeFrozen: 900n * nominal});
-      // Staker can not transfer
-      await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(900n * nominal);
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
-      expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
+        // Right after unstake tokens are still locked
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+        expect(await helper.balance.getLocked(staker.address)).to.deep.eq([{id: 'appstake', amount: STAKE_AMOUNT, reasons: 'All'}]);
+        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: STAKE_AMOUNT, feeFrozen: STAKE_AMOUNT});
+        // Staker can not transfer
+        await expect(helper.balance.transferToSubstrate(staker, recepient.address, 100n * nominal)).to.be.rejectedWith('balances.LiquidityRestrictions');
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(STAKE_AMOUNT);
+        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.staking.getTotalStaked()).to.be.equal(totalStakedBefore);
+      });
     });
 
-    itSub('should unlock balance after unlocking period ends and remove it from "pendingUnstake"', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstakeAll(staker);
-      const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should unlock balance after unlocking period ends and remove it from "pendingUnstake"`, async ({helper}) => {
+        const staker = accounts.pop()!;
+        await helper.staking.stake(staker, 100n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 100n * nominal);
+        const [pendingUnstake] = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
 
-      // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
-      await helper.wait.forParachainBlockNumber(pendingUnstake.block);
-      expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        // Wait for unstaking period. Balance now free ~1000; reserved, frozen, miscFrozeb: 0n
+        await helper.wait.forParachainBlockNumber(pendingUnstake.block);
+        expect(await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, miscFrozen: 0n, feeFrozen: 0n});
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
 
-      // staker can transfer:
-      await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
+        // staker can transfer:
+        await helper.balance.transferToSubstrate(staker, donor.address, 998n * nominal);
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(1n);
+      });
     });
 
-    itSub('should successfully unstake multiple stakes', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.stake(staker, 200n * nominal);
-      await helper.staking.stake(staker, 300n * nominal);
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should successfully unstake multiple stakes`, async ({helper}) => {
+        const staker = accounts.pop()!;
+        await helper.staking.stake(staker, 100n * nominal);
+        await helper.staking.stake(staker, 200n * nominal);
+        await helper.staking.stake(staker, 300n * nominal);
 
-      // staked: [100, 200, 300]; unstaked: 0
-      let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
-      let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
-      expect(totalPendingUnstake).to.be.deep.equal(0n);
-      expect(pendingUnstake).to.be.deep.equal([]);
-      expect(stakes[0].amount).to.equal(100n * nominal);
-      expect(stakes[1].amount).to.equal(200n * nominal);
-      expect(stakes[2].amount).to.equal(300n * nominal);
+        // staked: [100, 200, 300]; unstaked: 0
+        let totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+        let pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        let stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+        expect(totalPendingUnstake).to.be.deep.equal(0n);
+        expect(pendingUnstake).to.be.deep.equal([]);
+        expect(stakes[0].amount).to.equal(100n * nominal);
+        expect(stakes[1].amount).to.equal(200n * nominal);
+        expect(stakes[2].amount).to.equal(300n * nominal);
 
-      // Can unstake multiple stakes
-      await helper.staking.unstakeAll(staker);
-      pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
-      stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
-      expect(totalPendingUnstake).to.be.equal(600n * nominal);
-      expect(stakes).to.be.deep.equal([]);
-      expect(pendingUnstake[0].amount).to.equal(600n * nominal);
+        // Can unstake multiple stakes
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 600n * nominal);
 
-      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});
-      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
-      await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
-      expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
-      expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        pendingUnstake = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        totalPendingUnstake = await helper.staking.getPendingUnstake({Substrate: staker.address});
+        stakes = await helper.staking.getTotalStakedPerBlock({Substrate: staker.address});
+        expect(totalPendingUnstake).to.be.equal(600n * nominal);
+        expect(stakes).to.be.deep.equal([]);
+        expect(pendingUnstake[0].amount).to.equal(600n * nominal);
+
+        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 600n * nominal, miscFrozen: 600n * nominal});
+        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+        await helper.wait.forParachainBlockNumber(pendingUnstake[0].block);
+        expect (await helper.balance.getSubstrateFull(staker.address)).to.deep.contain({reserved: 0n, feeFrozen: 0n, miscFrozen: 0n});
+        expect (await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n);
+      });
     });
 
-    itSub('should not have any effects if no active stakes', async ({helper}) => {
-      const staker = accounts.pop()!;
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should not have any effects if no active stakes`, async ({helper}) => {
+        const staker = accounts.pop()!;
+
+        // unstake has no effect if no stakes at all
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 100n * nominal);
+
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
 
-      // unstake has no effect if no stakes at all
-      await helper.staking.unstakeAll(staker);
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(0n);
-      expect(await helper.balance.getSubstrate(staker.address) / nominal).to.be.equal(999n); // TODO bigint closeTo helper
+        // TODO stake() unstake() waitUnstaked() unstake();
 
-      // TODO stake() unstake() waitUnstaked() unstake();
+        // can't unstake if there are only pendingUnstakes
+        await helper.staking.stake(staker, 100n * nominal);
 
-      // can't unstake if there are only pendingUnstakes
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstakeAll(staker);
-      await helper.staking.unstakeAll(staker);
+        if (testCase.method === 'unstakeAll') {
+          await helper.staking.unstakeAll(staker);
+          await helper.staking.unstakeAll(staker);
+        } else {
+          await helper.staking.unstakePartial(staker, 100n * nominal);
+          await helper.staking.unstakePartial(staker, 100n * nominal);
+        }
 
-      expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
-      expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.eq(0);
+        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
+        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+      });
     });
 
-    itSub('should keep different unlocking block for each unlocking stake', async ({helper}) => {
-      const staker = accounts.pop()!;
-      await helper.staking.stake(staker, 100n * nominal);
-      await helper.staking.unstakeAll(staker);
-      await helper.staking.stake(staker, 120n * nominal);
-      await helper.staking.unstakeAll(staker);
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should create different pending-unlock for each unlocking stake`, async ({helper}) => {
+        const staker = accounts.pop()!;
+        await helper.staking.stake(staker, 100n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 100n * nominal);
+        await helper.staking.stake(staker, 120n * nominal);
+        testCase.method === 'unstakeAll'
+          ? await helper.staking.unstakeAll(staker)
+          : await helper.staking.unstakePartial(staker, 120n * nominal);
 
-      const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
-      expect(unstakingPerBlock).has.length(2);
-      expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
-      expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
+        const unstakingPerBlock = await helper.staking.getPendingUnstakePerBlock({Substrate: staker.address});
+        expect(unstakingPerBlock).has.length(2);
+        expect(unstakingPerBlock[0].amount).to.equal(100n * nominal);
+        expect(unstakingPerBlock[1].amount).to.equal(120n * nominal);
+        expect(await helper.staking.getStakesNumber({Substrate: staker.address})).to.equal(0);
+      });
     });
 
-    itSub('should be possible for 3 accounts in one block', async ({helper}) => {
-      const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
+    [
+      {method: 'unstakeAll' as const},
+      {method: 'unstakePartial' as const},
+    ].map(testCase => {
+      itSub(`[${testCase.method}] should be possible for 3 accounts in one block`, async ({helper}) => {
+        const stakers = [accounts.pop()!, accounts.pop()!, accounts.pop()!];
 
-      await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
-      await Promise.all(stakers.map(staker => helper.staking.unstakeAll(staker)));
+        await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
+        await Promise.all(stakers.map(staker => {
+          return testCase.method === 'unstakeAll'
+            ? helper.staking.unstakeAll(staker)
+            : helper.staking.unstakePartial(staker, 100n * nominal);
+        }));
 
-      await Promise.all(stakers.map(async (staker) => {
-        expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
-        expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
-      }));
+        await Promise.all(stakers.map(async (staker) => {
+          expect(await helper.staking.getPendingUnstake({Substrate: staker.address})).to.be.equal(100n * nominal);
+          expect(await helper.staking.getTotalStaked({Substrate: staker.address})).to.be.equal(0n);
+        }));
+      });
     });
 
     itSub('should not be possible for more than 3 accounts in one block', async ({helper}) => {
@@ -261,7 +320,11 @@
         const stakers = await helper.arrange.createAccounts([200n,200n,200n,200n,200n,200n,200n,200n,200n,200n], donor);
 
         await Promise.all(stakers.map(staker => helper.staking.stake(staker, 100n * nominal)));
-        const unstakingResults = await Promise.allSettled(stakers.map(staker => helper.staking.unstakeAll(staker)));
+        const unstakingResults = await Promise.allSettled(stakers.map((staker, i) => {
+          return i % 2 === 0
+            ? helper.staking.unstakeAll(staker)
+            : helper.staking.unstakePartial(staker, 100n * nominal);
+        }));
 
         const successfulUnstakes = unstakingResults.filter(result => result.status === 'fulfilled');
         expect(successfulUnstakes).to.have.length(3);
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
before · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  wsEndpoint: string | null;375  chainLog: IUniqueHelperLog[];376  children: ChainHelperBase[];377  address: AddressGroup;378  chain: ChainGroup;379380  constructor(logger?: ILogger, helperBase?: any) {381    this.helperBase = helperBase;382383    this.util = UniqueUtil;384    this.eventHelper = UniqueEventHelper;385    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386    this.logger = logger;387    this.api = null;388    this.forcedNetwork = null;389    this.network = null;390    this.wsEndpoint = null;391    this.chainLog = [];392    this.children = [];393    this.address = new AddressGroup(this);394    this.chain = new ChainGroup(this);395  }396397  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398    Object.setPrototypeOf(helperCls.prototype, this);399    const newHelper = new helperCls(this.logger, options);400401    newHelper.api = this.api;402    newHelper.network = this.network;403    newHelper.forceNetwork = this.forceNetwork;404405    this.children.push(newHelper);406407    return newHelper;408  }409410  getEndpoint(): string {411    if (this.wsEndpoint === null) throw Error('No connection was established');412    return this.wsEndpoint;413  }414415  getApi(): ApiPromise {416    if(this.api === null) throw Error('API not initialized');417    return this.api;418  }419420  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421    const collectedEvents: IEvent[] = [];422    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423      const ievents = this.eventHelper.extractEvents(events);424      ievents.forEach((event) => {425        expectedEvents.forEach((e => {426          if (event.section === e.section && e.names.includes(event.method)) {427            collectedEvents.push(event);428          }429        }));430      });431    });432    return {unsubscribe: unsubscribe as any, collectedEvents};433  }434435  clearChainLog(): void {436    this.chainLog = [];437  }438439  forceNetwork(value: TNetworks): void {440    this.forcedNetwork = value;441  }442443  async connect(wsEndpoint: string, listeners?: IApiListeners) {444    if (this.api !== null) throw Error('Already connected');445    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446    this.wsEndpoint = wsEndpoint;447    this.api = api;448    this.network = network;449  }450451  async disconnect() {452    for (const child of this.children) {453      child.clearApi();454    }455456    if (this.api === null) return;457    await this.api.disconnect();458    this.clearApi();459  }460461  clearApi() {462    this.api = null;463    this.network = null;464  }465466  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473    return 'opal';474  }475476  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478    await api.isReady;479480    const network = await this.detectNetwork(api);481482    await api.disconnect();483484    return network;485  }486487  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488    api: ApiPromise;489    network: TNetworks;490  }> {491    if(typeof network === 'undefined' || network === null) network = 'opal';492    const supportedRPC = {493      opal: {494        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495      },496      quartz: {497        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498      },499      unique: {500        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501      },502      rococo: {},503      westend: {},504      moonbeam: {},505      moonriver: {},506      acala: {},507      karura: {},508      westmint: {},509    };510    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511    const rpc = supportedRPC[network];512513    // TODO: investigate how to replace rpc in runtime514    // api._rpcCore.addUserInterfaces(rpc);515516    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518    await api.isReadyOrError;519520    if (typeof listeners === 'undefined') listeners = {};521    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524    }525526    return {api, network};527  }528529  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530    const {events, status} = data;531    if (status.isReady) {532      return this.transactionStatus.NOT_READY;533    }534    if (status.isBroadcast) {535      return this.transactionStatus.NOT_READY;536    }537    if (status.isInBlock || status.isFinalized) {538      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539      if (errors.length > 0) {540        return this.transactionStatus.FAIL;541      }542      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543        return this.transactionStatus.SUCCESS;544      }545    }546547    return this.transactionStatus.FAIL;548  }549550  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551    const sign = (callback: any) => {552      if(options !== null) return transaction.signAndSend(sender, options, callback);553      return transaction.signAndSend(sender, callback);554    };555    // eslint-disable-next-line no-async-promise-executor556    return new Promise(async (resolve, reject) => {557      try {558        const unsub = await sign((result: any) => {559          const status = this.getTransactionStatus(result);560561          if (status === this.transactionStatus.SUCCESS) {562            this.logger.log(`${label} successful`);563            unsub();564            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});565          } else if (status === this.transactionStatus.FAIL) {566            let moduleError = null;567568            if (result.hasOwnProperty('dispatchError')) {569              const dispatchError = result['dispatchError'];570571              if (dispatchError) {572                if (dispatchError.isModule) {573                  const modErr = dispatchError.asModule;574                  const errorMeta = dispatchError.registry.findMetaError(modErr);575576                  moduleError = `${errorMeta.section}.${errorMeta.name}`;577                } else {578                  moduleError = dispatchError.toHuman();579                }580              } else {581                this.logger.log(result, this.logger.level.ERROR);582              }583            }584585            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586            unsub();587            reject({status, moduleError, result});588          }589        });590      } catch (e) {591        this.logger.log(e, this.logger.level.ERROR);592        reject(e);593      }594    });595  }596597  async signTransactionWithoutSending(signer: TSigner, tx: any) {598    const api = this.getApi();599    const signingInfo = await api.derive.tx.signingInfo(signer.address);600601    tx.sign(signer, {602      blockHash: api.genesisHash,603      genesisHash: api.genesisHash,604      runtimeVersion: api.runtimeVersion,605      nonce: signingInfo.nonce,606    });607608    return tx.toHex();609  }610611  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612    const api = this.getApi();613    const signingInfo = await api.derive.tx.signingInfo(signer.address);614615    // We need to sign the tx because616    // unsigned transactions does not have an inclusion fee617    tx.sign(signer, {618      blockHash: api.genesisHash,619      genesisHash: api.genesisHash,620      runtimeVersion: api.runtimeVersion,621      nonce: signingInfo.nonce,622    });623624    if (len === null) {625      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626    } else {627      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628    }629  }630631  constructApiCall(apiCall: string, params: any[]) {632    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633    let call = this.getApi() as any;634    for(const part of apiCall.slice(4).split('.')) {635      call = call[part];636      if (!call) {637        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639      }640    }641    return call(...params);642  }643644  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645    if(this.api === null) throw Error('API not initialized');646    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648    const startTime = (new Date()).getTime();649    let result: ITransactionResult;650    let events: IEvent[] = [];651    try {652      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653      events = this.eventHelper.extractEvents(result.result.events);654      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');655      if (errorEvent)656        throw Error(errorEvent.method + ': ' + extrinsic);657    }658    catch(e) {659      if(!(e as object).hasOwnProperty('status')) throw e;660      result = e as ITransactionResult;661    }662663    const endTime = (new Date()).getTime();664665    const log = {666      executedAt: endTime,667      executionTime: endTime - startTime,668      type: this.chainLogType.EXTRINSIC,669      status: result.status,670      call: extrinsic,671      signer: this.getSignerAddress(sender),672      params,673    } as IUniqueHelperLog;674675    if(result.status !== this.transactionStatus.SUCCESS) {676      if (result.moduleError) log.moduleError = result.moduleError;677      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;678    }679    if(events.length > 0) log.events = events;680681    this.chainLog.push(log);682683    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {684      if (result.moduleError) throw Error(`${result.moduleError}`);685      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));686    }687    return result;688  }689690  async callRpc(rpc: string, params?: any[]) {691    if(typeof params === 'undefined') params = [];692    if(this.api === null) throw Error('API not initialized');693    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);694695    const startTime = (new Date()).getTime();696    let result;697    let error = null;698    const log = {699      type: this.chainLogType.RPC,700      call: rpc,701      params,702    } as IUniqueHelperLog;703704    try {705      result = await this.constructApiCall(rpc, params);706    }707    catch(e) {708      error = e;709    }710711    const endTime = (new Date()).getTime();712713    log.executedAt = endTime;714    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';715    log.executionTime = endTime - startTime;716717    this.chainLog.push(log);718719    if(error !== null) throw error;720721    return result;722  }723724  getSignerAddress(signer: IKeyringPair | string): string {725    if(typeof signer === 'string') return signer;726    return signer.address;727  }728729  fetchAllPalletNames(): string[] {730    if(this.api === null) throw Error('API not initialized');731    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());732  }733734  fetchMissingPalletNames(requiredPallets: string[]): string[] {735    const palletNames = this.fetchAllPalletNames();736    return requiredPallets.filter(p => !palletNames.includes(p));737  }738}739740741class HelperGroup<T extends ChainHelperBase> {742  helper: T;743744  constructor(uniqueHelper: T) {745    this.helper = uniqueHelper;746  }747}748749750class CollectionGroup extends HelperGroup<UniqueHelper> {751  /**752 * Get number of blocks when sponsored transaction is available.753 *754 * @param collectionId ID of collection755 * @param tokenId ID of token756 * @param addressObj address for which the sponsorship is checked757 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});758 * @returns number of blocks or null if sponsorship hasn't been set759 */760  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {761    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();762  }763764  /**765   * Get the number of created collections.766   *767   * @returns number of created collections768   */769  async getTotalCount(): Promise<number> {770    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();771  }772773  /**774   * Get information about the collection with additional data,775   * including the number of tokens it contains, its administrators,776   * the normalized address of the collection's owner, and decoded name and description.777   *778   * @param collectionId ID of collection779   * @example await getData(2)780   * @returns collection information object781   */782  async getData(collectionId: number): Promise<{783    id: number;784    name: string;785    description: string;786    tokensCount: number;787    admins: CrossAccountId[];788    normalizedOwner: TSubstrateAccount;789    raw: any790  } | null> {791    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);792    const humanCollection = collection.toHuman(), collectionData = {793      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],794      raw: humanCollection,795    } as any, jsonCollection = collection.toJSON();796    if (humanCollection === null) return null;797    collectionData.raw.limits = jsonCollection.limits;798    collectionData.raw.permissions = jsonCollection.permissions;799    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);800    for (const key of ['name', 'description']) {801      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);802    }803804    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))805      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)806      : 0;807    collectionData.admins = await this.getAdmins(collectionId);808809    return collectionData;810  }811812  /**813   * Get the addresses of the collection's administrators, optionally normalized.814   *815   * @param collectionId ID of collection816   * @param normalize whether to normalize the addresses to the default ss58 format817   * @example await getAdmins(1)818   * @returns array of administrators819   */820  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {821    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();822823    return normalize824      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())825      : admins;826  }827828  /**829   * Get the addresses added to the collection allow-list, optionally normalized.830   * @param collectionId ID of collection831   * @param normalize whether to normalize the addresses to the default ss58 format832   * @example await getAllowList(1)833   * @returns array of allow-listed addresses834   */835  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {836    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();837    return normalize838      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())839      : allowListed;840  }841842  /**843   * Get the effective limits of the collection instead of null for default values844   *845   * @param collectionId ID of collection846   * @example await getEffectiveLimits(2)847   * @returns object of collection limits848   */849  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {850    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();851  }852853  /**854   * Burns the collection if the signer has sufficient permissions and collection is empty.855   *856   * @param signer keyring of signer857   * @param collectionId ID of collection858   * @example await helper.collection.burn(aliceKeyring, 3);859   * @returns ```true``` if extrinsic success, otherwise ```false```860   */861  async burn(signer: TSigner, collectionId: number): Promise<boolean> {862    const result = await this.helper.executeExtrinsic(863      signer,864      'api.tx.unique.destroyCollection', [collectionId],865      true,866    );867868    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');869  }870871  /**872   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.873   *874   * @param signer keyring of signer875   * @param collectionId ID of collection876   * @param sponsorAddress Sponsor substrate address877   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")878   * @returns ```true``` if extrinsic success, otherwise ```false```879   */880  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {881    const result = await this.helper.executeExtrinsic(882      signer,883      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],884      true,885    );886887    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');888  }889890  /**891   * Confirms consent to sponsor the collection on behalf of the signer.892   *893   * @param signer keyring of signer894   * @param collectionId ID of collection895   * @example confirmSponsorship(aliceKeyring, 10)896   * @returns ```true``` if extrinsic success, otherwise ```false```897   */898  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {899    const result = await this.helper.executeExtrinsic(900      signer,901      'api.tx.unique.confirmSponsorship', [collectionId],902      true,903    );904905    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');906  }907908  /**909   * Removes the sponsor of a collection, regardless if it consented or not.910   *911   * @param signer keyring of signer912   * @param collectionId ID of collection913   * @example removeSponsor(aliceKeyring, 10)914   * @returns ```true``` if extrinsic success, otherwise ```false```915   */916  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {917    const result = await this.helper.executeExtrinsic(918      signer,919      'api.tx.unique.removeCollectionSponsor', [collectionId],920      true,921    );922923    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');924  }925926  /**927   * Sets the limits of the collection. At least one limit must be specified for a correct call.928   *929   * @param signer keyring of signer930   * @param collectionId ID of collection931   * @param limits collection limits object932   * @example933   * await setLimits(934   *   aliceKeyring,935   *   10,936   *   {937   *     sponsorTransferTimeout: 0,938   *     ownerCanDestroy: false939   *   }940   * )941   * @returns ```true``` if extrinsic success, otherwise ```false```942   */943  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {944    const result = await this.helper.executeExtrinsic(945      signer,946      'api.tx.unique.setCollectionLimits', [collectionId, limits],947      true,948    );949950    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');951  }952953  /**954   * Changes the owner of the collection to the new Substrate address.955   *956   * @param signer keyring of signer957   * @param collectionId ID of collection958   * @param ownerAddress substrate address of new owner959   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")960   * @returns ```true``` if extrinsic success, otherwise ```false```961   */962  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {963    const result = await this.helper.executeExtrinsic(964      signer,965      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],966      true,967    );968969    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');970  }971972  /**973   * Adds a collection administrator.974   *975   * @param signer keyring of signer976   * @param collectionId ID of collection977   * @param adminAddressObj Administrator address (substrate or ethereum)978   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})979   * @returns ```true``` if extrinsic success, otherwise ```false```980   */981  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {982    const result = await this.helper.executeExtrinsic(983      signer,984      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],985      true,986    );987988    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');989  }990991  /**992   * Removes a collection administrator.993   *994   * @param signer keyring of signer995   * @param collectionId ID of collection996   * @param adminAddressObj Administrator address (substrate or ethereum)997   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})998   * @returns ```true``` if extrinsic success, otherwise ```false```999   */1000  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1001    const result = await this.helper.executeExtrinsic(1002      signer,1003      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1004      true,1005    );10061007    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1008  }10091010  /**1011   * Check if user is in allow list.1012   *1013   * @param collectionId ID of collection1014   * @param user Account to check1015   * @example await getAdmins(1)1016   * @returns is user in allow list1017   */1018  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1019    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1020  }10211022  /**1023   * Adds an address to allow list1024   * @param signer keyring of signer1025   * @param collectionId ID of collection1026   * @param addressObj address to add to the allow list1027   * @returns ```true``` if extrinsic success, otherwise ```false```1028   */1029  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1030    const result = await this.helper.executeExtrinsic(1031      signer,1032      'api.tx.unique.addToAllowList', [collectionId, addressObj],1033      true,1034    );10351036    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1037  }10381039  /**1040   * Removes an address from allow list1041   *1042   * @param signer keyring of signer1043   * @param collectionId ID of collection1044   * @param addressObj address to remove from the allow list1045   * @returns ```true``` if extrinsic success, otherwise ```false```1046   */1047  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1048    const result = await this.helper.executeExtrinsic(1049      signer,1050      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1051      true,1052    );10531054    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1055  }10561057  /**1058   * Sets onchain permissions for selected collection.1059   *1060   * @param signer keyring of signer1061   * @param collectionId ID of collection1062   * @param permissions collection permissions object1063   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1064   * @returns ```true``` if extrinsic success, otherwise ```false```1065   */1066  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1067    const result = await this.helper.executeExtrinsic(1068      signer,1069      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1070      true,1071    );10721073    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1074  }10751076  /**1077   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1078   *1079   * @param signer keyring of signer1080   * @param collectionId ID of collection1081   * @param permissions nesting permissions object1082   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1083   * @returns ```true``` if extrinsic success, otherwise ```false```1084   */1085  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1086    return await this.setPermissions(signer, collectionId, {nesting: permissions});1087  }10881089  /**1090   * Disables nesting for selected collection.1091   *1092   * @param signer keyring of signer1093   * @param collectionId ID of collection1094   * @example disableNesting(aliceKeyring, 10);1095   * @returns ```true``` if extrinsic success, otherwise ```false```1096   */1097  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1098    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1099  }11001101  /**1102   * Sets onchain properties to the collection.1103   *1104   * @param signer keyring of signer1105   * @param collectionId ID of collection1106   * @param properties array of property objects1107   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1108   * @returns ```true``` if extrinsic success, otherwise ```false```1109   */1110  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1111    const result = await this.helper.executeExtrinsic(1112      signer,1113      'api.tx.unique.setCollectionProperties', [collectionId, properties],1114      true,1115    );11161117    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1118  }11191120  /**1121   * Get collection properties.1122   *1123   * @param collectionId ID of collection1124   * @param propertyKeys optionally filter the returned properties to only these keys1125   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1126   * @returns array of key-value pairs1127   */1128  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1129    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1130  }11311132  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1133    const api = this.helper.getApi();1134    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11351136    return (props! as any).consumedSpace;1137  }11381139  async getCollectionOptions(collectionId: number) {1140    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1141  }11421143  /**1144   * Deletes onchain properties from the collection.1145   *1146   * @param signer keyring of signer1147   * @param collectionId ID of collection1148   * @param propertyKeys array of property keys to delete1149   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1150   * @returns ```true``` if extrinsic success, otherwise ```false```1151   */1152  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1153    const result = await this.helper.executeExtrinsic(1154      signer,1155      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1156      true,1157    );11581159    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1160  }11611162  /**1163   * Changes the owner of the token.1164   *1165   * @param signer keyring of signer1166   * @param collectionId ID of collection1167   * @param tokenId ID of token1168   * @param addressObj address of a new owner1169   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1170   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171   * @returns true if the token success, otherwise false1172   */1173  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1174    const result = await this.helper.executeExtrinsic(1175      signer,1176      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1177      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1178    );11791180    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1181  }11821183  /**1184   *1185   * Change ownership of a token(s) on behalf of the owner.1186   *1187   * @param signer keyring of signer1188   * @param collectionId ID of collection1189   * @param tokenId ID of token1190   * @param fromAddressObj address on behalf of which the token will be sent1191   * @param toAddressObj new token owner1192   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1193   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1194   * @returns true if the token success, otherwise false1195   */1196  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1197    const result = await this.helper.executeExtrinsic(1198      signer,1199      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1200      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1201    );1202    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1203  }12041205  /**1206   *1207   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1208   *1209   * @param signer keyring of signer1210   * @param collectionId ID of collection1211   * @param tokenId ID of token1212   * @param amount amount of tokens to be burned. For NFT must be set to 1n1213   * @example burnToken(aliceKeyring, 10, 5);1214   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1215   */1216  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1217    const burnResult = await this.helper.executeExtrinsic(1218      signer,1219      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1220      true, // `Unable to burn token for ${label}`,1221    );1222    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1223    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1224    return burnedTokens.success;1225  }12261227  /**1228   * Destroys a concrete instance of NFT on behalf of the owner1229   *1230   * @param signer keyring of signer1231   * @param collectionId ID of collection1232   * @param tokenId ID of token1233   * @param fromAddressObj address on behalf of which the token will be burnt1234   * @param amount amount of tokens to be burned. For NFT must be set to 1n1235   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1236   * @returns ```true``` if extrinsic success, otherwise ```false```1237   */1238  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1239    const burnResult = await this.helper.executeExtrinsic(1240      signer,1241      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1242      true, // `Unable to burn token from for ${label}`,1243    );1244    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1245    return burnedTokens.success && burnedTokens.tokens.length > 0;1246  }12471248  /**1249   * Set, change, or remove approved address to transfer the ownership of the NFT.1250   *1251   * @param signer keyring of signer1252   * @param collectionId ID of collection1253   * @param tokenId ID of token1254   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1255   * @param amount amount of token to be approved. For NFT must be set to 1n1256   * @returns ```true``` if extrinsic success, otherwise ```false```1257   */1258  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1259    const approveResult = await this.helper.executeExtrinsic(1260      signer,1261      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1262      true, // `Unable to approve token for ${label}`,1263    );12641265    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1266  }12671268  /**1269   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1270   *1271   * @param signer keyring of signer1272   * @param collectionId ID of collection1273   * @param tokenId ID of token1274   * @param fromAddressObj Signer's Ethereum address containing her tokens1275   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1276   * @param amount amount of token to be approved. For NFT must be set to 1n1277   * @returns ```true``` if extrinsic success, otherwise ```false```1278   */1279  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1280    const approveResult = await this.helper.executeExtrinsic(1281      signer,1282      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1283      true, // `Unable to approve token for ${label}`,1284    );12851286    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1287  }12881289  /**1290   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1291   *1292   * @param signer keyring of signer1293   * @param collectionId ID of collection1294   * @param tokenId ID of token1295   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1296   * @param amount amount of token to be approved. For NFT must be set to 1n1297   * @returns ```true``` if extrinsic success, otherwise ```false```1298   */1299  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1300    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1301    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1302  }13031304  /**1305   * Get the amount of token pieces approved to transfer or burn. Normally 0.1306   *1307   * @param collectionId ID of collection1308   * @param tokenId ID of token1309   * @param toAccountObj address which is approved to use token pieces1310   * @param fromAccountObj address which may have allowed the use of its owned tokens1311   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1312   * @returns number of approved to transfer pieces1313   */1314  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1315    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1316  }13171318  /**1319   * Get the last created token ID in a collection1320   *1321   * @param collectionId ID of collection1322   * @example getLastTokenId(10);1323   * @returns id of the last created token1324   */1325  async getLastTokenId(collectionId: number): Promise<number> {1326    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1327  }13281329  /**1330   * Check if token exists1331   *1332   * @param collectionId ID of collection1333   * @param tokenId ID of token1334   * @example doesTokenExist(10, 20);1335   * @returns true if the token exists, otherwise false1336   */1337  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1338    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1339  }1340}13411342class NFTnRFT extends CollectionGroup {1343  /**1344   * Get tokens owned by account1345   *1346   * @param collectionId ID of collection1347   * @param addressObj tokens owner1348   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1349   * @returns array of token ids owned by account1350   */1351  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1352    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1353  }13541355  /**1356   * Get token data1357   *1358   * @param collectionId ID of collection1359   * @param tokenId ID of token1360   * @param propertyKeys optionally filter the token properties to only these keys1361   * @param blockHashAt optionally query the data at some block with this hash1362   * @example getToken(10, 5);1363   * @returns human readable token data1364   */1365  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1366    properties: IProperty[];1367    owner: CrossAccountId;1368    normalizedOwner: CrossAccountId;1369  }| null> {1370    let tokenData;1371    if(typeof blockHashAt === 'undefined') {1372      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1373    }1374    else {1375      if(propertyKeys.length == 0) {1376        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1377        if(!collection) return null;1378        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1379      }1380      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1381    }1382    tokenData = tokenData.toHuman();1383    if (tokenData === null || tokenData.owner === null) return null;1384    const owner = {} as any;1385    for (const key of Object.keys(tokenData.owner)) {1386      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1387        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1388        : tokenData.owner[key];1389    }1390    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1391    return tokenData;1392  }13931394  /**1395   * Get token's owner1396   * @param collectionId ID of collection1397   * @param tokenId ID of token1398   * @param blockHashAt optionally query the data at the block with this hash1399   * @example getTokenOwner(10, 5);1400   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1401   */1402  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1403    let owner;1404    if (typeof blockHashAt === 'undefined') {1405      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1406    } else {1407      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1408    }1409    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1410  }14111412  /**1413   * Recursively find the address that owns the token1414   * @param collectionId ID of collection1415   * @param tokenId ID of token1416   * @param blockHashAt1417   * @example getTokenTopmostOwner(10, 5);1418   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1419   */1420  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1421    let owner;1422    if (typeof blockHashAt === 'undefined') {1423      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1424    } else {1425      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1426    }14271428    if (owner === null) return null;14291430    return owner.toHuman();1431  }14321433  /**1434   * Nest one token into another1435   * @param signer keyring of signer1436   * @param tokenObj token to be nested1437   * @param rootTokenObj token to be parent1438   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1439   * @returns ```true``` if extrinsic success, otherwise ```false```1440   */1441  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1442    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1443    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1444    if(!result) {1445      throw Error('Unable to nest token!');1446    }1447    return result;1448  }14491450  /**1451     * Remove token from nested state1452     * @param signer keyring of signer1453     * @param tokenObj token to unnest1454     * @param rootTokenObj parent of a token1455     * @param toAddressObj address of a new token owner1456     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1457     * @returns ```true``` if extrinsic success, otherwise ```false```1458     */1459  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1460    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1461    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1462    if(!result) {1463      throw Error('Unable to unnest token!');1464    }1465    return result;1466  }14671468  /**1469   * Set permissions to change token properties1470   *1471   * @param signer keyring of signer1472   * @param collectionId ID of collection1473   * @param permissions permissions to change a property by the collection admin or token owner1474   * @example setTokenPropertyPermissions(1475   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1476   * )1477   * @returns true if extrinsic success otherwise false1478   */1479  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1480    const result = await this.helper.executeExtrinsic(1481      signer,1482      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1483      true,1484    );14851486    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1487  }14881489  /**1490   * Get token property permissions.1491   *1492   * @param collectionId ID of collection1493   * @param propertyKeys optionally filter the returned property permissions to only these keys1494   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1495   * @returns array of key-permission pairs1496   */1497  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1498    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1499  }15001501  /**1502   * Set token properties1503   *1504   * @param signer keyring of signer1505   * @param collectionId ID of collection1506   * @param tokenId ID of token1507   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1508   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1509   * @returns ```true``` if extrinsic success, otherwise ```false```1510   */1511  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1512    const result = await this.helper.executeExtrinsic(1513      signer,1514      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1515      true,1516    );15171518    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1519  }15201521  /**1522   * Get properties, metadata assigned to a token.1523   *1524   * @param collectionId ID of collection1525   * @param tokenId ID of token1526   * @param propertyKeys optionally filter the returned properties to only these keys1527   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1528   * @returns array of key-value pairs1529   */1530  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1531    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1532  }15331534  /**1535   * Delete the provided properties of a token1536   * @param signer keyring of signer1537   * @param collectionId ID of collection1538   * @param tokenId ID of token1539   * @param propertyKeys property keys to be deleted1540   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1541   * @returns ```true``` if extrinsic success, otherwise ```false```1542   */1543  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1544    const result = await this.helper.executeExtrinsic(1545      signer,1546      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1547      true,1548    );15491550    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1551  }15521553  /**1554   * Mint new collection1555   *1556   * @param signer keyring of signer1557   * @param collectionOptions basic collection options and properties1558   * @param mode NFT or RFT type of a collection1559   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1560   * @returns object of the created collection1561   */1562  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1563    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1564    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1565    for (const key of ['name', 'description', 'tokenPrefix']) {1566      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1567    }1568    const creationResult = await this.helper.executeExtrinsic(1569      signer,1570      'api.tx.unique.createCollectionEx', [collectionOptions],1571      true, // errorLabel,1572    );1573    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1574  }15751576  getCollectionObject(_collectionId: number): any {1577    return null;1578  }15791580  getTokenObject(_collectionId: number, _tokenId: number): any {1581    return null;1582  }15831584  /**1585   * Tells whether the given `owner` approves the `operator`.1586   * @param collectionId ID of collection1587   * @param owner owner address1588   * @param operator operator addrees1589   * @returns true if operator is enabled1590   */1591  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1592    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1593  }15941595  /** Sets or unsets the approval of a given operator.1596   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1597   *  @param operator Operator1598   *  @param approved Should operator status be granted or revoked?1599   *  @returns ```true``` if extrinsic success, otherwise ```false```1600   */1601  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1602    const result = await this.helper.executeExtrinsic(1603      signer,1604      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1605      true,1606    );1607    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1608  }1609}161016111612class NFTGroup extends NFTnRFT {1613  /**1614   * Get collection object1615   * @param collectionId ID of collection1616   * @example getCollectionObject(2);1617   * @returns instance of UniqueNFTCollection1618   */1619  getCollectionObject(collectionId: number): UniqueNFTCollection {1620    return new UniqueNFTCollection(collectionId, this.helper);1621  }16221623  /**1624   * Get token object1625   * @param collectionId ID of collection1626   * @param tokenId ID of token1627   * @example getTokenObject(10, 5);1628   * @returns instance of UniqueNFTToken1629   */1630  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1631    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1632  }16331634  /**1635   * Is token approved to transfer1636   * @param collectionId ID of collection1637   * @param tokenId ID of token1638   * @param toAccountObj address to be approved1639   * @returns ```true``` if extrinsic success, otherwise ```false```1640   */1641  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1642    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1643  }16441645  /**1646   * Changes the owner of the token.1647   *1648   * @param signer keyring of signer1649   * @param collectionId ID of collection1650   * @param tokenId ID of token1651   * @param addressObj address of a new owner1652   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1653   * @returns ```true``` if extrinsic success, otherwise ```false```1654   */1655  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1656    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1657  }16581659  /**1660   *1661   * Change ownership of a NFT on behalf of the owner.1662   *1663   * @param signer keyring of signer1664   * @param collectionId ID of collection1665   * @param tokenId ID of token1666   * @param fromAddressObj address on behalf of which the token will be sent1667   * @param toAddressObj new token owner1668   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1669   * @returns ```true``` if extrinsic success, otherwise ```false```1670   */1671  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1672    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1673  }16741675  /**1676   * Get tokens nested in the provided token1677   * @param collectionId ID of collection1678   * @param tokenId ID of token1679   * @param blockHashAt optionally query the data at the block with this hash1680   * @example getTokenChildren(10, 5);1681   * @returns tokens whose depth of nesting is <= 51682   */1683  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1684    let children;1685    if(typeof blockHashAt === 'undefined') {1686      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1687    } else {1688      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1689    }16901691    return children.toJSON().map((x: any) => {1692      return {collectionId: x.collection, tokenId: x.token};1693    });1694  }16951696  /**1697   * Mint new collection1698   * @param signer keyring of signer1699   * @param collectionOptions Collection options1700   * @example1701   * mintCollection(aliceKeyring, {1702   *   name: 'New',1703   *   description: 'New collection',1704   *   tokenPrefix: 'NEW',1705   * })1706   * @returns object of the created collection1707   */1708  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1709    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1710  }17111712  /**1713   * Mint new token1714   * @param signer keyring of signer1715   * @param data token data1716   * @returns created token object1717   */1718  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1719    const creationResult = await this.helper.executeExtrinsic(1720      signer,1721      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1722        nft: {1723          properties: data.properties,1724        },1725      }],1726      true,1727    );1728    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1729    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1730    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1731    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1732  }17331734  /**1735   * Mint multiple NFT tokens1736   * @param signer keyring of signer1737   * @param collectionId ID of collection1738   * @param tokens array of tokens with owner and properties1739   * @example1740   * mintMultipleTokens(aliceKeyring, 10, [{1741   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1742   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1743   *   },{1744   *     owner: {Ethereum: "0x9F0583DbB855d..."},1745   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1746   * }]);1747   * @returns ```true``` if extrinsic success, otherwise ```false```1748   */1749  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1750    const creationResult = await this.helper.executeExtrinsic(1751      signer,1752      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1753      true,1754    );1755    const collection = this.getCollectionObject(collectionId);1756    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1757  }17581759  /**1760   * Mint multiple NFT tokens with one owner1761   * @param signer keyring of signer1762   * @param collectionId ID of collection1763   * @param owner tokens owner1764   * @param tokens array of tokens with owner and properties1765   * @example1766   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1767   *   properties: [{1768   *   key: "gender",1769   *   value: "female",1770   *  },{1771   *   key: "age",1772   *   value: "33",1773   *  }],1774   * }]);1775   * @returns array of newly created tokens1776   */1777  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1778    const rawTokens = [];1779    for (const token of tokens) {1780      const raw = {NFT: {properties: token.properties}};1781      rawTokens.push(raw);1782    }1783    const creationResult = await this.helper.executeExtrinsic(1784      signer,1785      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1786      true,1787    );1788    const collection = this.getCollectionObject(collectionId);1789    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1790  }17911792  /**1793   * Set, change, or remove approved address to transfer the ownership of the NFT.1794   *1795   * @param signer keyring of signer1796   * @param collectionId ID of collection1797   * @param tokenId ID of token1798   * @param toAddressObj address to approve1799   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1800   * @returns ```true``` if extrinsic success, otherwise ```false```1801   */1802  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1803    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1804  }1805}180618071808class RFTGroup extends NFTnRFT {1809  /**1810   * Get collection object1811   * @param collectionId ID of collection1812   * @example getCollectionObject(2);1813   * @returns instance of UniqueRFTCollection1814   */1815  getCollectionObject(collectionId: number): UniqueRFTCollection {1816    return new UniqueRFTCollection(collectionId, this.helper);1817  }18181819  /**1820   * Get token object1821   * @param collectionId ID of collection1822   * @param tokenId ID of token1823   * @example getTokenObject(10, 5);1824   * @returns instance of UniqueNFTToken1825   */1826  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1827    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1828  }18291830  /**1831   * Get top 10 token owners with the largest number of pieces1832   * @param collectionId ID of collection1833   * @param tokenId ID of token1834   * @example getTokenTop10Owners(10, 5);1835   * @returns array of top 10 owners1836   */1837  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1838    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1839  }18401841  /**1842   * Get number of pieces owned by address1843   * @param collectionId ID of collection1844   * @param tokenId ID of token1845   * @param addressObj address token owner1846   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1847   * @returns number of pieces ownerd by address1848   */1849  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1850    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1851  }18521853  /**1854   * Transfer pieces of token to another address1855   * @param signer keyring of signer1856   * @param collectionId ID of collection1857   * @param tokenId ID of token1858   * @param addressObj address of a new owner1859   * @param amount number of pieces to be transfered1860   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1861   * @returns ```true``` if extrinsic success, otherwise ```false```1862   */1863  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1864    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1865  }18661867  /**1868   * Change ownership of some pieces of RFT on behalf of the owner.1869   * @param signer keyring of signer1870   * @param collectionId ID of collection1871   * @param tokenId ID of token1872   * @param fromAddressObj address on behalf of which the token will be sent1873   * @param toAddressObj new token owner1874   * @param amount number of pieces to be transfered1875   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1876   * @returns ```true``` if extrinsic success, otherwise ```false```1877   */1878  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1879    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1880  }18811882  /**1883   * Mint new collection1884   * @param signer keyring of signer1885   * @param collectionOptions Collection options1886   * @example1887   * mintCollection(aliceKeyring, {1888   *   name: 'New',1889   *   description: 'New collection',1890   *   tokenPrefix: 'NEW',1891   * })1892   * @returns object of the created collection1893   */1894  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1895    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1896  }18971898  /**1899   * Mint new token1900   * @param signer keyring of signer1901   * @param data token data1902   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1903   * @returns created token object1904   */1905  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1906    const creationResult = await this.helper.executeExtrinsic(1907      signer,1908      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1909        refungible: {1910          pieces: data.pieces,1911          properties: data.properties,1912        },1913      }],1914      true,1915    );1916    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1917    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1918    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1919    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1920  }19211922  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1923    throw Error('Not implemented');1924    const creationResult = await this.helper.executeExtrinsic(1925      signer,1926      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1927      true, // `Unable to mint RFT tokens for ${label}`,1928    );1929    const collection = this.getCollectionObject(collectionId);1930    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1931  }19321933  /**1934   * Mint multiple RFT tokens with one owner1935   * @param signer keyring of signer1936   * @param collectionId ID of collection1937   * @param owner tokens owner1938   * @param tokens array of tokens with properties and pieces1939   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1940   * @returns array of newly created RFT tokens1941   */1942  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1943    const rawTokens = [];1944    for (const token of tokens) {1945      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1946      rawTokens.push(raw);1947    }1948    const creationResult = await this.helper.executeExtrinsic(1949      signer,1950      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1951      true,1952    );1953    const collection = this.getCollectionObject(collectionId);1954    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1955  }19561957  /**1958   * Destroys a concrete instance of RFT.1959   * @param signer keyring of signer1960   * @param collectionId ID of collection1961   * @param tokenId ID of token1962   * @param amount number of pieces to be burnt1963   * @example burnToken(aliceKeyring, 10, 5);1964   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1965   */1966  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1967    return await super.burnToken(signer, collectionId, tokenId, amount);1968  }19691970  /**1971   * Destroys a concrete instance of RFT on behalf of the owner.1972   * @param signer keyring of signer1973   * @param collectionId ID of collection1974   * @param tokenId ID of token1975   * @param fromAddressObj address on behalf of which the token will be burnt1976   * @param amount number of pieces to be burnt1977   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1978   * @returns ```true``` if extrinsic success, otherwise ```false```1979   */1980  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1981    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1982  }19831984  /**1985   * Set, change, or remove approved address to transfer the ownership of the RFT.1986   *1987   * @param signer keyring of signer1988   * @param collectionId ID of collection1989   * @param tokenId ID of token1990   * @param toAddressObj address to approve1991   * @param amount number of pieces to be approved1992   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1993   * @returns true if the token success, otherwise false1994   */1995  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1996    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1997  }19981999  /**2000   * Get total number of pieces2001   * @param collectionId ID of collection2002   * @param tokenId ID of token2003   * @example getTokenTotalPieces(10, 5);2004   * @returns number of pieces2005   */2006  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2007    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2008  }20092010  /**2011   * Change number of token pieces. Signer must be the owner of all token pieces.2012   * @param signer keyring of signer2013   * @param collectionId ID of collection2014   * @param tokenId ID of token2015   * @param amount new number of pieces2016   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2017   * @returns true if the repartion was success, otherwise false2018   */2019  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2020    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2021    const repartitionResult = await this.helper.executeExtrinsic(2022      signer,2023      'api.tx.unique.repartition', [collectionId, tokenId, amount],2024      true,2025    );2026    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2027    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2028  }2029}203020312032class FTGroup extends CollectionGroup {2033  /**2034   * Get collection object2035   * @param collectionId ID of collection2036   * @example getCollectionObject(2);2037   * @returns instance of UniqueFTCollection2038   */2039  getCollectionObject(collectionId: number): UniqueFTCollection {2040    return new UniqueFTCollection(collectionId, this.helper);2041  }20422043  /**2044   * Mint new fungible collection2045   * @param signer keyring of signer2046   * @param collectionOptions Collection options2047   * @param decimalPoints number of token decimals2048   * @example2049   * mintCollection(aliceKeyring, {2050   *   name: 'New',2051   *   description: 'New collection',2052   *   tokenPrefix: 'NEW',2053   * }, 18)2054   * @returns newly created fungible collection2055   */2056  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2057    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2058    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2059    collectionOptions.mode = {fungible: decimalPoints};2060    for (const key of ['name', 'description', 'tokenPrefix']) {2061      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);2062    }2063    const creationResult = await this.helper.executeExtrinsic(2064      signer,2065      'api.tx.unique.createCollectionEx', [collectionOptions],2066      true,2067    );2068    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2069  }20702071  /**2072   * Mint tokens2073   * @param signer keyring of signer2074   * @param collectionId ID of collection2075   * @param owner address owner of new tokens2076   * @param amount amount of tokens to be meanted2077   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2078   * @returns ```true``` if extrinsic success, otherwise ```false```2079   */2080  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2081    const creationResult = await this.helper.executeExtrinsic(2082      signer,2083      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2084        fungible: {2085          value: amount,2086        },2087      }],2088      true, // `Unable to mint fungible tokens for ${label}`,2089    );2090    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2091  }20922093  /**2094   * Mint multiple Fungible tokens with one owner2095   * @param signer keyring of signer2096   * @param collectionId ID of collection2097   * @param owner tokens owner2098   * @param tokens array of tokens with properties and pieces2099   * @returns ```true``` if extrinsic success, otherwise ```false```2100   */2101  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2102    const rawTokens = [];2103    for (const token of tokens) {2104      const raw = {Fungible: {Value: token.value}};2105      rawTokens.push(raw);2106    }2107    const creationResult = await this.helper.executeExtrinsic(2108      signer,2109      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2110      true,2111    );2112    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2113  }21142115  /**2116   * Get the top 10 owners with the largest balance for the Fungible collection2117   * @param collectionId ID of collection2118   * @example getTop10Owners(10);2119   * @returns array of ```ICrossAccountId```2120   */2121  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2122    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2123  }21242125  /**2126   * Get account balance2127   * @param collectionId ID of collection2128   * @param addressObj address of owner2129   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2130   * @returns amount of fungible tokens owned by address2131   */2132  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2133    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2134  }21352136  /**2137   * Transfer tokens to address2138   * @param signer keyring of signer2139   * @param collectionId ID of collection2140   * @param toAddressObj address recipient2141   * @param amount amount of tokens to be sent2142   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2143   * @returns ```true``` if extrinsic success, otherwise ```false```2144   */2145  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2146    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2147  }21482149  /**2150   * Transfer some tokens on behalf of the owner.2151   * @param signer keyring of signer2152   * @param collectionId ID of collection2153   * @param fromAddressObj address on behalf of which tokens will be sent2154   * @param toAddressObj address where token to be sent2155   * @param amount number of tokens to be sent2156   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2157   * @returns ```true``` if extrinsic success, otherwise ```false```2158   */2159  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2160    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2161  }21622163  /**2164   * Destroy some amount of tokens2165   * @param signer keyring of signer2166   * @param collectionId ID of collection2167   * @param amount amount of tokens to be destroyed2168   * @example burnTokens(aliceKeyring, 10, 1000n);2169   * @returns ```true``` if extrinsic success, otherwise ```false```2170   */2171  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2172    return await super.burnToken(signer, collectionId, 0, amount);2173  }21742175  /**2176   * Burn some tokens on behalf of the owner.2177   * @param signer keyring of signer2178   * @param collectionId ID of collection2179   * @param fromAddressObj address on behalf of which tokens will be burnt2180   * @param amount amount of tokens to be burnt2181   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2182   * @returns ```true``` if extrinsic success, otherwise ```false```2183   */2184  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2185    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2186  }21872188  /**2189   * Get total collection supply2190   * @param collectionId2191   * @returns2192   */2193  async getTotalPieces(collectionId: number): Promise<bigint> {2194    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2195  }21962197  /**2198   * Set, change, or remove approved address to transfer tokens.2199   *2200   * @param signer keyring of signer2201   * @param collectionId ID of collection2202   * @param toAddressObj address to be approved2203   * @param amount amount of tokens to be approved2204   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2205   * @returns ```true``` if extrinsic success, otherwise ```false```2206   */2207  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2208    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2209  }22102211  /**2212   * Get amount of fungible tokens approved to transfer2213   * @param collectionId ID of collection2214   * @param fromAddressObj owner of tokens2215   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2216   * @returns number of tokens approved for the transfer2217   */2218  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2219    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2220  }2221}222222232224class ChainGroup extends HelperGroup<ChainHelperBase> {2225  /**2226   * Get system properties of a chain2227   * @example getChainProperties();2228   * @returns ss58Format, token decimals, and token symbol2229   */2230  getChainProperties(): IChainProperties {2231    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2232    return {2233      ss58Format: properties.ss58Format.toJSON(),2234      tokenDecimals: properties.tokenDecimals.toJSON(),2235      tokenSymbol: properties.tokenSymbol.toJSON(),2236    };2237  }22382239  /**2240   * Get chain header2241   * @example getLatestBlockNumber();2242   * @returns the number of the last block2243   */2244  async getLatestBlockNumber(): Promise<number> {2245    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2246  }22472248  /**2249   * Get block hash by block number2250   * @param blockNumber number of block2251   * @example getBlockHashByNumber(12345);2252   * @returns hash of a block2253   */2254  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2255    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2256    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2257    return blockHash;2258  }22592260  // TODO add docs2261  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2262    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2263    if (!blockHash) return null;2264    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2265  }22662267  /**2268   * Get latest relay block2269   * @returns {number} relay block2270   */2271  async getRelayBlockNumber(): Promise<bigint> {2272    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2273    return BigInt(blockNumber);2274  }22752276  /**2277   * Get account nonce2278   * @param address substrate address2279   * @example getNonce("5GrwvaEF5zXb26Fz...");2280   * @returns number, account's nonce2281   */2282  async getNonce(address: TSubstrateAccount): Promise<number> {2283    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2284  }2285}22862287class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2288  /**2289 * Get substrate address balance2290 * @param address substrate address2291 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2292 * @returns amount of tokens on address2293 */2294  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2295    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2296  }22972298  /**2299   * Transfer tokens to substrate address2300   * @param signer keyring of signer2301   * @param address substrate address of a recipient2302   * @param amount amount of tokens to be transfered2303   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2304   * @returns ```true``` if extrinsic success, otherwise ```false```2305   */2306  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2307    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);23082309    let transfer = {from: null, to: null, amount: 0n} as any;2310    result.result.events.forEach(({event: {data, method, section}}) => {2311      if ((section === 'balances') && (method === 'Transfer')) {2312        transfer = {2313          from: this.helper.address.normalizeSubstrate(data[0]),2314          to: this.helper.address.normalizeSubstrate(data[1]),2315          amount: BigInt(data[2]),2316        };2317      }2318    });2319    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2320      && this.helper.address.normalizeSubstrate(address) === transfer.to2321      && BigInt(amount) === transfer.amount;2322    return isSuccess;2323  }23242325  /**2326   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2327   * @param address substrate address2328   * @returns2329   */2330  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2331    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2332    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2333  }23342335  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2336    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2337    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2338  }2339}23402341class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2342  /**2343   * Get ethereum address balance2344   * @param address ethereum address2345   * @example getEthereum("0x9F0583DbB855d...")2346   * @returns amount of tokens on address2347   */2348  async getEthereum(address: TEthereumAccount): Promise<bigint> {2349    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2350  }23512352  /**2353   * Transfer tokens to address2354   * @param signer keyring of signer2355   * @param address Ethereum address of a recipient2356   * @param amount amount of tokens to be transfered2357   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2358   * @returns ```true``` if extrinsic success, otherwise ```false```2359   */2360  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2361    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23622363    let transfer = {from: null, to: null, amount: 0n} as any;2364    result.result.events.forEach(({event: {data, method, section}}) => {2365      if ((section === 'balances') && (method === 'Transfer')) {2366        transfer = {2367          from: data[0].toString(),2368          to: data[1].toString(),2369          amount: BigInt(data[2]),2370        };2371      }2372    });2373    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2374      && address === transfer.to2375      && BigInt(amount) === transfer.amount;2376    return isSuccess;2377  }2378}23792380class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2381  subBalanceGroup: SubstrateBalanceGroup<T>;2382  ethBalanceGroup: EthereumBalanceGroup<T>;23832384  constructor(helper: T) {2385    super(helper);2386    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2387    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2388  }23892390  getCollectionCreationPrice(): bigint {2391    return 2n * this.getOneTokenNominal();2392  }2393  /**2394   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2395   * @example getOneTokenNominal()2396   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2397   */2398  getOneTokenNominal(): bigint {2399    const chainProperties = this.helper.chain.getChainProperties();2400    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2401  }24022403  /**2404   * Get substrate address balance2405   * @param address substrate address2406   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2407   * @returns amount of tokens on address2408   */2409  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2410    return this.subBalanceGroup.getSubstrate(address);2411  }24122413  /**2414   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2415   * @param address substrate address2416   * @returns2417   */2418  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2419    return this.subBalanceGroup.getSubstrateFull(address);2420  }24212422  /**2423   * Get locked balances2424   * @param address substrate address2425   * @returns locked balances with reason via api.query.balances.locks2426   */2427  getLocked(address: TSubstrateAccount) {2428    return this.subBalanceGroup.getLocked(address);2429  }24302431  /**2432   * Get ethereum address balance2433   * @param address ethereum address2434   * @example getEthereum("0x9F0583DbB855d...")2435   * @returns amount of tokens on address2436   */2437  getEthereum(address: TEthereumAccount): Promise<bigint> {2438    return this.ethBalanceGroup.getEthereum(address);2439  }24402441  /**2442   * Transfer tokens to substrate address2443   * @param signer keyring of signer2444   * @param address substrate address of a recipient2445   * @param amount amount of tokens to be transfered2446   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2447   * @returns ```true``` if extrinsic success, otherwise ```false```2448   */2449  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2450    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2451  }24522453  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2454    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24552456    let transfer = {from: null, to: null, amount: 0n} as any;2457    result.result.events.forEach(({event: {data, method, section}}) => {2458      if ((section === 'balances') && (method === 'Transfer')) {2459        transfer = {2460          from: this.helper.address.normalizeSubstrate(data[0]),2461          to: this.helper.address.normalizeSubstrate(data[1]),2462          amount: BigInt(data[2]),2463        };2464      }2465    });2466    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2467    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2468    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2469    return isSuccess;2470  }24712472  /**2473   * Transfer tokens with the unlock period2474   * @param signer signers Keyring2475   * @param address Substrate address of recipient2476   * @param schedule Schedule params2477   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002478   */2479  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2480    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2481    const event = result.result.events2482      .find(e => e.event.section === 'vesting' &&2483            e.event.method === 'VestingScheduleAdded' &&2484            e.event.data[0].toHuman() === signer.address);2485    if (!event) throw Error('Cannot find transfer in events');2486  }24872488  /**2489   * Get schedule for recepient of vested transfer2490   * @param address Substrate address of recipient2491   * @returns2492   */2493  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2494    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2495    return schedule.map((schedule: any) => {2496      return {2497        start: BigInt(schedule.start),2498        period: BigInt(schedule.period),2499        periodCount: BigInt(schedule.periodCount),2500        perPeriod: BigInt(schedule.perPeriod),2501      };2502    });2503  }25042505  /**2506   * Claim vested tokens2507   * @param signer signers Keyring2508   */2509  async claim(signer: TSigner) {2510    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2511    const event = result.result.events2512      .find(e => e.event.section === 'vesting' &&2513            e.event.method === 'Claimed' &&2514            e.event.data[0].toHuman() === signer.address);2515    if (!event) throw Error('Cannot find claim in events');2516  }2517}25182519class AddressGroup extends HelperGroup<ChainHelperBase> {2520  /**2521   * Normalizes the address to the specified ss58 format, by default ```42```.2522   * @param address substrate address2523   * @param ss58Format format for address conversion, by default ```42```2524   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2525   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2526   */2527  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2528    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2529  }25302531  /**2532   * Get address in the connected chain format2533   * @param address substrate address2534   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2535   * @returns address in chain format2536   */2537  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2538    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2539  }25402541  /**2542   * Get substrate mirror of an ethereum address2543   * @param ethAddress ethereum address2544   * @param toChainFormat false for normalized account2545   * @example ethToSubstrate('0x9F0583DbB855d...')2546   * @returns substrate mirror of a provided ethereum address2547   */2548  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2549    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2550  }25512552  /**2553   * Get ethereum mirror of a substrate address2554   * @param subAddress substrate account2555   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2556   * @returns ethereum mirror of a provided substrate address2557   */2558  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2559    return CrossAccountId.translateSubToEth(subAddress);2560  }25612562  /**2563   * Encode key to substrate address2564   * @param key key for encoding address2565   * @param ss58Format prefix for encoding to the address of the corresponding network2566   * @returns encoded substrate address2567   */2568  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2569    const u8a :Uint8Array = typeof key === 'string'2570      ? hexToU8a(key)2571      : typeof key === 'bigint'2572        ? hexToU8a(key.toString(16))2573        : key;25742575    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2576      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2577    }25782579    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2580    if (!allowedDecodedLengths.includes(u8a.length)) {2581      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2582    }25832584    const u8aPrefix = ss58Format < 642585      ? new Uint8Array([ss58Format])2586      : new Uint8Array([2587        ((ss58Format & 0xfc) >> 2) | 0x40,2588        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2589      ]);25902591    const input = u8aConcat(u8aPrefix, u8a);25922593    return base58Encode(u8aConcat(2594      input,2595      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2596    ));2597  }25982599  /**2600   * Restore substrate address from bigint representation2601   * @param number decimal representation of substrate address2602   * @returns substrate address2603   */2604  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2605    if (this.helper.api === null) {2606      throw 'Not connected';2607    }2608    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2609    if (res === undefined || res === null) {2610      throw 'Restore address error';2611    }2612    return res.toString();2613  }26142615  /**2616   * Convert etherium cross account id to substrate cross account id2617   * @param ethCrossAccount etherium cross account2618   * @returns substrate cross account id2619   */2620  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2621    if (ethCrossAccount.sub === '0') {2622      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2623    }26242625    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2626    return {Substrate: ss58};2627  }26282629  paraSiblingSovereignAccount(paraid: number) {2630    // We are getting a *sibling* parachain sovereign account,2631    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2632    const siblingPrefix = '0x7369626c';26332634    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2635    const suffix = '000000000000000000000000000000000000000000000000';26362637    return siblingPrefix + encodedParaId + suffix;2638  }2639}26402641class StakingGroup extends HelperGroup<UniqueHelper> {2642  /**2643   * Stake tokens for App Promotion2644   * @param signer keyring of signer2645   * @param amountToStake amount of tokens to stake2646   * @param label extra label for log2647   * @returns2648   */2649  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2650    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2651    const _stakeResult = await this.helper.executeExtrinsic(2652      signer, 'api.tx.appPromotion.stake',2653      [amountToStake], true,2654    );2655    // TODO extract info from stakeResult2656    return true;2657  }26582659  /**2660   * Unstake all staked tokens2661   * @param signer keyring of signer2662   * @param amountToUnstake amount of tokens to unstake2663   * @param label extra label for log2664   * @returns block hash where unstake happened2665   */2666  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2667    if(typeof label === 'undefined') label = `${signer.address}`;2668    const unstakeResult = await this.helper.executeExtrinsic(2669      signer, 'api.tx.appPromotion.unstakeAll',2670      [], true,2671    );2672    return unstakeResult.blockHash;2673  }26742675  /**2676   * Unstake the part of a staked tokens2677   * @param signer keyring of signer2678   * @param amount amount of tokens to unstake2679   * @param label extra label for log2680   * @returns block hash where unstake happened2681   */2682  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2683    if(typeof label === 'undefined') label = `${signer.address}`;2684    const unstakeResult = await this.helper.executeExtrinsic(2685      signer, 'api.tx.appPromotion.unstakePartial',2686      [amount], true,2687    );2688    return unstakeResult.blockHash;2689  }26902691  /**2692   * Get total staked amount for address2693   * @param address substrate or ethereum address2694   * @returns total staked amount2695   */2696  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2697    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2698    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2699  }27002701  /**2702   * Get total staked per block2703   * @param address substrate or ethereum address2704   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2705   */2706  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2707    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2708    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2709      return {2710        block: block.toBigInt(),2711        amount: amount.toBigInt(),2712      };2713    });2714  }27152716  /**2717   * Get total pending unstake amount for address2718   * @param address substrate or ethereum address2719   * @returns total pending unstake amount2720   */2721  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2722    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2723  }27242725  /**2726   * Get pending unstake amount per block for address2727   * @param address substrate or ethereum address2728   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2729   */2730  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2731    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2732    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2733      return {2734        block: block.toBigInt(),2735        amount: amount.toBigInt(),2736      };2737    });2738    return result;2739  }2740}27412742class SchedulerGroup extends HelperGroup<UniqueHelper> {2743  constructor(helper: UniqueHelper) {2744    super(helper);2745  }27462747  cancelScheduled(signer: TSigner, scheduledId: string) {2748    return this.helper.executeExtrinsic(2749      signer,2750      'api.tx.scheduler.cancelNamed',2751      [scheduledId],2752      true,2753    );2754  }27552756  changePriority(signer: TSigner, scheduledId: string, priority: number) {2757    return this.helper.executeExtrinsic(2758      signer,2759      'api.tx.scheduler.changeNamedPriority',2760      [scheduledId, priority],2761      true,2762    );2763  }27642765  scheduleAt<T extends UniqueHelper>(2766    executionBlockNumber: number,2767    options: ISchedulerOptions = {},2768  ) {2769    return this.schedule<T>('schedule', executionBlockNumber, options);2770  }27712772  scheduleAfter<T extends UniqueHelper>(2773    blocksBeforeExecution: number,2774    options: ISchedulerOptions = {},2775  ) {2776    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2777  }27782779  schedule<T extends UniqueHelper>(2780    scheduleFn: 'schedule' | 'scheduleAfter',2781    blocksNum: number,2782    options: ISchedulerOptions = {},2783  ) {2784    // eslint-disable-next-line @typescript-eslint/naming-convention2785    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2786    return this.helper.clone(ScheduledHelperType, {2787      scheduleFn,2788      blocksNum,2789      options,2790    }) as T;2791  }2792}27932794class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2795  //todo:collator documentation2796  addInvulnerable(signer: TSigner, address: string) {2797    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2798  }27992800  removeInvulnerable(signer: TSigner, address: string) {2801    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2802  }28032804  async getInvulnerables(): Promise<string[]> {2805    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2806  }28072808  /** and also total max invulnerables */2809  maxCollators(): number {2810    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2811  }28122813  async getDesiredCollators(): Promise<number> {2814    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2815  }28162817  setLicenseBond(signer: TSigner, amount: bigint) {2818    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2819  }28202821  async getLicenseBond(): Promise<bigint> {2822    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2823  }28242825  obtainLicense(signer: TSigner) {2826    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2827  }28282829  releaseLicense(signer: TSigner) {2830    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2831  }28322833  forceReleaseLicense(signer: TSigner, released: string) {2834    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2835  }28362837  async hasLicense(address: string): Promise<bigint> {2838    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2839  }28402841  onboard(signer: TSigner) {2842    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2843  }28442845  offboard(signer: TSigner) {2846    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2847  }28482849  async getCandidates(): Promise<string[]> {2850    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2851  }2852}28532854class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2855  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2856    await this.helper.executeExtrinsic(2857      signer,2858      'api.tx.foreignAssets.registerForeignAsset',2859      [ownerAddress, location, metadata],2860      true,2861    );2862  }28632864  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2865    await this.helper.executeExtrinsic(2866      signer,2867      'api.tx.foreignAssets.updateForeignAsset',2868      [foreignAssetId, location, metadata],2869      true,2870    );2871  }2872}28732874class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2875  palletName: string;28762877  constructor(helper: T, palletName: string) {2878    super(helper);28792880    this.palletName = palletName;2881  }28822883  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2884    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2885  }28862887  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2888    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2889  }28902891  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2892    const destination = {2893      V1: {2894        parents: 0,2895        interior: {2896          X1: {2897            Parachain: destinationParaId,2898          },2899        },2900      },2901    };29022903    const beneficiary = {2904      V1: {2905        parents: 0,2906        interior: {2907          X1: {2908            AccountId32: {2909              network: 'Any',2910              id: targetAccount,2911            },2912          },2913        },2914      },2915    };29162917    const assets = {2918      V1: [2919        {2920          id: {2921            Concrete: {2922              parents: 0,2923              interior: 'Here',2924            },2925          },2926          fun: {2927            Fungible: amount,2928          },2929        },2930      ],2931    };29322933    const feeAssetItem = 0;29342935    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2936  }2937}29382939class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2940  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2941    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2942  }29432944  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2945    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2946  }29472948  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2949    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2950  }2951}29522953class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2954  async accounts(address: string, currencyId: any) {2955    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2956    return BigInt(free);2957  }2958}29592960class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2961  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2962    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2963  }29642965  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2966    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2967  }29682969  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2970    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2971  }29722973  async account(assetId: string | number, address: string) {2974    const accountAsset = (2975      await this.helper.callRpc('api.query.assets.account', [assetId, address])2976    ).toJSON()! as any;29772978    if (accountAsset !== null) {2979      return BigInt(accountAsset['balance']);2980    } else {2981      return null;2982    }2983  }2984}29852986class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2987  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2988    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2989  }2990}29912992class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {2993  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {2994    const apiPrefix = 'api.tx.assetManager.';29952996    const registerTx = this.helper.constructApiCall(2997      apiPrefix + 'registerForeignAsset',2998      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],2999    );30003001    const setUnitsTx = this.helper.constructApiCall(3002      apiPrefix + 'setAssetUnitsPerSecond',3003      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3004    );30053006    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3007    const encodedProposal = batchCall?.method.toHex() || '';3008    return encodedProposal;3009  }30103011  async assetTypeId(location: any) {3012    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3013  }3014}30153016class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3017  notePreimagePallet: string;30183019  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3020    super(helper);3021    this.notePreimagePallet = options.notePreimagePallet;3022  }30233024  async notePreimage(signer: TSigner, encodedProposal: string) {3025    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3026  }30273028  externalProposeMajority(proposal: any) {3029    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3030  }30313032  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3033    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3034  }30353036  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3037    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3038  }3039}30403041class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3042  collective: string;30433044  constructor(helper: MoonbeamHelper, collective: string) {3045    super(helper);30463047    this.collective = collective;3048  }30493050  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3051    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3052  }30533054  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3055    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3056  }30573058  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3059    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3060  }30613062  async proposalCount() {3063    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3064  }3065}30663067export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3068export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30693070export class UniqueHelper extends ChainHelperBase {3071  balance: BalanceGroup<UniqueHelper>;3072  collection: CollectionGroup;3073  nft: NFTGroup;3074  rft: RFTGroup;3075  ft: FTGroup;3076  staking: StakingGroup;3077  scheduler: SchedulerGroup;3078  collatorSelection: CollatorSelectionGroup;3079  foreignAssets: ForeignAssetsGroup;3080  xcm: XcmGroup<UniqueHelper>;3081  xTokens: XTokensGroup<UniqueHelper>;3082  tokens: TokensGroup<UniqueHelper>;30833084  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3085    super(logger, options.helperBase ?? UniqueHelper);30863087    this.balance = new BalanceGroup(this);3088    this.collection = new CollectionGroup(this);3089    this.nft = new NFTGroup(this);3090    this.rft = new RFTGroup(this);3091    this.ft = new FTGroup(this);3092    this.staking = new StakingGroup(this);3093    this.scheduler = new SchedulerGroup(this);3094    this.collatorSelection = new CollatorSelectionGroup(this);3095    this.foreignAssets = new ForeignAssetsGroup(this);3096    this.xcm = new XcmGroup(this, 'polkadotXcm');3097    this.xTokens = new XTokensGroup(this);3098    this.tokens = new TokensGroup(this);3099  }31003101  getSudo<T extends UniqueHelper>() {3102    // eslint-disable-next-line @typescript-eslint/naming-convention3103    const SudoHelperType = SudoHelper(this.helperBase);3104    return this.clone(SudoHelperType) as T;3105  }3106}31073108export class XcmChainHelper extends ChainHelperBase {3109  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3110    const wsProvider = new WsProvider(wsEndpoint);3111    this.api = new ApiPromise({3112      provider: wsProvider,3113    });3114    await this.api.isReadyOrError;3115    this.network = await UniqueHelper.detectNetwork(this.api);3116  }3117}31183119export class RelayHelper extends XcmChainHelper {3120  balance: SubstrateBalanceGroup<RelayHelper>;3121  xcm: XcmGroup<RelayHelper>;31223123  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3124    super(logger, options.helperBase ?? RelayHelper);31253126    this.balance = new SubstrateBalanceGroup(this);3127    this.xcm = new XcmGroup(this, 'xcmPallet');3128  }3129}31303131export class WestmintHelper extends XcmChainHelper {3132  balance: SubstrateBalanceGroup<WestmintHelper>;3133  xcm: XcmGroup<WestmintHelper>;3134  assets: AssetsGroup<WestmintHelper>;3135  xTokens: XTokensGroup<WestmintHelper>;31363137  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3138    super(logger, options.helperBase ?? WestmintHelper);31393140    this.balance = new SubstrateBalanceGroup(this);3141    this.xcm = new XcmGroup(this, 'polkadotXcm');3142    this.assets = new AssetsGroup(this);3143    this.xTokens = new XTokensGroup(this);3144  }3145}31463147export class MoonbeamHelper extends XcmChainHelper {3148  balance: EthereumBalanceGroup<MoonbeamHelper>;3149  assetManager: MoonbeamAssetManagerGroup;3150  assets: AssetsGroup<MoonbeamHelper>;3151  xTokens: XTokensGroup<MoonbeamHelper>;3152  democracy: MoonbeamDemocracyGroup;3153  collective: {3154    council: MoonbeamCollectiveGroup,3155    techCommittee: MoonbeamCollectiveGroup,3156  };31573158  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3159    super(logger, options.helperBase ?? MoonbeamHelper);31603161    this.balance = new EthereumBalanceGroup(this);3162    this.assetManager = new MoonbeamAssetManagerGroup(this);3163    this.assets = new AssetsGroup(this);3164    this.xTokens = new XTokensGroup(this);3165    this.democracy = new MoonbeamDemocracyGroup(this, options);3166    this.collective = {3167      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3168      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3169    };3170  }3171}31723173export class AcalaHelper extends XcmChainHelper {3174  balance: SubstrateBalanceGroup<AcalaHelper>;3175  assetRegistry: AcalaAssetRegistryGroup;3176  xTokens: XTokensGroup<AcalaHelper>;3177  tokens: TokensGroup<AcalaHelper>;31783179  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3180    super(logger, options.helperBase ?? AcalaHelper);31813182    this.balance = new SubstrateBalanceGroup(this);3183    this.assetRegistry = new AcalaAssetRegistryGroup(this);3184    this.xTokens = new XTokensGroup(this);3185    this.tokens = new TokensGroup(this);3186  }31873188  getSudo<T extends AcalaHelper>() {3189    // eslint-disable-next-line @typescript-eslint/naming-convention3190    const SudoHelperType = SudoHelper(this.helperBase);3191    return this.clone(SudoHelperType) as T;3192  }3193}31943195// eslint-disable-next-line @typescript-eslint/naming-convention3196function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3197  return class extends Base {3198    scheduleFn: 'schedule' | 'scheduleAfter';3199    blocksNum: number;3200    options: ISchedulerOptions;32013202    constructor(...args: any[]) {3203      const logger = args[0] as ILogger;3204      const options = args[1] as {3205        scheduleFn: 'schedule' | 'scheduleAfter',3206        blocksNum: number,3207        options: ISchedulerOptions3208      };32093210      super(logger);32113212      this.scheduleFn = options.scheduleFn;3213      this.blocksNum = options.blocksNum;3214      this.options = options.options;3215    }32163217    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3218      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32193220      const mandatorySchedArgs = [3221        this.blocksNum,3222        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3223        this.options.priority ?? null,3224        scheduledTx,3225      ];32263227      let schedArgs;3228      let scheduleFn;32293230      if (this.options.scheduledId) {3231        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32323233        if (this.scheduleFn == 'schedule') {3234          scheduleFn = 'scheduleNamed';3235        } else if (this.scheduleFn == 'scheduleAfter') {3236          scheduleFn = 'scheduleNamedAfter';3237        }3238      } else {3239        schedArgs = mandatorySchedArgs;3240        scheduleFn = this.scheduleFn;3241      }32423243      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;32443245      return super.executeExtrinsic(3246        sender,3247        extrinsic,3248        schedArgs,3249        expectSuccess,3250      );3251    }3252  };3253}32543255// eslint-disable-next-line @typescript-eslint/naming-convention3256function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3257  return class extends Base {3258    constructor(...args: any[]) {3259      super(...args);3260    }32613262    async executeExtrinsic(3263      sender: IKeyringPair,3264      extrinsic: string,3265      params: any[],3266      expectSuccess?: boolean,3267      options: Partial<SignerOptions>|null = null,3268    ): Promise<ITransactionResult> {3269      const call = this.constructApiCall(extrinsic, params);3270      const result = await super.executeExtrinsic(3271        sender,3272        'api.tx.sudo.sudo',3273        [call],3274        expectSuccess,3275        options,3276      );32773278      if (result.status === 'Fail') return result;32793280      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3281      if (data.isErr) {3282        if (data.asErr.isModule) {3283          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3284          const metaError = super.getApi()?.registry.findMetaError(error);3285          throw new Error(`${metaError.section}.${metaError.name}`);3286        } else {3287          throw new Error(data.asErr.toHuman());3288        }3289      }3290      return result;3291    }3292  };3293}32943295export class UniqueBaseCollection {3296  helper: UniqueHelper;3297  collectionId: number;32983299  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3300    this.collectionId = collectionId;3301    this.helper = uniqueHelper;3302  }33033304  async getData() {3305    return await this.helper.collection.getData(this.collectionId);3306  }33073308  async getLastTokenId() {3309    return await this.helper.collection.getLastTokenId(this.collectionId);3310  }33113312  async doesTokenExist(tokenId: number) {3313    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3314  }33153316  async getAdmins() {3317    return await this.helper.collection.getAdmins(this.collectionId);3318  }33193320  async getAllowList() {3321    return await this.helper.collection.getAllowList(this.collectionId);3322  }33233324  async getEffectiveLimits() {3325    return await this.helper.collection.getEffectiveLimits(this.collectionId);3326  }33273328  async getProperties(propertyKeys?: string[] | null) {3329    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3330  }33313332  async getPropertiesConsumedSpace() {3333    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3334  }33353336  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3337    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3338  }33393340  async getOptions() {3341    return await this.helper.collection.getCollectionOptions(this.collectionId);3342  }33433344  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3345    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3346  }33473348  async confirmSponsorship(signer: TSigner) {3349    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3350  }33513352  async removeSponsor(signer: TSigner) {3353    return await this.helper.collection.removeSponsor(signer, this.collectionId);3354  }33553356  async setLimits(signer: TSigner, limits: ICollectionLimits) {3357    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3358  }33593360  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3361    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3362  }33633364  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3365    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3366  }33673368  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3369    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3370  }33713372  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3373    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3374  }33753376  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3377    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3378  }33793380  async setProperties(signer: TSigner, properties: IProperty[]) {3381    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3382  }33833384  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3385    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3386  }33873388  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3389    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3390  }33913392  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3393    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3394  }33953396  async disableNesting(signer: TSigner) {3397    return await this.helper.collection.disableNesting(signer, this.collectionId);3398  }33993400  async burn(signer: TSigner) {3401    return await this.helper.collection.burn(signer, this.collectionId);3402  }34033404  scheduleAt<T extends UniqueHelper>(3405    executionBlockNumber: number,3406    options: ISchedulerOptions = {},3407  ) {3408    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3409    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3410  }34113412  scheduleAfter<T extends UniqueHelper>(3413    blocksBeforeExecution: number,3414    options: ISchedulerOptions = {},3415  ) {3416    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3417    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3418  }34193420  getSudo<T extends UniqueHelper>() {3421    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3422  }3423}342434253426export class UniqueNFTCollection extends UniqueBaseCollection {3427  getTokenObject(tokenId: number) {3428    return new UniqueNFToken(tokenId, this);3429  }34303431  async getTokensByAddress(addressObj: ICrossAccountId) {3432    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3433  }34343435  async getToken(tokenId: number, blockHashAt?: string) {3436    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3437  }34383439  async getTokenOwner(tokenId: number, blockHashAt?: string) {3440    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3441  }34423443  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3444    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3445  }34463447  async getTokenChildren(tokenId: number, blockHashAt?: string) {3448    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3449  }34503451  async getPropertyPermissions(propertyKeys: string[] | null = null) {3452    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3453  }34543455  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3456    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3457  }34583459  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3460    const api = this.helper.getApi();3461    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34623463    return (props! as any).consumedSpace;3464  }34653466  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3467    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3468  }34693470  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3471    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3472  }34733474  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3475    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3476  }34773478  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3479    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3480  }34813482  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3483    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3484  }34853486  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3487    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3488  }34893490  async burnToken(signer: TSigner, tokenId: number) {3491    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3492  }34933494  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3495    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3496  }34973498  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3499    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3500  }35013502  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3503    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3504  }35053506  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3507    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3508  }35093510  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3511    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3512  }35133514  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3515    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3516  }35173518  scheduleAt<T extends UniqueHelper>(3519    executionBlockNumber: number,3520    options: ISchedulerOptions = {},3521  ) {3522    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3523    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3524  }35253526  scheduleAfter<T extends UniqueHelper>(3527    blocksBeforeExecution: number,3528    options: ISchedulerOptions = {},3529  ) {3530    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3531    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3532  }35333534  getSudo<T extends UniqueHelper>() {3535    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3536  }3537}353835393540export class UniqueRFTCollection extends UniqueBaseCollection {3541  getTokenObject(tokenId: number) {3542    return new UniqueRFToken(tokenId, this);3543  }35443545  async getToken(tokenId: number, blockHashAt?: string) {3546    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3547  }35483549  async getTokenOwner(tokenId: number, blockHashAt?: string) {3550    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3551  }35523553  async getTokensByAddress(addressObj: ICrossAccountId) {3554    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3555  }35563557  async getTop10TokenOwners(tokenId: number) {3558    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3559  }35603561  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3562    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3563  }35643565  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3566    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3567  }35683569  async getTokenTotalPieces(tokenId: number) {3570    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3571  }35723573  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3574    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3575  }35763577  async getPropertyPermissions(propertyKeys: string[] | null = null) {3578    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3579  }35803581  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3582    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3583  }35843585  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3586    const api = this.helper.getApi();3587    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35883589    return (props! as any).consumedSpace;3590  }35913592  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3593    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3594  }35953596  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3597    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3598  }35993600  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3601    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3602  }36033604  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3605    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3606  }36073608  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3609    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3610  }36113612  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3613    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3614  }36153616  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3617    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3618  }36193620  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3621    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3622  }36233624  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3625    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3626  }36273628  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3629    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3630  }36313632  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3633    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3634  }36353636  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3637    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3638  }36393640  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3641    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3642  }36433644  scheduleAt<T extends UniqueHelper>(3645    executionBlockNumber: number,3646    options: ISchedulerOptions = {},3647  ) {3648    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3649    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3650  }36513652  scheduleAfter<T extends UniqueHelper>(3653    blocksBeforeExecution: number,3654    options: ISchedulerOptions = {},3655  ) {3656    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3657    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3658  }36593660  getSudo<T extends UniqueHelper>() {3661    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3662  }3663}366436653666export class UniqueFTCollection extends UniqueBaseCollection {3667  async getBalance(addressObj: ICrossAccountId) {3668    return await this.helper.ft.getBalance(this.collectionId, addressObj);3669  }36703671  async getTotalPieces() {3672    return await this.helper.ft.getTotalPieces(this.collectionId);3673  }36743675  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3676    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3677  }36783679  async getTop10Owners() {3680    return await this.helper.ft.getTop10Owners(this.collectionId);3681  }36823683  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3684    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3685  }36863687  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3688    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3689  }36903691  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3692    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3693  }36943695  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3696    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3697  }36983699  async burnTokens(signer: TSigner, amount=1n) {3700    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3701  }37023703  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3704    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3705  }37063707  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3708    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3709  }37103711  scheduleAt<T extends UniqueHelper>(3712    executionBlockNumber: number,3713    options: ISchedulerOptions = {},3714  ) {3715    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3716    return new UniqueFTCollection(this.collectionId, scheduledHelper);3717  }37183719  scheduleAfter<T extends UniqueHelper>(3720    blocksBeforeExecution: number,3721    options: ISchedulerOptions = {},3722  ) {3723    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3724    return new UniqueFTCollection(this.collectionId, scheduledHelper);3725  }37263727  getSudo<T extends UniqueHelper>() {3728    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3729  }3730}373137323733export class UniqueBaseToken {3734  collection: UniqueNFTCollection | UniqueRFTCollection;3735  collectionId: number;3736  tokenId: number;37373738  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3739    this.collection = collection;3740    this.collectionId = collection.collectionId;3741    this.tokenId = tokenId;3742  }37433744  async getNextSponsored(addressObj: ICrossAccountId) {3745    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3746  }37473748  async getProperties(propertyKeys?: string[] | null) {3749    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3750  }37513752  async getTokenPropertiesConsumedSpace() {3753    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3754  }37553756  async setProperties(signer: TSigner, properties: IProperty[]) {3757    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3758  }37593760  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3761    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3762  }37633764  async doesExist() {3765    return await this.collection.doesTokenExist(this.tokenId);3766  }37673768  nestingAccount() {3769    return this.collection.helper.util.getTokenAccount(this);3770  }37713772  scheduleAt<T extends UniqueHelper>(3773    executionBlockNumber: number,3774    options: ISchedulerOptions = {},3775  ) {3776    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3777    return new UniqueBaseToken(this.tokenId, scheduledCollection);3778  }37793780  scheduleAfter<T extends UniqueHelper>(3781    blocksBeforeExecution: number,3782    options: ISchedulerOptions = {},3783  ) {3784    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3785    return new UniqueBaseToken(this.tokenId, scheduledCollection);3786  }37873788  getSudo<T extends UniqueHelper>() {3789    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3790  }3791}379237933794export class UniqueNFToken extends UniqueBaseToken {3795  collection: UniqueNFTCollection;37963797  constructor(tokenId: number, collection: UniqueNFTCollection) {3798    super(tokenId, collection);3799    this.collection = collection;3800  }38013802  async getData(blockHashAt?: string) {3803    return await this.collection.getToken(this.tokenId, blockHashAt);3804  }38053806  async getOwner(blockHashAt?: string) {3807    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3808  }38093810  async getTopmostOwner(blockHashAt?: string) {3811    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3812  }38133814  async getChildren(blockHashAt?: string) {3815    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3816  }38173818  async nest(signer: TSigner, toTokenObj: IToken) {3819    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3820  }38213822  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3823    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3824  }38253826  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3827    return await this.collection.transferToken(signer, this.tokenId, addressObj);3828  }38293830  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3831    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3832  }38333834  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3835    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3836  }38373838  async isApproved(toAddressObj: ICrossAccountId) {3839    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3840  }38413842  async burn(signer: TSigner) {3843    return await this.collection.burnToken(signer, this.tokenId);3844  }38453846  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3847    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3848  }38493850  scheduleAt<T extends UniqueHelper>(3851    executionBlockNumber: number,3852    options: ISchedulerOptions = {},3853  ) {3854    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3855    return new UniqueNFToken(this.tokenId, scheduledCollection);3856  }38573858  scheduleAfter<T extends UniqueHelper>(3859    blocksBeforeExecution: number,3860    options: ISchedulerOptions = {},3861  ) {3862    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3863    return new UniqueNFToken(this.tokenId, scheduledCollection);3864  }38653866  getSudo<T extends UniqueHelper>() {3867    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3868  }3869}38703871export class UniqueRFToken extends UniqueBaseToken {3872  collection: UniqueRFTCollection;38733874  constructor(tokenId: number, collection: UniqueRFTCollection) {3875    super(tokenId, collection);3876    this.collection = collection;3877  }38783879  async getData(blockHashAt?: string) {3880    return await this.collection.getToken(this.tokenId, blockHashAt);3881  }38823883  async getOwner(blockHashAt?: string) {3884    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3885  }38863887  async getTop10Owners() {3888    return await this.collection.getTop10TokenOwners(this.tokenId);3889  }38903891  async getTopmostOwner(blockHashAt?: string) {3892    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3893  }38943895  async nest(signer: TSigner, toTokenObj: IToken) {3896    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3897  }38983899  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3900    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3901  }39023903  async getBalance(addressObj: ICrossAccountId) {3904    return await this.collection.getTokenBalance(this.tokenId, addressObj);3905  }39063907  async getTotalPieces() {3908    return await this.collection.getTokenTotalPieces(this.tokenId);3909  }39103911  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3912    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3913  }39143915  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3916    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3917  }39183919  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3920    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3921  }39223923  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3924    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3925  }39263927  async repartition(signer: TSigner, amount: bigint) {3928    return await this.collection.repartitionToken(signer, this.tokenId, amount);3929  }39303931  async burn(signer: TSigner, amount=1n) {3932    return await this.collection.burnToken(signer, this.tokenId, amount);3933  }39343935  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3936    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3937  }39383939  scheduleAt<T extends UniqueHelper>(3940    executionBlockNumber: number,3941    options: ISchedulerOptions = {},3942  ) {3943    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3944    return new UniqueRFToken(this.tokenId, scheduledCollection);3945  }39463947  scheduleAfter<T extends UniqueHelper>(3948    blocksBeforeExecution: number,3949    options: ISchedulerOptions = {},3950  ) {3951    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3952    return new UniqueRFToken(this.tokenId, scheduledCollection);3953  }39543955  getSudo<T extends UniqueHelper>() {3956    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3957  }3958}
after · tests/src/util/playgrounds/unique.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm, base58Encode, blake2AsU8a} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {hexToU8a} from '@polkadot/util/hex';13import {u8aConcat} from '@polkadot/util/u8a';14import {15  IApiListeners,16  IBlock,17  IEvent,18  IChainProperties,19  ICollectionCreationOptions,20  ICollectionLimits,21  ICollectionPermissions,22  ICrossAccountId,23  ICrossAccountIdLower,24  ILogger,25  INestingPermissions,26  IProperty,27  IStakingInfo,28  ISchedulerOptions,29  ISubstrateBalance,30  IToken,31  ITokenPropertyPermission,32  ITransactionResult,33  IUniqueHelperLog,34  TApiAllowedListeners,35  TEthereumAccount,36  TSigner,37  TSubstrateAccount,38  TNetworks,39  IForeignAssetMetadata,40  AcalaAssetMetadata,41  MoonbeamAssetInfo,42  DemocracyStandardAccountVote,43  IEthCrossAccountId,44} from './types';45import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';46import type {Vec} from '@polkadot/types-codec';47import {FrameSystemEventRecord} from '@polkadot/types/lookup';4849export class CrossAccountId implements ICrossAccountId {50  Substrate?: TSubstrateAccount;51  Ethereum?: TEthereumAccount;5253  constructor(account: ICrossAccountId) {54    if (account.Substrate) this.Substrate = account.Substrate;55    if (account.Ethereum) this.Ethereum = account.Ethereum;56  }5758  static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {59    switch (domain) {60      case 'Substrate': return new CrossAccountId({Substrate: account.address});61      case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();62    }63  }6465  static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {66    return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});67  }6869  static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {70    return encodeAddress(decodeAddress(address), ss58Format);71  }7273  static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {74    return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});75  }7677  withNormalizedSubstrate(ss58Format = 42): CrossAccountId {78    if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);79    return this;80  }8182  static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {83    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));84  }8586  toEthereum(): CrossAccountId {87    if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});88    return this;89  }9091  static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {92    return evmToAddress(address, ss58Format);93  }9495  toSubstrate(ss58Format?: number): CrossAccountId {96    if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});97    return this;98  }99100  toLowerCase(): CrossAccountId {101    if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();102    if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();103    return this;104  }105}106107const nesting = {108  toChecksumAddress(address: string): string {109    if (typeof address === 'undefined') return '';110111    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);112113    address = address.toLowerCase().replace(/^0x/i,'');114    const addressHash = keccakAsHex(address).replace(/^0x/i,'');115    const checksumAddress = ['0x'];116117    for (let i = 0; i < address.length; i++) {118      // If ith character is 8 to f then make it uppercase119      if (parseInt(addressHash[i], 16) > 7) {120        checksumAddress.push(address[i].toUpperCase());121      } else {122        checksumAddress.push(address[i]);123      }124    }125    return checksumAddress.join('');126  },127  tokenIdToAddress(collectionId: number, tokenId: number) {128    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);129  },130};131132class UniqueUtil {133  static transactionStatus = {134    NOT_READY: 'NotReady',135    FAIL: 'Fail',136    SUCCESS: 'Success',137  };138139  static chainLogType = {140    EXTRINSIC: 'extrinsic',141    RPC: 'rpc',142  };143144  static getTokenAccount(token: IToken): CrossAccountId {145    return new CrossAccountId({Ethereum: this.getTokenAddress(token)});146  }147148  static getTokenAddress(token: IToken): string {149    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);150  }151152  static getDefaultLogger(): ILogger {153    return {154      log(msg: any, level = 'INFO') {155        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));156      },157      level: {158        ERROR: 'ERROR',159        WARNING: 'WARNING',160        INFO: 'INFO',161      },162    };163  }164165  static vec2str(arr: string[] | number[]) {166    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');167  }168169  static str2vec(string: string) {170    if (typeof string !== 'string') return string;171    return Array.from(string).map(x => x.charCodeAt(0));172  }173174  static fromSeed(seed: string, ss58Format = 42) {175    const keyring = new Keyring({type: 'sr25519', ss58Format});176    return keyring.addFromUri(seed);177  }178179  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {180    if (creationResult.status !== this.transactionStatus.SUCCESS) {181      throw Error('Unable to create collection!');182    }183184    let collectionId = null;185    creationResult.result.events.forEach(({event: {data, method, section}}) => {186      if ((section === 'common') && (method === 'CollectionCreated')) {187        collectionId = parseInt(data[0].toString(), 10);188      }189    });190191    if (collectionId === null) {192      throw Error('No CollectionCreated event was found!');193    }194195    return collectionId;196  }197198  static extractTokensFromCreationResult(creationResult: ITransactionResult): {199    success: boolean,200    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],201  } {202    if (creationResult.status !== this.transactionStatus.SUCCESS) {203      throw Error('Unable to create tokens!');204    }205    let success = false;206    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];207    creationResult.result.events.forEach(({event: {data, method, section}}) => {208      if (method === 'ExtrinsicSuccess') {209        success = true;210      } else if ((section === 'common') && (method === 'ItemCreated')) {211        tokens.push({212          collectionId: parseInt(data[0].toString(), 10),213          tokenId: parseInt(data[1].toString(), 10),214          owner: data[2].toHuman(),215          amount: data[3].toBigInt(),216        });217      }218    });219    return {success, tokens};220  }221222  static extractTokensFromBurnResult(burnResult: ITransactionResult): {223    success: boolean,224    tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],225  } {226    if (burnResult.status !== this.transactionStatus.SUCCESS) {227      throw Error('Unable to burn tokens!');228    }229    let success = false;230    const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];231    burnResult.result.events.forEach(({event: {data, method, section}}) => {232      if (method === 'ExtrinsicSuccess') {233        success = true;234      } else if ((section === 'common') && (method === 'ItemDestroyed')) {235        tokens.push({236          collectionId: parseInt(data[0].toString(), 10),237          tokenId: parseInt(data[1].toString(), 10),238          owner: data[2].toHuman(),239          amount: data[3].toBigInt(),240        });241      }242    });243    return {success, tokens};244  }245246  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {247    let eventId = null;248    events.forEach(({event: {data, method, section}}) => {249      if ((section === expectedSection) && (method === expectedMethod)) {250        eventId = parseInt(data[0].toString(), 10);251      }252    });253254    if (eventId === null) {255      throw Error(`No ${expectedMethod} event was found!`);256    }257    return eventId === collectionId;258  }259260  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {261    const normalizeAddress = (address: string | ICrossAccountId) => {262      if(typeof address === 'string') return address;263      const obj = {} as any;264      Object.keys(address).forEach(k => {265        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];266      });267      if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);268      if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();269      return address;270    };271    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;272    events.forEach(({event: {data, method, section}}) => {273      if ((section === 'common') && (method === 'Transfer')) {274        const hData = (data as any).toJSON();275        transfer = {276          collectionId: hData[0],277          tokenId: hData[1],278          from: normalizeAddress(hData[2]),279          to: normalizeAddress(hData[3]),280          amount: BigInt(hData[4]),281        };282      }283    });284    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;285    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);286    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);287    isSuccess = isSuccess && amount === transfer.amount;288    return isSuccess;289  }290291  static bigIntToDecimals(number: bigint, decimals = 18) {292    const numberStr = number.toString();293    const dotPos = numberStr.length - decimals;294295    if (dotPos <= 0) {296      return '0.' + '0'.repeat(Math.abs(dotPos)) + numberStr;297    } else {298      const intPart = numberStr.substring(0, dotPos);299      const fractPart = numberStr.substring(dotPos);300      return intPart + '.' + fractPart;301    }302  }303}304305class UniqueEventHelper {306  private static extractIndex(index: any): [number, number] | string {307    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];308    return index.toJSON();309  }310311  private static extractSub(data: any, subTypes: any): {[key: string]: any} {312    let obj: any = {};313    let index = 0;314315    if (data.entries) {316      for(const [key, value] of data.entries()) {317        obj[key] = this.extractData(value, subTypes[index]);318        index++;319      }320    } else obj = data.toJSON();321322    return obj;323  }324325  private static toHuman(data: any) {326    return data && data.toHuman ? data.toHuman() : `${data}`;327  }328329  private static extractData(data: any, type: any): any {330    if(!type) return this.toHuman(data);331    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();332    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();333    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);334    return this.toHuman(data);335  }336337  public static extractEvents(events: {event: any, phase: any}[]): IEvent[] {338    const parsedEvents: IEvent[] = [];339340    events.forEach((record) => {341      const {event, phase} = record;342      const types = event.typeDef;343344      const eventData: IEvent = {345        section: event.section.toString(),346        method: event.method.toString(),347        index: this.extractIndex(event.index),348        data: [],349        phase: phase.toJSON(),350      };351352      event.data.forEach((val: any, index: number) => {353        eventData.data.push(this.extractData(val, types[index]));354      });355356      parsedEvents.push(eventData);357    });358359    return parsedEvents;360  }361}362363export class ChainHelperBase {364  helperBase: any;365366  transactionStatus = UniqueUtil.transactionStatus;367  chainLogType = UniqueUtil.chainLogType;368  util: typeof UniqueUtil;369  eventHelper: typeof UniqueEventHelper;370  logger: ILogger;371  api: ApiPromise | null;372  forcedNetwork: TNetworks | null;373  network: TNetworks | null;374  wsEndpoint: string | null;375  chainLog: IUniqueHelperLog[];376  children: ChainHelperBase[];377  address: AddressGroup;378  chain: ChainGroup;379380  constructor(logger?: ILogger, helperBase?: any) {381    this.helperBase = helperBase;382383    this.util = UniqueUtil;384    this.eventHelper = UniqueEventHelper;385    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();386    this.logger = logger;387    this.api = null;388    this.forcedNetwork = null;389    this.network = null;390    this.wsEndpoint = null;391    this.chainLog = [];392    this.children = [];393    this.address = new AddressGroup(this);394    this.chain = new ChainGroup(this);395  }396397  clone(helperCls: ChainHelperBaseConstructor, options: {[key: string]: any} = {}) {398    Object.setPrototypeOf(helperCls.prototype, this);399    const newHelper = new helperCls(this.logger, options);400401    newHelper.api = this.api;402    newHelper.network = this.network;403    newHelper.forceNetwork = this.forceNetwork;404405    this.children.push(newHelper);406407    return newHelper;408  }409410  getEndpoint(): string {411    if (this.wsEndpoint === null) throw Error('No connection was established');412    return this.wsEndpoint;413  }414415  getApi(): ApiPromise {416    if(this.api === null) throw Error('API not initialized');417    return this.api;418  }419420  async subscribeEvents(expectedEvents: {section: string, names: string[]}[]) {421    const collectedEvents: IEvent[] = [];422    const unsubscribe = await this.getApi().query.system.events((events: Vec<FrameSystemEventRecord>) => {423      const ievents = this.eventHelper.extractEvents(events);424      ievents.forEach((event) => {425        expectedEvents.forEach((e => {426          if (event.section === e.section && e.names.includes(event.method)) {427            collectedEvents.push(event);428          }429        }));430      });431    });432    return {unsubscribe: unsubscribe as any, collectedEvents};433  }434435  clearChainLog(): void {436    this.chainLog = [];437  }438439  forceNetwork(value: TNetworks): void {440    this.forcedNetwork = value;441  }442443  async connect(wsEndpoint: string, listeners?: IApiListeners) {444    if (this.api !== null) throw Error('Already connected');445    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);446    this.wsEndpoint = wsEndpoint;447    this.api = api;448    this.network = network;449  }450451  async disconnect() {452    for (const child of this.children) {453      child.clearApi();454    }455456    if (this.api === null) return;457    await this.api.disconnect();458    this.clearApi();459  }460461  clearApi() {462    this.api = null;463    this.network = null;464  }465466  static async detectNetwork(api: ApiPromise): Promise<TNetworks> {467    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;468    const xcmChains = ['rococo', 'westend', 'westmint', 'acala', 'karura', 'moonbeam', 'moonriver'];469470    if(xcmChains.indexOf(spec.specName) > -1) return spec.specName;471472    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;473    return 'opal';474  }475476  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TNetworks> {477    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});478    await api.isReady;479480    const network = await this.detectNetwork(api);481482    await api.disconnect();483484    return network;485  }486487  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TNetworks | null): Promise<{488    api: ApiPromise;489    network: TNetworks;490  }> {491    if(typeof network === 'undefined' || network === null) network = 'opal';492    const supportedRPC = {493      opal: {494        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,495      },496      quartz: {497        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,498      },499      unique: {500        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,501      },502      rococo: {},503      westend: {},504      moonbeam: {},505      moonriver: {},506      acala: {},507      karura: {},508      westmint: {},509    };510    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);511    const rpc = supportedRPC[network];512513    // TODO: investigate how to replace rpc in runtime514    // api._rpcCore.addUserInterfaces(rpc);515516    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});517518    await api.isReadyOrError;519520    if (typeof listeners === 'undefined') listeners = {};521    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {522      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;523      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);524    }525526    return {api, network};527  }528529  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {530    const {events, status} = data;531    if (status.isReady) {532      return this.transactionStatus.NOT_READY;533    }534    if (status.isBroadcast) {535      return this.transactionStatus.NOT_READY;536    }537    if (status.isInBlock || status.isFinalized) {538      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');539      if (errors.length > 0) {540        return this.transactionStatus.FAIL;541      }542      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {543        return this.transactionStatus.SUCCESS;544      }545    }546547    return this.transactionStatus.FAIL;548  }549550  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {551    const sign = (callback: any) => {552      if(options !== null) return transaction.signAndSend(sender, options, callback);553      return transaction.signAndSend(sender, callback);554    };555    // eslint-disable-next-line no-async-promise-executor556    return new Promise(async (resolve, reject) => {557      try {558        const unsub = await sign((result: any) => {559          const status = this.getTransactionStatus(result);560561          if (status === this.transactionStatus.SUCCESS) {562            this.logger.log(`${label} successful`);563            unsub();564            resolve({result, status, blockHash: result.status.asInBlock.toHuman()});565          } else if (status === this.transactionStatus.FAIL) {566            let moduleError = null;567568            if (result.hasOwnProperty('dispatchError')) {569              const dispatchError = result['dispatchError'];570571              if (dispatchError) {572                if (dispatchError.isModule) {573                  const modErr = dispatchError.asModule;574                  const errorMeta = dispatchError.registry.findMetaError(modErr);575576                  moduleError = `${errorMeta.section}.${errorMeta.name}`;577                } else {578                  moduleError = dispatchError.toHuman();579                }580              } else {581                this.logger.log(result, this.logger.level.ERROR);582              }583            }584585            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);586            unsub();587            reject({status, moduleError, result});588          }589        });590      } catch (e) {591        this.logger.log(e, this.logger.level.ERROR);592        reject(e);593      }594    });595  }596597  async signTransactionWithoutSending(signer: TSigner, tx: any) {598    const api = this.getApi();599    const signingInfo = await api.derive.tx.signingInfo(signer.address);600601    tx.sign(signer, {602      blockHash: api.genesisHash,603      genesisHash: api.genesisHash,604      runtimeVersion: api.runtimeVersion,605      nonce: signingInfo.nonce,606    });607608    return tx.toHex();609  }610611  async getPaymentInfo(signer: TSigner, tx: any, len: number | null) {612    const api = this.getApi();613    const signingInfo = await api.derive.tx.signingInfo(signer.address);614615    // We need to sign the tx because616    // unsigned transactions does not have an inclusion fee617    tx.sign(signer, {618      blockHash: api.genesisHash,619      genesisHash: api.genesisHash,620      runtimeVersion: api.runtimeVersion,621      nonce: signingInfo.nonce,622    });623624    if (len === null) {625      return (await this.callRpc('api.rpc.payment.queryInfo', [tx.toHex()])) as RuntimeDispatchInfo;626    } else {627      return (await api.call.transactionPaymentApi.queryInfo(tx, len)) as RuntimeDispatchInfo;628    }629  }630631  constructApiCall(apiCall: string, params: any[]) {632    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);633    let call = this.getApi() as any;634    for(const part of apiCall.slice(4).split('.')) {635      call = call[part];636      if (!call) {637        const advice = part.includes('_') ? ' Looks like it needs to be converted to camel case.' : '';638        throw Error(`Function ${part} of api call ${apiCall} not found.${advice}`);639      }640    }641    return call(...params);642  }643644  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {645    if(this.api === null) throw Error('API not initialized');646    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);647648    const startTime = (new Date()).getTime();649    let result: ITransactionResult;650    let events: IEvent[] = [];651    try {652      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;653      events = this.eventHelper.extractEvents(result.result.events);654      const errorEvent = events.find((event) => event.method == 'ExecutedFailed' || event.method == 'CreatedFailed');655      if (errorEvent)656        throw Error(errorEvent.method + ': ' + extrinsic);657    }658    catch(e) {659      if(!(e as object).hasOwnProperty('status')) throw e;660      result = e as ITransactionResult;661    }662663    const endTime = (new Date()).getTime();664665    const log = {666      executedAt: endTime,667      executionTime: endTime - startTime,668      type: this.chainLogType.EXTRINSIC,669      status: result.status,670      call: extrinsic,671      signer: this.getSignerAddress(sender),672      params,673    } as IUniqueHelperLog;674675    if(result.status !== this.transactionStatus.SUCCESS) {676      if (result.moduleError) log.moduleError = result.moduleError;677      else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;678    }679    if(events.length > 0) log.events = events;680681    this.chainLog.push(log);682683    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {684      if (result.moduleError) throw Error(`${result.moduleError}`);685      else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));686    }687    return result;688  }689690  async callRpc(rpc: string, params?: any[]) {691    if(typeof params === 'undefined') params = [];692    if(this.api === null) throw Error('API not initialized');693    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);694695    const startTime = (new Date()).getTime();696    let result;697    let error = null;698    const log = {699      type: this.chainLogType.RPC,700      call: rpc,701      params,702    } as IUniqueHelperLog;703704    try {705      result = await this.constructApiCall(rpc, params);706    }707    catch(e) {708      error = e;709    }710711    const endTime = (new Date()).getTime();712713    log.executedAt = endTime;714    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';715    log.executionTime = endTime - startTime;716717    this.chainLog.push(log);718719    if(error !== null) throw error;720721    return result;722  }723724  getSignerAddress(signer: IKeyringPair | string): string {725    if(typeof signer === 'string') return signer;726    return signer.address;727  }728729  fetchAllPalletNames(): string[] {730    if(this.api === null) throw Error('API not initialized');731    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());732  }733734  fetchMissingPalletNames(requiredPallets: string[]): string[] {735    const palletNames = this.fetchAllPalletNames();736    return requiredPallets.filter(p => !palletNames.includes(p));737  }738}739740741class HelperGroup<T extends ChainHelperBase> {742  helper: T;743744  constructor(uniqueHelper: T) {745    this.helper = uniqueHelper;746  }747}748749750class CollectionGroup extends HelperGroup<UniqueHelper> {751  /**752 * Get number of blocks when sponsored transaction is available.753 *754 * @param collectionId ID of collection755 * @param tokenId ID of token756 * @param addressObj address for which the sponsorship is checked757 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});758 * @returns number of blocks or null if sponsorship hasn't been set759 */760  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {761    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();762  }763764  /**765   * Get the number of created collections.766   *767   * @returns number of created collections768   */769  async getTotalCount(): Promise<number> {770    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();771  }772773  /**774   * Get information about the collection with additional data,775   * including the number of tokens it contains, its administrators,776   * the normalized address of the collection's owner, and decoded name and description.777   *778   * @param collectionId ID of collection779   * @example await getData(2)780   * @returns collection information object781   */782  async getData(collectionId: number): Promise<{783    id: number;784    name: string;785    description: string;786    tokensCount: number;787    admins: CrossAccountId[];788    normalizedOwner: TSubstrateAccount;789    raw: any790  } | null> {791    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);792    const humanCollection = collection.toHuman(), collectionData = {793      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],794      raw: humanCollection,795    } as any, jsonCollection = collection.toJSON();796    if (humanCollection === null) return null;797    collectionData.raw.limits = jsonCollection.limits;798    collectionData.raw.permissions = jsonCollection.permissions;799    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);800    for (const key of ['name', 'description']) {801      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);802    }803804    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))805      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)806      : 0;807    collectionData.admins = await this.getAdmins(collectionId);808809    return collectionData;810  }811812  /**813   * Get the addresses of the collection's administrators, optionally normalized.814   *815   * @param collectionId ID of collection816   * @param normalize whether to normalize the addresses to the default ss58 format817   * @example await getAdmins(1)818   * @returns array of administrators819   */820  async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {821    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();822823    return normalize824      ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())825      : admins;826  }827828  /**829   * Get the addresses added to the collection allow-list, optionally normalized.830   * @param collectionId ID of collection831   * @param normalize whether to normalize the addresses to the default ss58 format832   * @example await getAllowList(1)833   * @returns array of allow-listed addresses834   */835  async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {836    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();837    return normalize838      ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())839      : allowListed;840  }841842  /**843   * Get the effective limits of the collection instead of null for default values844   *845   * @param collectionId ID of collection846   * @example await getEffectiveLimits(2)847   * @returns object of collection limits848   */849  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {850    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();851  }852853  /**854   * Burns the collection if the signer has sufficient permissions and collection is empty.855   *856   * @param signer keyring of signer857   * @param collectionId ID of collection858   * @example await helper.collection.burn(aliceKeyring, 3);859   * @returns ```true``` if extrinsic success, otherwise ```false```860   */861  async burn(signer: TSigner, collectionId: number): Promise<boolean> {862    const result = await this.helper.executeExtrinsic(863      signer,864      'api.tx.unique.destroyCollection', [collectionId],865      true,866    );867868    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');869  }870871  /**872   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.873   *874   * @param signer keyring of signer875   * @param collectionId ID of collection876   * @param sponsorAddress Sponsor substrate address877   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")878   * @returns ```true``` if extrinsic success, otherwise ```false```879   */880  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {881    const result = await this.helper.executeExtrinsic(882      signer,883      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],884      true,885    );886887    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorSet');888  }889890  /**891   * Confirms consent to sponsor the collection on behalf of the signer.892   *893   * @param signer keyring of signer894   * @param collectionId ID of collection895   * @example confirmSponsorship(aliceKeyring, 10)896   * @returns ```true``` if extrinsic success, otherwise ```false```897   */898  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {899    const result = await this.helper.executeExtrinsic(900      signer,901      'api.tx.unique.confirmSponsorship', [collectionId],902      true,903    );904905    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'SponsorshipConfirmed');906  }907908  /**909   * Removes the sponsor of a collection, regardless if it consented or not.910   *911   * @param signer keyring of signer912   * @param collectionId ID of collection913   * @example removeSponsor(aliceKeyring, 10)914   * @returns ```true``` if extrinsic success, otherwise ```false```915   */916  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {917    const result = await this.helper.executeExtrinsic(918      signer,919      'api.tx.unique.removeCollectionSponsor', [collectionId],920      true,921    );922923    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionSponsorRemoved');924  }925926  /**927   * Sets the limits of the collection. At least one limit must be specified for a correct call.928   *929   * @param signer keyring of signer930   * @param collectionId ID of collection931   * @param limits collection limits object932   * @example933   * await setLimits(934   *   aliceKeyring,935   *   10,936   *   {937   *     sponsorTransferTimeout: 0,938   *     ownerCanDestroy: false939   *   }940   * )941   * @returns ```true``` if extrinsic success, otherwise ```false```942   */943  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {944    const result = await this.helper.executeExtrinsic(945      signer,946      'api.tx.unique.setCollectionLimits', [collectionId, limits],947      true,948    );949950    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionLimitSet');951  }952953  /**954   * Changes the owner of the collection to the new Substrate address.955   *956   * @param signer keyring of signer957   * @param collectionId ID of collection958   * @param ownerAddress substrate address of new owner959   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")960   * @returns ```true``` if extrinsic success, otherwise ```false```961   */962  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {963    const result = await this.helper.executeExtrinsic(964      signer,965      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],966      true,967    );968969    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionOwnerChanged');970  }971972  /**973   * Adds a collection administrator.974   *975   * @param signer keyring of signer976   * @param collectionId ID of collection977   * @param adminAddressObj Administrator address (substrate or ethereum)978   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})979   * @returns ```true``` if extrinsic success, otherwise ```false```980   */981  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {982    const result = await this.helper.executeExtrinsic(983      signer,984      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],985      true,986    );987988    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminAdded');989  }990991  /**992   * Removes a collection administrator.993   *994   * @param signer keyring of signer995   * @param collectionId ID of collection996   * @param adminAddressObj Administrator address (substrate or ethereum)997   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})998   * @returns ```true``` if extrinsic success, otherwise ```false```999   */1000  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {1001    const result = await this.helper.executeExtrinsic(1002      signer,1003      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],1004      true,1005    );10061007    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionAdminRemoved');1008  }10091010  /**1011   * Check if user is in allow list.1012   *1013   * @param collectionId ID of collection1014   * @param user Account to check1015   * @example await getAdmins(1)1016   * @returns is user in allow list1017   */1018  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {1019    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();1020  }10211022  /**1023   * Adds an address to allow list1024   * @param signer keyring of signer1025   * @param collectionId ID of collection1026   * @param addressObj address to add to the allow list1027   * @returns ```true``` if extrinsic success, otherwise ```false```1028   */1029  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1030    const result = await this.helper.executeExtrinsic(1031      signer,1032      'api.tx.unique.addToAllowList', [collectionId, addressObj],1033      true,1034    );10351036    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressAdded');1037  }10381039  /**1040   * Removes an address from allow list1041   *1042   * @param signer keyring of signer1043   * @param collectionId ID of collection1044   * @param addressObj address to remove from the allow list1045   * @returns ```true``` if extrinsic success, otherwise ```false```1046   */1047  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {1048    const result = await this.helper.executeExtrinsic(1049      signer,1050      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],1051      true,1052    );10531054    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'AllowListAddressRemoved');1055  }10561057  /**1058   * Sets onchain permissions for selected collection.1059   *1060   * @param signer keyring of signer1061   * @param collectionId ID of collection1062   * @param permissions collection permissions object1063   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});1064   * @returns ```true``` if extrinsic success, otherwise ```false```1065   */1066  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {1067    const result = await this.helper.executeExtrinsic(1068      signer,1069      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],1070      true,1071    );10721073    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPermissionSet');1074  }10751076  /**1077   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.1078   *1079   * @param signer keyring of signer1080   * @param collectionId ID of collection1081   * @param permissions nesting permissions object1082   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});1083   * @returns ```true``` if extrinsic success, otherwise ```false```1084   */1085  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {1086    return await this.setPermissions(signer, collectionId, {nesting: permissions});1087  }10881089  /**1090   * Disables nesting for selected collection.1091   *1092   * @param signer keyring of signer1093   * @param collectionId ID of collection1094   * @example disableNesting(aliceKeyring, 10);1095   * @returns ```true``` if extrinsic success, otherwise ```false```1096   */1097  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {1098    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});1099  }11001101  /**1102   * Sets onchain properties to the collection.1103   *1104   * @param signer keyring of signer1105   * @param collectionId ID of collection1106   * @param properties array of property objects1107   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);1108   * @returns ```true``` if extrinsic success, otherwise ```false```1109   */1110  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {1111    const result = await this.helper.executeExtrinsic(1112      signer,1113      'api.tx.unique.setCollectionProperties', [collectionId, properties],1114      true,1115    );11161117    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');1118  }11191120  /**1121   * Get collection properties.1122   *1123   * @param collectionId ID of collection1124   * @param propertyKeys optionally filter the returned properties to only these keys1125   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);1126   * @returns array of key-value pairs1127   */1128  async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1129    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();1130  }11311132  async getPropertiesConsumedSpace(collectionId: number): Promise<number> {1133    const api = this.helper.getApi();1134    const props = (await api.query.common.collectionProperties(collectionId)).toJSON();11351136    return (props! as any).consumedSpace;1137  }11381139  async getCollectionOptions(collectionId: number) {1140    return (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1141  }11421143  /**1144   * Deletes onchain properties from the collection.1145   *1146   * @param signer keyring of signer1147   * @param collectionId ID of collection1148   * @param propertyKeys array of property keys to delete1149   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);1150   * @returns ```true``` if extrinsic success, otherwise ```false```1151   */1152  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {1153    const result = await this.helper.executeExtrinsic(1154      signer,1155      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],1156      true,1157    );11581159    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1160  }11611162  /**1163   * Changes the owner of the token.1164   *1165   * @param signer keyring of signer1166   * @param collectionId ID of collection1167   * @param tokenId ID of token1168   * @param addressObj address of a new owner1169   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1170   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1171   * @returns true if the token success, otherwise false1172   */1173  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1174    const result = await this.helper.executeExtrinsic(1175      signer,1176      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1177      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1178    );11791180    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1181  }11821183  /**1184   *1185   * Change ownership of a token(s) on behalf of the owner.1186   *1187   * @param signer keyring of signer1188   * @param collectionId ID of collection1189   * @param tokenId ID of token1190   * @param fromAddressObj address on behalf of which the token will be sent1191   * @param toAddressObj new token owner1192   * @param amount amount of tokens to be transfered. For NFT must be set to 1n1193   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1194   * @returns true if the token success, otherwise false1195   */1196  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1197    const result = await this.helper.executeExtrinsic(1198      signer,1199      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1200      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1201    );1202    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1203  }12041205  /**1206   *1207   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1208   *1209   * @param signer keyring of signer1210   * @param collectionId ID of collection1211   * @param tokenId ID of token1212   * @param amount amount of tokens to be burned. For NFT must be set to 1n1213   * @example burnToken(aliceKeyring, 10, 5);1214   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1215   */1216  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1217    const burnResult = await this.helper.executeExtrinsic(1218      signer,1219      'api.tx.unique.burnItem', [collectionId, tokenId, amount],1220      true, // `Unable to burn token for ${label}`,1221    );1222    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1223    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1224    return burnedTokens.success;1225  }12261227  /**1228   * Destroys a concrete instance of NFT on behalf of the owner1229   *1230   * @param signer keyring of signer1231   * @param collectionId ID of collection1232   * @param tokenId ID of token1233   * @param fromAddressObj address on behalf of which the token will be burnt1234   * @param amount amount of tokens to be burned. For NFT must be set to 1n1235   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1236   * @returns ```true``` if extrinsic success, otherwise ```false```1237   */1238  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1239    const burnResult = await this.helper.executeExtrinsic(1240      signer,1241      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1242      true, // `Unable to burn token from for ${label}`,1243    );1244    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1245    return burnedTokens.success && burnedTokens.tokens.length > 0;1246  }12471248  /**1249   * Set, change, or remove approved address to transfer the ownership of the NFT.1250   *1251   * @param signer keyring of signer1252   * @param collectionId ID of collection1253   * @param tokenId ID of token1254   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1255   * @param amount amount of token to be approved. For NFT must be set to 1n1256   * @returns ```true``` if extrinsic success, otherwise ```false```1257   */1258  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1259    const approveResult = await this.helper.executeExtrinsic(1260      signer,1261      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1262      true, // `Unable to approve token for ${label}`,1263    );12641265    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1266  }12671268  /**1269   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1270   *1271   * @param signer keyring of signer1272   * @param collectionId ID of collection1273   * @param tokenId ID of token1274   * @param fromAddressObj Signer's Ethereum address containing her tokens1275   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1276   * @param amount amount of token to be approved. For NFT must be set to 1n1277   * @returns ```true``` if extrinsic success, otherwise ```false```1278   */1279  async approveTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1280    const approveResult = await this.helper.executeExtrinsic(1281      signer,1282      'api.tx.unique.approveFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1283      true, // `Unable to approve token for ${label}`,1284    );12851286    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1287  }12881289  /**1290   * Set, change, or remove approved address to transfer the ownership of the NFT from eth mirror.1291   *1292   * @param signer keyring of signer1293   * @param collectionId ID of collection1294   * @param tokenId ID of token1295   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1296   * @param amount amount of token to be approved. For NFT must be set to 1n1297   * @returns ```true``` if extrinsic success, otherwise ```false```1298   */1299  async approveTokenFromEth(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1300    const ethMirror = CrossAccountId.fromKeyring(signer).toEthereum();1301    return await this.approveTokenFrom(signer, collectionId, tokenId, ethMirror, toAddressObj, amount);1302  }13031304  /**1305   * Get the amount of token pieces approved to transfer or burn. Normally 0.1306   *1307   * @param collectionId ID of collection1308   * @param tokenId ID of token1309   * @param toAccountObj address which is approved to use token pieces1310   * @param fromAccountObj address which may have allowed the use of its owned tokens1311   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1312   * @returns number of approved to transfer pieces1313   */1314  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1315    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1316  }13171318  /**1319   * Get the last created token ID in a collection1320   *1321   * @param collectionId ID of collection1322   * @example getLastTokenId(10);1323   * @returns id of the last created token1324   */1325  async getLastTokenId(collectionId: number): Promise<number> {1326    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1327  }13281329  /**1330   * Check if token exists1331   *1332   * @param collectionId ID of collection1333   * @param tokenId ID of token1334   * @example doesTokenExist(10, 20);1335   * @returns true if the token exists, otherwise false1336   */1337  async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1338    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1339  }1340}13411342class NFTnRFT extends CollectionGroup {1343  /**1344   * Get tokens owned by account1345   *1346   * @param collectionId ID of collection1347   * @param addressObj tokens owner1348   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1349   * @returns array of token ids owned by account1350   */1351  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1352    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1353  }13541355  /**1356   * Get token data1357   *1358   * @param collectionId ID of collection1359   * @param tokenId ID of token1360   * @param propertyKeys optionally filter the token properties to only these keys1361   * @param blockHashAt optionally query the data at some block with this hash1362   * @example getToken(10, 5);1363   * @returns human readable token data1364   */1365  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1366    properties: IProperty[];1367    owner: CrossAccountId;1368    normalizedOwner: CrossAccountId;1369  }| null> {1370    let tokenData;1371    if(typeof blockHashAt === 'undefined') {1372      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1373    }1374    else {1375      if(propertyKeys.length == 0) {1376        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1377        if(!collection) return null;1378        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1379      }1380      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1381    }1382    tokenData = tokenData.toHuman();1383    if (tokenData === null || tokenData.owner === null) return null;1384    const owner = {} as any;1385    for (const key of Object.keys(tokenData.owner)) {1386      owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate'1387        ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key])1388        : tokenData.owner[key];1389    }1390    tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1391    return tokenData;1392  }13931394  /**1395   * Get token's owner1396   * @param collectionId ID of collection1397   * @param tokenId ID of token1398   * @param blockHashAt optionally query the data at the block with this hash1399   * @example getTokenOwner(10, 5);1400   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1401   */1402  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1403    let owner;1404    if (typeof blockHashAt === 'undefined') {1405      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1406    } else {1407      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1408    }1409    return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1410  }14111412  /**1413   * Recursively find the address that owns the token1414   * @param collectionId ID of collection1415   * @param tokenId ID of token1416   * @param blockHashAt1417   * @example getTokenTopmostOwner(10, 5);1418   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1419   */1420  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1421    let owner;1422    if (typeof blockHashAt === 'undefined') {1423      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1424    } else {1425      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1426    }14271428    if (owner === null) return null;14291430    return owner.toHuman();1431  }14321433  /**1434   * Nest one token into another1435   * @param signer keyring of signer1436   * @param tokenObj token to be nested1437   * @param rootTokenObj token to be parent1438   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1439   * @returns ```true``` if extrinsic success, otherwise ```false```1440   */1441  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1442    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1443    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1444    if(!result) {1445      throw Error('Unable to nest token!');1446    }1447    return result;1448  }14491450  /**1451     * Remove token from nested state1452     * @param signer keyring of signer1453     * @param tokenObj token to unnest1454     * @param rootTokenObj parent of a token1455     * @param toAddressObj address of a new token owner1456     * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1457     * @returns ```true``` if extrinsic success, otherwise ```false```1458     */1459  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1460    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1461    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1462    if(!result) {1463      throw Error('Unable to unnest token!');1464    }1465    return result;1466  }14671468  /**1469   * Set permissions to change token properties1470   *1471   * @param signer keyring of signer1472   * @param collectionId ID of collection1473   * @param permissions permissions to change a property by the collection admin or token owner1474   * @example setTokenPropertyPermissions(1475   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1476   * )1477   * @returns true if extrinsic success otherwise false1478   */1479  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1480    const result = await this.helper.executeExtrinsic(1481      signer,1482      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1483      true,1484    );14851486    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1487  }14881489  /**1490   * Get token property permissions.1491   *1492   * @param collectionId ID of collection1493   * @param propertyKeys optionally filter the returned property permissions to only these keys1494   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1495   * @returns array of key-permission pairs1496   */1497  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1498    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1499  }15001501  /**1502   * Set token properties1503   *1504   * @param signer keyring of signer1505   * @param collectionId ID of collection1506   * @param tokenId ID of token1507   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1508   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1509   * @returns ```true``` if extrinsic success, otherwise ```false```1510   */1511  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1512    const result = await this.helper.executeExtrinsic(1513      signer,1514      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1515      true,1516    );15171518    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1519  }15201521  /**1522   * Get properties, metadata assigned to a token.1523   *1524   * @param collectionId ID of collection1525   * @param tokenId ID of token1526   * @param propertyKeys optionally filter the returned properties to only these keys1527   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1528   * @returns array of key-value pairs1529   */1530  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1531    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1532  }15331534  /**1535   * Delete the provided properties of a token1536   * @param signer keyring of signer1537   * @param collectionId ID of collection1538   * @param tokenId ID of token1539   * @param propertyKeys property keys to be deleted1540   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1541   * @returns ```true``` if extrinsic success, otherwise ```false```1542   */1543  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1544    const result = await this.helper.executeExtrinsic(1545      signer,1546      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1547      true,1548    );15491550    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1551  }15521553  /**1554   * Mint new collection1555   *1556   * @param signer keyring of signer1557   * @param collectionOptions basic collection options and properties1558   * @param mode NFT or RFT type of a collection1559   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1560   * @returns object of the created collection1561   */1562  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1563    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1564    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1565    for (const key of ['name', 'description', 'tokenPrefix']) {1566      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1567    }1568    const creationResult = await this.helper.executeExtrinsic(1569      signer,1570      'api.tx.unique.createCollectionEx', [collectionOptions],1571      true, // errorLabel,1572    );1573    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1574  }15751576  getCollectionObject(_collectionId: number): any {1577    return null;1578  }15791580  getTokenObject(_collectionId: number, _tokenId: number): any {1581    return null;1582  }15831584  /**1585   * Tells whether the given `owner` approves the `operator`.1586   * @param collectionId ID of collection1587   * @param owner owner address1588   * @param operator operator addrees1589   * @returns true if operator is enabled1590   */1591  async allowanceForAll(collectionId: number, owner: ICrossAccountId, operator: ICrossAccountId): Promise<boolean> {1592    return (await this.helper.callRpc('api.rpc.unique.allowanceForAll', [collectionId, owner, operator])).toJSON();1593  }15941595  /** Sets or unsets the approval of a given operator.1596   *  The `operator` is allowed to transfer all tokens of the `caller` on their behalf.1597   *  @param operator Operator1598   *  @param approved Should operator status be granted or revoked?1599   *  @returns ```true``` if extrinsic success, otherwise ```false```1600   */1601  async setAllowanceForAll(signer: TSigner, collectionId: number, operator: ICrossAccountId, approved: boolean): Promise<boolean> {1602    const result = await this.helper.executeExtrinsic(1603      signer,1604      'api.tx.unique.setAllowanceForAll', [collectionId, operator, approved],1605      true,1606    );1607    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'ApprovedForAll');1608  }1609}161016111612class NFTGroup extends NFTnRFT {1613  /**1614   * Get collection object1615   * @param collectionId ID of collection1616   * @example getCollectionObject(2);1617   * @returns instance of UniqueNFTCollection1618   */1619  getCollectionObject(collectionId: number): UniqueNFTCollection {1620    return new UniqueNFTCollection(collectionId, this.helper);1621  }16221623  /**1624   * Get token object1625   * @param collectionId ID of collection1626   * @param tokenId ID of token1627   * @example getTokenObject(10, 5);1628   * @returns instance of UniqueNFTToken1629   */1630  getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1631    return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1632  }16331634  /**1635   * Is token approved to transfer1636   * @param collectionId ID of collection1637   * @param tokenId ID of token1638   * @param toAccountObj address to be approved1639   * @returns ```true``` if extrinsic success, otherwise ```false```1640   */1641  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1642    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1643  }16441645  /**1646   * Changes the owner of the token.1647   *1648   * @param signer keyring of signer1649   * @param collectionId ID of collection1650   * @param tokenId ID of token1651   * @param addressObj address of a new owner1652   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1653   * @returns ```true``` if extrinsic success, otherwise ```false```1654   */1655  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1656    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1657  }16581659  /**1660   *1661   * Change ownership of a NFT on behalf of the owner.1662   *1663   * @param signer keyring of signer1664   * @param collectionId ID of collection1665   * @param tokenId ID of token1666   * @param fromAddressObj address on behalf of which the token will be sent1667   * @param toAddressObj new token owner1668   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1669   * @returns ```true``` if extrinsic success, otherwise ```false```1670   */1671  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1672    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1673  }16741675  /**1676   * Get tokens nested in the provided token1677   * @param collectionId ID of collection1678   * @param tokenId ID of token1679   * @param blockHashAt optionally query the data at the block with this hash1680   * @example getTokenChildren(10, 5);1681   * @returns tokens whose depth of nesting is <= 51682   */1683  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1684    let children;1685    if(typeof blockHashAt === 'undefined') {1686      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1687    } else {1688      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1689    }16901691    return children.toJSON().map((x: any) => {1692      return {collectionId: x.collection, tokenId: x.token};1693    });1694  }16951696  /**1697   * Mint new collection1698   * @param signer keyring of signer1699   * @param collectionOptions Collection options1700   * @example1701   * mintCollection(aliceKeyring, {1702   *   name: 'New',1703   *   description: 'New collection',1704   *   tokenPrefix: 'NEW',1705   * })1706   * @returns object of the created collection1707   */1708  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1709    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1710  }17111712  /**1713   * Mint new token1714   * @param signer keyring of signer1715   * @param data token data1716   * @returns created token object1717   */1718  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1719    const creationResult = await this.helper.executeExtrinsic(1720      signer,1721      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1722        nft: {1723          properties: data.properties,1724        },1725      }],1726      true,1727    );1728    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1729    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1730    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1731    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1732  }17331734  /**1735   * Mint multiple NFT tokens1736   * @param signer keyring of signer1737   * @param collectionId ID of collection1738   * @param tokens array of tokens with owner and properties1739   * @example1740   * mintMultipleTokens(aliceKeyring, 10, [{1741   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1742   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1743   *   },{1744   *     owner: {Ethereum: "0x9F0583DbB855d..."},1745   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1746   * }]);1747   * @returns ```true``` if extrinsic success, otherwise ```false```1748   */1749  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1750    const creationResult = await this.helper.executeExtrinsic(1751      signer,1752      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1753      true,1754    );1755    const collection = this.getCollectionObject(collectionId);1756    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1757  }17581759  /**1760   * Mint multiple NFT tokens with one owner1761   * @param signer keyring of signer1762   * @param collectionId ID of collection1763   * @param owner tokens owner1764   * @param tokens array of tokens with owner and properties1765   * @example1766   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1767   *   properties: [{1768   *   key: "gender",1769   *   value: "female",1770   *  },{1771   *   key: "age",1772   *   value: "33",1773   *  }],1774   * }]);1775   * @returns array of newly created tokens1776   */1777  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1778    const rawTokens = [];1779    for (const token of tokens) {1780      const raw = {NFT: {properties: token.properties}};1781      rawTokens.push(raw);1782    }1783    const creationResult = await this.helper.executeExtrinsic(1784      signer,1785      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1786      true,1787    );1788    const collection = this.getCollectionObject(collectionId);1789    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1790  }17911792  /**1793   * Set, change, or remove approved address to transfer the ownership of the NFT.1794   *1795   * @param signer keyring of signer1796   * @param collectionId ID of collection1797   * @param tokenId ID of token1798   * @param toAddressObj address to approve1799   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1800   * @returns ```true``` if extrinsic success, otherwise ```false```1801   */1802  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1803    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1804  }1805}180618071808class RFTGroup extends NFTnRFT {1809  /**1810   * Get collection object1811   * @param collectionId ID of collection1812   * @example getCollectionObject(2);1813   * @returns instance of UniqueRFTCollection1814   */1815  getCollectionObject(collectionId: number): UniqueRFTCollection {1816    return new UniqueRFTCollection(collectionId, this.helper);1817  }18181819  /**1820   * Get token object1821   * @param collectionId ID of collection1822   * @param tokenId ID of token1823   * @example getTokenObject(10, 5);1824   * @returns instance of UniqueNFTToken1825   */1826  getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1827    return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1828  }18291830  /**1831   * Get top 10 token owners with the largest number of pieces1832   * @param collectionId ID of collection1833   * @param tokenId ID of token1834   * @example getTokenTop10Owners(10, 5);1835   * @returns array of top 10 owners1836   */1837  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1838    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1839  }18401841  /**1842   * Get number of pieces owned by address1843   * @param collectionId ID of collection1844   * @param tokenId ID of token1845   * @param addressObj address token owner1846   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1847   * @returns number of pieces ownerd by address1848   */1849  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1850    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1851  }18521853  /**1854   * Transfer pieces of token to another address1855   * @param signer keyring of signer1856   * @param collectionId ID of collection1857   * @param tokenId ID of token1858   * @param addressObj address of a new owner1859   * @param amount number of pieces to be transfered1860   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1861   * @returns ```true``` if extrinsic success, otherwise ```false```1862   */1863  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1864    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1865  }18661867  /**1868   * Change ownership of some pieces of RFT on behalf of the owner.1869   * @param signer keyring of signer1870   * @param collectionId ID of collection1871   * @param tokenId ID of token1872   * @param fromAddressObj address on behalf of which the token will be sent1873   * @param toAddressObj new token owner1874   * @param amount number of pieces to be transfered1875   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1876   * @returns ```true``` if extrinsic success, otherwise ```false```1877   */1878  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1879    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1880  }18811882  /**1883   * Mint new collection1884   * @param signer keyring of signer1885   * @param collectionOptions Collection options1886   * @example1887   * mintCollection(aliceKeyring, {1888   *   name: 'New',1889   *   description: 'New collection',1890   *   tokenPrefix: 'NEW',1891   * })1892   * @returns object of the created collection1893   */1894  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1895    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1896  }18971898  /**1899   * Mint new token1900   * @param signer keyring of signer1901   * @param data token data1902   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1903   * @returns created token object1904   */1905  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1906    const creationResult = await this.helper.executeExtrinsic(1907      signer,1908      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1909        refungible: {1910          pieces: data.pieces,1911          properties: data.properties,1912        },1913      }],1914      true,1915    );1916    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1917    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1918    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1919    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1920  }19211922  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1923    throw Error('Not implemented');1924    const creationResult = await this.helper.executeExtrinsic(1925      signer,1926      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1927      true, // `Unable to mint RFT tokens for ${label}`,1928    );1929    const collection = this.getCollectionObject(collectionId);1930    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1931  }19321933  /**1934   * Mint multiple RFT tokens with one owner1935   * @param signer keyring of signer1936   * @param collectionId ID of collection1937   * @param owner tokens owner1938   * @param tokens array of tokens with properties and pieces1939   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1940   * @returns array of newly created RFT tokens1941   */1942  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1943    const rawTokens = [];1944    for (const token of tokens) {1945      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1946      rawTokens.push(raw);1947    }1948    const creationResult = await this.helper.executeExtrinsic(1949      signer,1950      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1951      true,1952    );1953    const collection = this.getCollectionObject(collectionId);1954    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1955  }19561957  /**1958   * Destroys a concrete instance of RFT.1959   * @param signer keyring of signer1960   * @param collectionId ID of collection1961   * @param tokenId ID of token1962   * @param amount number of pieces to be burnt1963   * @example burnToken(aliceKeyring, 10, 5);1964   * @returns ```true``` if the extrinsic is successful, otherwise ```false```1965   */1966  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1967    return await super.burnToken(signer, collectionId, tokenId, amount);1968  }19691970  /**1971   * Destroys a concrete instance of RFT on behalf of the owner.1972   * @param signer keyring of signer1973   * @param collectionId ID of collection1974   * @param tokenId ID of token1975   * @param fromAddressObj address on behalf of which the token will be burnt1976   * @param amount number of pieces to be burnt1977   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1978   * @returns ```true``` if extrinsic success, otherwise ```false```1979   */1980  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1981    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1982  }19831984  /**1985   * Set, change, or remove approved address to transfer the ownership of the RFT.1986   *1987   * @param signer keyring of signer1988   * @param collectionId ID of collection1989   * @param tokenId ID of token1990   * @param toAddressObj address to approve1991   * @param amount number of pieces to be approved1992   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1993   * @returns true if the token success, otherwise false1994   */1995  approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1996    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1997  }19981999  /**2000   * Get total number of pieces2001   * @param collectionId ID of collection2002   * @param tokenId ID of token2003   * @example getTokenTotalPieces(10, 5);2004   * @returns number of pieces2005   */2006  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {2007    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();2008  }20092010  /**2011   * Change number of token pieces. Signer must be the owner of all token pieces.2012   * @param signer keyring of signer2013   * @param collectionId ID of collection2014   * @param tokenId ID of token2015   * @param amount new number of pieces2016   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);2017   * @returns true if the repartion was success, otherwise false2018   */2019  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {2020    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);2021    const repartitionResult = await this.helper.executeExtrinsic(2022      signer,2023      'api.tx.unique.repartition', [collectionId, tokenId, amount],2024      true,2025    );2026    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');2027    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');2028  }2029}203020312032class FTGroup extends CollectionGroup {2033  /**2034   * Get collection object2035   * @param collectionId ID of collection2036   * @example getCollectionObject(2);2037   * @returns instance of UniqueFTCollection2038   */2039  getCollectionObject(collectionId: number): UniqueFTCollection {2040    return new UniqueFTCollection(collectionId, this.helper);2041  }20422043  /**2044   * Mint new fungible collection2045   * @param signer keyring of signer2046   * @param collectionOptions Collection options2047   * @param decimalPoints number of token decimals2048   * @example2049   * mintCollection(aliceKeyring, {2050   *   name: 'New',2051   *   description: 'New collection',2052   *   tokenPrefix: 'NEW',2053   * }, 18)2054   * @returns newly created fungible collection2055   */2056  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {2057    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object2058    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');2059    collectionOptions.mode = {fungible: decimalPoints};2060    for (const key of ['name', 'description', 'tokenPrefix']) {2061      if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);2062    }2063    const creationResult = await this.helper.executeExtrinsic(2064      signer,2065      'api.tx.unique.createCollectionEx', [collectionOptions],2066      true,2067    );2068    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));2069  }20702071  /**2072   * Mint tokens2073   * @param signer keyring of signer2074   * @param collectionId ID of collection2075   * @param owner address owner of new tokens2076   * @param amount amount of tokens to be meanted2077   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);2078   * @returns ```true``` if extrinsic success, otherwise ```false```2079   */2080  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {2081    const creationResult = await this.helper.executeExtrinsic(2082      signer,2083      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {2084        fungible: {2085          value: amount,2086        },2087      }],2088      true, // `Unable to mint fungible tokens for ${label}`,2089    );2090    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2091  }20922093  /**2094   * Mint multiple Fungible tokens with one owner2095   * @param signer keyring of signer2096   * @param collectionId ID of collection2097   * @param owner tokens owner2098   * @param tokens array of tokens with properties and pieces2099   * @returns ```true``` if extrinsic success, otherwise ```false```2100   */2101  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {2102    const rawTokens = [];2103    for (const token of tokens) {2104      const raw = {Fungible: {Value: token.value}};2105      rawTokens.push(raw);2106    }2107    const creationResult = await this.helper.executeExtrinsic(2108      signer,2109      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],2110      true,2111    );2112    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');2113  }21142115  /**2116   * Get the top 10 owners with the largest balance for the Fungible collection2117   * @param collectionId ID of collection2118   * @example getTop10Owners(10);2119   * @returns array of ```ICrossAccountId```2120   */2121  async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {2122    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);2123  }21242125  /**2126   * Get account balance2127   * @param collectionId ID of collection2128   * @param addressObj address of owner2129   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})2130   * @returns amount of fungible tokens owned by address2131   */2132  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {2133    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();2134  }21352136  /**2137   * Transfer tokens to address2138   * @param signer keyring of signer2139   * @param collectionId ID of collection2140   * @param toAddressObj address recipient2141   * @param amount amount of tokens to be sent2142   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2143   * @returns ```true``` if extrinsic success, otherwise ```false```2144   */2145  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2146    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);2147  }21482149  /**2150   * Transfer some tokens on behalf of the owner.2151   * @param signer keyring of signer2152   * @param collectionId ID of collection2153   * @param fromAddressObj address on behalf of which tokens will be sent2154   * @param toAddressObj address where token to be sent2155   * @param amount number of tokens to be sent2156   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);2157   * @returns ```true``` if extrinsic success, otherwise ```false```2158   */2159  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2160    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);2161  }21622163  /**2164   * Destroy some amount of tokens2165   * @param signer keyring of signer2166   * @param collectionId ID of collection2167   * @param amount amount of tokens to be destroyed2168   * @example burnTokens(aliceKeyring, 10, 1000n);2169   * @returns ```true``` if extrinsic success, otherwise ```false```2170   */2171  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {2172    return await super.burnToken(signer, collectionId, 0, amount);2173  }21742175  /**2176   * Burn some tokens on behalf of the owner.2177   * @param signer keyring of signer2178   * @param collectionId ID of collection2179   * @param fromAddressObj address on behalf of which tokens will be burnt2180   * @param amount amount of tokens to be burnt2181   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);2182   * @returns ```true``` if extrinsic success, otherwise ```false```2183   */2184  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {2185    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);2186  }21872188  /**2189   * Get total collection supply2190   * @param collectionId2191   * @returns2192   */2193  async getTotalPieces(collectionId: number): Promise<bigint> {2194    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();2195  }21962197  /**2198   * Set, change, or remove approved address to transfer tokens.2199   *2200   * @param signer keyring of signer2201   * @param collectionId ID of collection2202   * @param toAddressObj address to be approved2203   * @param amount amount of tokens to be approved2204   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)2205   * @returns ```true``` if extrinsic success, otherwise ```false```2206   */2207  approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {2208    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);2209  }22102211  /**2212   * Get amount of fungible tokens approved to transfer2213   * @param collectionId ID of collection2214   * @param fromAddressObj owner of tokens2215   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner2216   * @returns number of tokens approved for the transfer2217   */2218  getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2219    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2220  }2221}222222232224class ChainGroup extends HelperGroup<ChainHelperBase> {2225  /**2226   * Get system properties of a chain2227   * @example getChainProperties();2228   * @returns ss58Format, token decimals, and token symbol2229   */2230  getChainProperties(): IChainProperties {2231    const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2232    return {2233      ss58Format: properties.ss58Format.toJSON(),2234      tokenDecimals: properties.tokenDecimals.toJSON(),2235      tokenSymbol: properties.tokenSymbol.toJSON(),2236    };2237  }22382239  /**2240   * Get chain header2241   * @example getLatestBlockNumber();2242   * @returns the number of the last block2243   */2244  async getLatestBlockNumber(): Promise<number> {2245    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2246  }22472248  /**2249   * Get block hash by block number2250   * @param blockNumber number of block2251   * @example getBlockHashByNumber(12345);2252   * @returns hash of a block2253   */2254  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2255    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2256    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2257    return blockHash;2258  }22592260  // TODO add docs2261  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2262    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2263    if (!blockHash) return null;2264    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2265  }22662267  /**2268   * Get latest relay block2269   * @returns {number} relay block2270   */2271  async getRelayBlockNumber(): Promise<bigint> {2272    const blockNumber = (await this.helper.callRpc('api.query.parachainSystem.validationData')).toJSON().relayParentNumber;2273    return BigInt(blockNumber);2274  }22752276  /**2277   * Get account nonce2278   * @param address substrate address2279   * @example getNonce("5GrwvaEF5zXb26Fz...");2280   * @returns number, account's nonce2281   */2282  async getNonce(address: TSubstrateAccount): Promise<number> {2283    return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2284  }2285}22862287class SubstrateBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2288  /**2289 * Get substrate address balance2290 * @param address substrate address2291 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2292 * @returns amount of tokens on address2293 */2294  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2295    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2296  }22972298  /**2299   * Transfer tokens to substrate address2300   * @param signer keyring of signer2301   * @param address substrate address of a recipient2302   * @param amount amount of tokens to be transfered2303   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2304   * @returns ```true``` if extrinsic success, otherwise ```false```2305   */2306  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2307    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true/*, `Unable to transfer balance from ${this.helper.getSignerAddress(signer)} to ${address}`*/);23082309    let transfer = {from: null, to: null, amount: 0n} as any;2310    result.result.events.forEach(({event: {data, method, section}}) => {2311      if ((section === 'balances') && (method === 'Transfer')) {2312        transfer = {2313          from: this.helper.address.normalizeSubstrate(data[0]),2314          to: this.helper.address.normalizeSubstrate(data[1]),2315          amount: BigInt(data[2]),2316        };2317      }2318    });2319    const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from2320      && this.helper.address.normalizeSubstrate(address) === transfer.to2321      && BigInt(amount) === transfer.amount;2322    return isSuccess;2323  }23242325  /**2326   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2327   * @param address substrate address2328   * @returns2329   */2330  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2331    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2332    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2333  }23342335  async getLocked(address: TSubstrateAccount): Promise<[{id: string, amount: bigint, reason: string}]> {2336    const locks = (await this.helper.callRpc('api.query.balances.locks', [address])).toHuman();2337    return locks.map((lock: any) => {return {id: lock.id, amount: BigInt(lock.amount.replace(/,/g, '')), reasons: lock.reasons};});2338  }2339}23402341class EthereumBalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2342  /**2343   * Get ethereum address balance2344   * @param address ethereum address2345   * @example getEthereum("0x9F0583DbB855d...")2346   * @returns amount of tokens on address2347   */2348  async getEthereum(address: TEthereumAccount): Promise<bigint> {2349    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2350  }23512352  /**2353   * Transfer tokens to address2354   * @param signer keyring of signer2355   * @param address Ethereum address of a recipient2356   * @param amount amount of tokens to be transfered2357   * @example transferToEthereum(alithKeyring, "0x9F0583DbB855d...", 100_000_000_000n);2358   * @returns ```true``` if extrinsic success, otherwise ```false```2359   */2360  async transferToEthereum(signer: TSigner, address: TEthereumAccount, amount: bigint | string): Promise<boolean> {2361    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);23622363    let transfer = {from: null, to: null, amount: 0n} as any;2364    result.result.events.forEach(({event: {data, method, section}}) => {2365      if ((section === 'balances') && (method === 'Transfer')) {2366        transfer = {2367          from: data[0].toString(),2368          to: data[1].toString(),2369          amount: BigInt(data[2]),2370        };2371      }2372    });2373    const isSuccess = (typeof signer === 'string' ? signer : signer.address) === transfer.from2374      && address === transfer.to2375      && BigInt(amount) === transfer.amount;2376    return isSuccess;2377  }2378}23792380class BalanceGroup<T extends ChainHelperBase> extends HelperGroup<T> {2381  subBalanceGroup: SubstrateBalanceGroup<T>;2382  ethBalanceGroup: EthereumBalanceGroup<T>;23832384  constructor(helper: T) {2385    super(helper);2386    this.subBalanceGroup = new SubstrateBalanceGroup(helper);2387    this.ethBalanceGroup = new EthereumBalanceGroup(helper);2388  }23892390  getCollectionCreationPrice(): bigint {2391    return 2n * this.getOneTokenNominal();2392  }2393  /**2394   * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2395   * @example getOneTokenNominal()2396   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2397   */2398  getOneTokenNominal(): bigint {2399    const chainProperties = this.helper.chain.getChainProperties();2400    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2401  }24022403  /**2404   * Get substrate address balance2405   * @param address substrate address2406   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2407   * @returns amount of tokens on address2408   */2409  getSubstrate(address: TSubstrateAccount): Promise<bigint> {2410    return this.subBalanceGroup.getSubstrate(address);2411  }24122413  /**2414   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2415   * @param address substrate address2416   * @returns2417   */2418  getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2419    return this.subBalanceGroup.getSubstrateFull(address);2420  }24212422  /**2423   * Get locked balances2424   * @param address substrate address2425   * @returns locked balances with reason via api.query.balances.locks2426   */2427  getLocked(address: TSubstrateAccount) {2428    return this.subBalanceGroup.getLocked(address);2429  }24302431  /**2432   * Get ethereum address balance2433   * @param address ethereum address2434   * @example getEthereum("0x9F0583DbB855d...")2435   * @returns amount of tokens on address2436   */2437  getEthereum(address: TEthereumAccount): Promise<bigint> {2438    return this.ethBalanceGroup.getEthereum(address);2439  }24402441  /**2442   * Transfer tokens to substrate address2443   * @param signer keyring of signer2444   * @param address substrate address of a recipient2445   * @param amount amount of tokens to be transfered2446   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2447   * @returns ```true``` if extrinsic success, otherwise ```false```2448   */2449  transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2450    return this.subBalanceGroup.transferToSubstrate(signer, address, amount);2451  }24522453  async forceTransferToSubstrate(signer: TSigner, from: TSubstrateAccount, to: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2454    const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.forceTransfer', [from, to, amount], true);24552456    let transfer = {from: null, to: null, amount: 0n} as any;2457    result.result.events.forEach(({event: {data, method, section}}) => {2458      if ((section === 'balances') && (method === 'Transfer')) {2459        transfer = {2460          from: this.helper.address.normalizeSubstrate(data[0]),2461          to: this.helper.address.normalizeSubstrate(data[1]),2462          amount: BigInt(data[2]),2463        };2464      }2465    });2466    let isSuccess = this.helper.address.normalizeSubstrate(from) === transfer.from;2467    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(to) === transfer.to;2468    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2469    return isSuccess;2470  }24712472  /**2473   * Transfer tokens with the unlock period2474   * @param signer signers Keyring2475   * @param address Substrate address of recipient2476   * @param schedule Schedule params2477   * @example vestedTransfer(signer, recepient.address, 20000, 100, 10, 50 * nominal); // total amount of vested tokens will be 100 * 50 = 50002478   */2479  async vestedTransfer(signer: TSigner, address: TSubstrateAccount, schedule: {start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}): Promise<void> {2480    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.vestedTransfer', [address, schedule]);2481    const event = result.result.events2482      .find(e => e.event.section === 'vesting' &&2483            e.event.method === 'VestingScheduleAdded' &&2484            e.event.data[0].toHuman() === signer.address);2485    if (!event) throw Error('Cannot find transfer in events');2486  }24872488  /**2489   * Get schedule for recepient of vested transfer2490   * @param address Substrate address of recipient2491   * @returns2492   */2493  async getVestingSchedules(address: TSubstrateAccount): Promise<{start: bigint, period: bigint, periodCount: bigint, perPeriod: bigint}[]> {2494    const schedule = (await this.helper.callRpc('api.query.vesting.vestingSchedules', [address])).toJSON();2495    return schedule.map((schedule: any) => {2496      return {2497        start: BigInt(schedule.start),2498        period: BigInt(schedule.period),2499        periodCount: BigInt(schedule.periodCount),2500        perPeriod: BigInt(schedule.perPeriod),2501      };2502    });2503  }25042505  /**2506   * Claim vested tokens2507   * @param signer signers Keyring2508   */2509  async claim(signer: TSigner) {2510    const result = await this.helper.executeExtrinsic(signer, 'api.tx.vesting.claim', []);2511    const event = result.result.events2512      .find(e => e.event.section === 'vesting' &&2513            e.event.method === 'Claimed' &&2514            e.event.data[0].toHuman() === signer.address);2515    if (!event) throw Error('Cannot find claim in events');2516  }2517}25182519class AddressGroup extends HelperGroup<ChainHelperBase> {2520  /**2521   * Normalizes the address to the specified ss58 format, by default ```42```.2522   * @param address substrate address2523   * @param ss58Format format for address conversion, by default ```42```2524   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2525   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2526   */2527  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2528    return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2529  }25302531  /**2532   * Get address in the connected chain format2533   * @param address substrate address2534   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2535   * @returns address in chain format2536   */2537  normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2538    return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2539  }25402541  /**2542   * Get substrate mirror of an ethereum address2543   * @param ethAddress ethereum address2544   * @param toChainFormat false for normalized account2545   * @example ethToSubstrate('0x9F0583DbB855d...')2546   * @returns substrate mirror of a provided ethereum address2547   */2548  ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2549    return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2550  }25512552  /**2553   * Get ethereum mirror of a substrate address2554   * @param subAddress substrate account2555   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2556   * @returns ethereum mirror of a provided substrate address2557   */2558  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2559    return CrossAccountId.translateSubToEth(subAddress);2560  }25612562  /**2563   * Encode key to substrate address2564   * @param key key for encoding address2565   * @param ss58Format prefix for encoding to the address of the corresponding network2566   * @returns encoded substrate address2567   */2568  encodeSubstrateAddress (key: Uint8Array | string | bigint, ss58Format = 42): string {2569    const u8a :Uint8Array = typeof key === 'string'2570      ? hexToU8a(key)2571      : typeof key === 'bigint'2572        ? hexToU8a(key.toString(16))2573        : key;25742575    if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {2576      throw new Error(`ss58Format is not valid, received ${typeof ss58Format} "${ss58Format}"`);2577    }25782579    const allowedDecodedLengths = [1, 2, 4, 8, 32, 33];2580    if (!allowedDecodedLengths.includes(u8a.length)) {2581      throw new Error(`key length is not valid, received ${u8a.length}, valid values are ${allowedDecodedLengths.join(', ')}`);2582    }25832584    const u8aPrefix = ss58Format < 642585      ? new Uint8Array([ss58Format])2586      : new Uint8Array([2587        ((ss58Format & 0xfc) >> 2) | 0x40,2588        (ss58Format >> 8) | ((ss58Format & 0x03) << 6),2589      ]);25902591    const input = u8aConcat(u8aPrefix, u8a);25922593    return base58Encode(u8aConcat(2594      input,2595      blake2AsU8a(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1),2596    ));2597  }25982599  /**2600   * Restore substrate address from bigint representation2601   * @param number decimal representation of substrate address2602   * @returns substrate address2603   */2604  restoreCrossAccountFromBigInt(number: bigint): TSubstrateAccount {2605    if (this.helper.api === null) {2606      throw 'Not connected';2607    }2608    const res = this.helper.api.registry.createType('AccountId', '0x' + number.toString(16).padStart(64, '0')).toJSON();2609    if (res === undefined || res === null) {2610      throw 'Restore address error';2611    }2612    return res.toString();2613  }26142615  /**2616   * Convert etherium cross account id to substrate cross account id2617   * @param ethCrossAccount etherium cross account2618   * @returns substrate cross account id2619   */2620  convertCrossAccountFromEthCrossAccount(ethCrossAccount: IEthCrossAccountId): ICrossAccountId {2621    if (ethCrossAccount.sub === '0') {2622      return {Ethereum: ethCrossAccount.eth.toLocaleLowerCase()};2623    }26242625    const ss58 = this.restoreCrossAccountFromBigInt(BigInt(ethCrossAccount.sub));2626    return {Substrate: ss58};2627  }26282629  paraSiblingSovereignAccount(paraid: number) {2630    // We are getting a *sibling* parachain sovereign account,2631    // so we need a sibling prefix: encoded(b"sibl") == 0x7369626c2632    const siblingPrefix = '0x7369626c';26332634    const encodedParaId = this.helper.getApi().createType('u32', paraid).toHex(true).substring(2);2635    const suffix = '000000000000000000000000000000000000000000000000';26362637    return siblingPrefix + encodedParaId + suffix;2638  }2639}26402641class StakingGroup extends HelperGroup<UniqueHelper> {2642  /**2643   * Stake tokens for App Promotion2644   * @param signer keyring of signer2645   * @param amountToStake amount of tokens to stake2646   * @param label extra label for log2647   * @returns2648   */2649  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2650    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2651    const _stakeResult = await this.helper.executeExtrinsic(2652      signer, 'api.tx.appPromotion.stake',2653      [amountToStake], true,2654    );2655    // TODO extract info from stakeResult2656    return true;2657  }26582659  /**2660   * Unstake all staked tokens2661   * @param signer keyring of signer2662   * @param amountToUnstake amount of tokens to unstake2663   * @param label extra label for log2664   * @returns block hash where unstake happened2665   */2666  async unstakeAll(signer: TSigner, label?: string): Promise<string> {2667    if(typeof label === 'undefined') label = `${signer.address}`;2668    const unstakeResult = await this.helper.executeExtrinsic(2669      signer, 'api.tx.appPromotion.unstakeAll',2670      [], true,2671    );2672    return unstakeResult.blockHash;2673  }26742675  /**2676   * Unstake the part of a staked tokens2677   * @param signer keyring of signer2678   * @param amount amount of tokens to unstake2679   * @param label extra label for log2680   * @returns block hash where unstake happened2681   */2682  async unstakePartial(signer: TSigner, amount: bigint, label?: string): Promise<string> {2683    if(typeof label === 'undefined') label = `${signer.address}`;2684    const unstakeResult = await this.helper.executeExtrinsic(2685      signer, 'api.tx.appPromotion.unstakePartial',2686      [amount], true,2687    );2688    return unstakeResult.blockHash;2689  }26902691  /**2692   * Get total number of active stakes2693   * @param address substrate address2694   * @returns {number}2695   */2696  async getStakesNumber(address: ICrossAccountId): Promise<number> {2697    if (address.Ethereum) throw Error('only substrate address');2698    return (await this.helper.callRpc('api.query.appPromotion.stakesPerAccount', [address.Substrate])).toNumber();2699  }27002701  /**2702   * Get total staked amount for address2703   * @param address substrate or ethereum address2704   * @returns total staked amount2705   */2706  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2707    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2708    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2709  }27102711  /**2712   * Get total staked per block2713   * @param address substrate or ethereum address2714   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2715   */2716  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2717    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2718    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2719      return {2720        block: block.toBigInt(),2721        amount: amount.toBigInt(),2722      };2723    });2724  }27252726  /**2727   * Get total pending unstake amount for address2728   * @param address substrate or ethereum address2729   * @returns total pending unstake amount2730   */2731  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2732    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2733  }27342735  /**2736   * Get pending unstake amount per block for address2737   * @param address substrate or ethereum address2738   * @returns array of pending stakes. `block` – the number of the block in which the unstake was made. `amount` - the number of tokens unstaked in the block2739   */2740  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2741    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2742    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2743      return {2744        block: block.toBigInt(),2745        amount: amount.toBigInt(),2746      };2747    });2748    return result;2749  }2750}27512752class SchedulerGroup extends HelperGroup<UniqueHelper> {2753  constructor(helper: UniqueHelper) {2754    super(helper);2755  }27562757  cancelScheduled(signer: TSigner, scheduledId: string) {2758    return this.helper.executeExtrinsic(2759      signer,2760      'api.tx.scheduler.cancelNamed',2761      [scheduledId],2762      true,2763    );2764  }27652766  changePriority(signer: TSigner, scheduledId: string, priority: number) {2767    return this.helper.executeExtrinsic(2768      signer,2769      'api.tx.scheduler.changeNamedPriority',2770      [scheduledId, priority],2771      true,2772    );2773  }27742775  scheduleAt<T extends UniqueHelper>(2776    executionBlockNumber: number,2777    options: ISchedulerOptions = {},2778  ) {2779    return this.schedule<T>('schedule', executionBlockNumber, options);2780  }27812782  scheduleAfter<T extends UniqueHelper>(2783    blocksBeforeExecution: number,2784    options: ISchedulerOptions = {},2785  ) {2786    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);2787  }27882789  schedule<T extends UniqueHelper>(2790    scheduleFn: 'schedule' | 'scheduleAfter',2791    blocksNum: number,2792    options: ISchedulerOptions = {},2793  ) {2794    // eslint-disable-next-line @typescript-eslint/naming-convention2795    const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2796    return this.helper.clone(ScheduledHelperType, {2797      scheduleFn,2798      blocksNum,2799      options,2800    }) as T;2801  }2802}28032804class CollatorSelectionGroup extends HelperGroup<UniqueHelper> {2805  //todo:collator documentation2806  addInvulnerable(signer: TSigner, address: string) {2807    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.addInvulnerable', [address]);2808  }28092810  removeInvulnerable(signer: TSigner, address: string) {2811    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.removeInvulnerable', [address]);2812  }28132814  async getInvulnerables(): Promise<string[]> {2815    return (await this.helper.callRpc('api.query.collatorSelection.invulnerables')).map((x: any) => x.toHuman());2816  }28172818  /** and also total max invulnerables */2819  maxCollators(): number {2820    return (this.helper.getApi().consts.configuration.defaultCollatorSelectionMaxCollators.toJSON() as number);2821  }28222823  async getDesiredCollators(): Promise<number> {2824    return (await this.helper.callRpc('api.query.configuration.collatorSelectionDesiredCollatorsOverride')).toNumber();2825  }28262827  setLicenseBond(signer: TSigner, amount: bigint) {2828    return this.helper.executeExtrinsic(signer, 'api.tx.configuration.setCollatorSelectionLicenseBond', [amount]);2829  }28302831  async getLicenseBond(): Promise<bigint> {2832    return (await this.helper.callRpc('api.query.configuration.collatorSelectionLicenseBondOverride')).toBigInt();2833  }28342835  obtainLicense(signer: TSigner) {2836    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.getLicense', []);2837  }28382839  releaseLicense(signer: TSigner) {2840    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.releaseLicense', []);2841  }28422843  forceReleaseLicense(signer: TSigner, released: string) {2844    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.forceReleaseLicense', [released]);2845  }28462847  async hasLicense(address: string): Promise<bigint> {2848    return (await this.helper.callRpc('api.query.collatorSelection.licenseDepositOf', [address])).toBigInt();2849  }28502851  onboard(signer: TSigner) {2852    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.onboard', []);2853  }28542855  offboard(signer: TSigner) {2856    return this.helper.executeExtrinsic(signer, 'api.tx.collatorSelection.offboard', []);2857  }28582859  async getCandidates(): Promise<string[]> {2860    return (await this.helper.callRpc('api.query.collatorSelection.candidates')).map((x: any) => x.toHuman());2861  }2862}28632864class ForeignAssetsGroup extends HelperGroup<UniqueHelper> {2865  async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2866    await this.helper.executeExtrinsic(2867      signer,2868      'api.tx.foreignAssets.registerForeignAsset',2869      [ownerAddress, location, metadata],2870      true,2871    );2872  }28732874  async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2875    await this.helper.executeExtrinsic(2876      signer,2877      'api.tx.foreignAssets.updateForeignAsset',2878      [foreignAssetId, location, metadata],2879      true,2880    );2881  }2882}28832884class XcmGroup<T extends ChainHelperBase> extends HelperGroup<T> {2885  palletName: string;28862887  constructor(helper: T, palletName: string) {2888    super(helper);28892890    this.palletName = palletName;2891  }28922893  async limitedReserveTransferAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number, weightLimit: any) {2894    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.limitedReserveTransferAssets`, [destination, beneficiary, assets, feeAssetItem, weightLimit], true);2895  }28962897  async teleportAssets(signer: TSigner, destination: any, beneficiary: any, assets: any, feeAssetItem: number) {2898    await this.helper.executeExtrinsic(signer, `api.tx.${this.palletName}.teleportAssets`, [destination, beneficiary, assets, feeAssetItem], true);2899  }29002901  async teleportNativeAsset(signer: TSigner, destinationParaId: number, targetAccount: Uint8Array, amount: bigint) {2902    const destination = {2903      V1: {2904        parents: 0,2905        interior: {2906          X1: {2907            Parachain: destinationParaId,2908          },2909        },2910      },2911    };29122913    const beneficiary = {2914      V1: {2915        parents: 0,2916        interior: {2917          X1: {2918            AccountId32: {2919              network: 'Any',2920              id: targetAccount,2921            },2922          },2923        },2924      },2925    };29262927    const assets = {2928      V1: [2929        {2930          id: {2931            Concrete: {2932              parents: 0,2933              interior: 'Here',2934            },2935          },2936          fun: {2937            Fungible: amount,2938          },2939        },2940      ],2941    };29422943    const feeAssetItem = 0;29442945    await this.teleportAssets(signer, destination, beneficiary, assets, feeAssetItem);2946  }2947}29482949class XTokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2950  async transfer(signer: TSigner, currencyId: any, amount: bigint, destination: any, destWeight: any) {2951    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transfer', [currencyId, amount, destination, destWeight], true);2952  }29532954  async transferMultiasset(signer: TSigner, asset: any, destination: any, destWeight: any) {2955    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMultiasset', [asset, destination, destWeight], true);2956  }29572958  async transferMulticurrencies(signer: TSigner, currencies: any[], feeItem: number, destLocation: any, destWeight: any) {2959    await this.helper.executeExtrinsic(signer, 'api.tx.xTokens.transferMulticurrencies', [currencies, feeItem, destLocation, destWeight], true);2960  }2961}29622963class TokensGroup<T extends ChainHelperBase> extends HelperGroup<T> {2964  async accounts(address: string, currencyId: any) {2965    const {free} = (await this.helper.callRpc('api.query.tokens.accounts', [address, currencyId])).toJSON() as any;2966    return BigInt(free);2967  }2968}29692970class AssetsGroup<T extends ChainHelperBase> extends HelperGroup<T> {2971  async create(signer: TSigner, assetId: number, admin: string, minimalBalance: bigint) {2972    await this.helper.executeExtrinsic(signer, 'api.tx.assets.create', [assetId, admin, minimalBalance], true);2973  }29742975  async setMetadata(signer: TSigner, assetId: number, name: string, symbol: string, decimals: number) {2976    await this.helper.executeExtrinsic(signer, 'api.tx.assets.setMetadata', [assetId, name, symbol, decimals], true);2977  }29782979  async mint(signer: TSigner, assetId: number, beneficiary: string, amount: bigint) {2980    await this.helper.executeExtrinsic(signer, 'api.tx.assets.mint', [assetId, beneficiary, amount], true);2981  }29822983  async account(assetId: string | number, address: string) {2984    const accountAsset = (2985      await this.helper.callRpc('api.query.assets.account', [assetId, address])2986    ).toJSON()! as any;29872988    if (accountAsset !== null) {2989      return BigInt(accountAsset['balance']);2990    } else {2991      return null;2992    }2993  }2994}29952996class AcalaAssetRegistryGroup extends HelperGroup<AcalaHelper> {2997  async registerForeignAsset(signer: TSigner, destination: any, metadata: AcalaAssetMetadata) {2998    await this.helper.executeExtrinsic(signer, 'api.tx.assetRegistry.registerForeignAsset', [destination, metadata], true);2999  }3000}30013002class MoonbeamAssetManagerGroup extends HelperGroup<MoonbeamHelper> {3003  makeRegisterForeignAssetProposal(assetInfo: MoonbeamAssetInfo) {3004    const apiPrefix = 'api.tx.assetManager.';30053006    const registerTx = this.helper.constructApiCall(3007      apiPrefix + 'registerForeignAsset',3008      [assetInfo.location, assetInfo.metadata, assetInfo.existentialDeposit, assetInfo.isSufficient],3009    );30103011    const setUnitsTx = this.helper.constructApiCall(3012      apiPrefix + 'setAssetUnitsPerSecond',3013      [assetInfo.location, assetInfo.unitsPerSecond, assetInfo.numAssetsWeightHint],3014    );30153016    const batchCall = this.helper.getApi().tx.utility.batchAll([registerTx, setUnitsTx]);3017    const encodedProposal = batchCall?.method.toHex() || '';3018    return encodedProposal;3019  }30203021  async assetTypeId(location: any) {3022    return await this.helper.callRpc('api.query.assetManager.assetTypeId', [location]);3023  }3024}30253026class MoonbeamDemocracyGroup extends HelperGroup<MoonbeamHelper> {3027  notePreimagePallet: string;30283029  constructor(helper: MoonbeamHelper, options: {[key: string]: any} = {}) {3030    super(helper);3031    this.notePreimagePallet = options.notePreimagePallet;3032  }30333034  async notePreimage(signer: TSigner, encodedProposal: string) {3035    await this.helper.executeExtrinsic(signer, `api.tx.${this.notePreimagePallet}.notePreimage`, [encodedProposal], true);3036  }30373038  externalProposeMajority(proposal: any) {3039    return this.helper.constructApiCall('api.tx.democracy.externalProposeMajority', [proposal]);3040  }30413042  fastTrack(proposalHash: string, votingPeriod: number, delayPeriod: number) {3043    return this.helper.constructApiCall('api.tx.democracy.fastTrack', [proposalHash, votingPeriod, delayPeriod]);3044  }30453046  async referendumVote(signer: TSigner, referendumIndex: number, accountVote: DemocracyStandardAccountVote) {3047    await this.helper.executeExtrinsic(signer, 'api.tx.democracy.vote', [referendumIndex, {Standard: accountVote}], true);3048  }3049}30503051class MoonbeamCollectiveGroup extends HelperGroup<MoonbeamHelper> {3052  collective: string;30533054  constructor(helper: MoonbeamHelper, collective: string) {3055    super(helper);30563057    this.collective = collective;3058  }30593060  async propose(signer: TSigner, threshold: number, proposalHash: string, lengthBound: number) {3061    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.propose`, [threshold, proposalHash, lengthBound], true);3062  }30633064  async vote(signer: TSigner, proposalHash: string, proposalIndex: number, approve: boolean) {3065    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.vote`, [proposalHash, proposalIndex, approve], true);3066  }30673068  async close(signer: TSigner, proposalHash: string, proposalIndex: number, weightBound: any, lengthBound: number) {3069    await this.helper.executeExtrinsic(signer, `api.tx.${this.collective}.close`, [proposalHash, proposalIndex, weightBound, lengthBound], true);3070  }30713072  async proposalCount() {3073    return Number(await this.helper.callRpc(`api.query.${this.collective}.proposalCount`, []));3074  }3075}30763077export type ChainHelperBaseConstructor = new(...args: any[]) => ChainHelperBase;3078export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;30793080export class UniqueHelper extends ChainHelperBase {3081  balance: BalanceGroup<UniqueHelper>;3082  collection: CollectionGroup;3083  nft: NFTGroup;3084  rft: RFTGroup;3085  ft: FTGroup;3086  staking: StakingGroup;3087  scheduler: SchedulerGroup;3088  collatorSelection: CollatorSelectionGroup;3089  foreignAssets: ForeignAssetsGroup;3090  xcm: XcmGroup<UniqueHelper>;3091  xTokens: XTokensGroup<UniqueHelper>;3092  tokens: TokensGroup<UniqueHelper>;30933094  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3095    super(logger, options.helperBase ?? UniqueHelper);30963097    this.balance = new BalanceGroup(this);3098    this.collection = new CollectionGroup(this);3099    this.nft = new NFTGroup(this);3100    this.rft = new RFTGroup(this);3101    this.ft = new FTGroup(this);3102    this.staking = new StakingGroup(this);3103    this.scheduler = new SchedulerGroup(this);3104    this.collatorSelection = new CollatorSelectionGroup(this);3105    this.foreignAssets = new ForeignAssetsGroup(this);3106    this.xcm = new XcmGroup(this, 'polkadotXcm');3107    this.xTokens = new XTokensGroup(this);3108    this.tokens = new TokensGroup(this);3109  }31103111  getSudo<T extends UniqueHelper>() {3112    // eslint-disable-next-line @typescript-eslint/naming-convention3113    const SudoHelperType = SudoHelper(this.helperBase);3114    return this.clone(SudoHelperType) as T;3115  }3116}31173118export class XcmChainHelper extends ChainHelperBase {3119  async connect(wsEndpoint: string, _listeners?: any): Promise<void> {3120    const wsProvider = new WsProvider(wsEndpoint);3121    this.api = new ApiPromise({3122      provider: wsProvider,3123    });3124    await this.api.isReadyOrError;3125    this.network = await UniqueHelper.detectNetwork(this.api);3126  }3127}31283129export class RelayHelper extends XcmChainHelper {3130  balance: SubstrateBalanceGroup<RelayHelper>;3131  xcm: XcmGroup<RelayHelper>;31323133  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3134    super(logger, options.helperBase ?? RelayHelper);31353136    this.balance = new SubstrateBalanceGroup(this);3137    this.xcm = new XcmGroup(this, 'xcmPallet');3138  }3139}31403141export class WestmintHelper extends XcmChainHelper {3142  balance: SubstrateBalanceGroup<WestmintHelper>;3143  xcm: XcmGroup<WestmintHelper>;3144  assets: AssetsGroup<WestmintHelper>;3145  xTokens: XTokensGroup<WestmintHelper>;31463147  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3148    super(logger, options.helperBase ?? WestmintHelper);31493150    this.balance = new SubstrateBalanceGroup(this);3151    this.xcm = new XcmGroup(this, 'polkadotXcm');3152    this.assets = new AssetsGroup(this);3153    this.xTokens = new XTokensGroup(this);3154  }3155}31563157export class MoonbeamHelper extends XcmChainHelper {3158  balance: EthereumBalanceGroup<MoonbeamHelper>;3159  assetManager: MoonbeamAssetManagerGroup;3160  assets: AssetsGroup<MoonbeamHelper>;3161  xTokens: XTokensGroup<MoonbeamHelper>;3162  democracy: MoonbeamDemocracyGroup;3163  collective: {3164    council: MoonbeamCollectiveGroup,3165    techCommittee: MoonbeamCollectiveGroup,3166  };31673168  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3169    super(logger, options.helperBase ?? MoonbeamHelper);31703171    this.balance = new EthereumBalanceGroup(this);3172    this.assetManager = new MoonbeamAssetManagerGroup(this);3173    this.assets = new AssetsGroup(this);3174    this.xTokens = new XTokensGroup(this);3175    this.democracy = new MoonbeamDemocracyGroup(this, options);3176    this.collective = {3177      council: new MoonbeamCollectiveGroup(this, 'councilCollective'),3178      techCommittee: new MoonbeamCollectiveGroup(this, 'techCommitteeCollective'),3179    };3180  }3181}31823183export class AcalaHelper extends XcmChainHelper {3184  balance: SubstrateBalanceGroup<AcalaHelper>;3185  assetRegistry: AcalaAssetRegistryGroup;3186  xTokens: XTokensGroup<AcalaHelper>;3187  tokens: TokensGroup<AcalaHelper>;31883189  constructor(logger?: ILogger, options: {[key: string]: any} = {}) {3190    super(logger, options.helperBase ?? AcalaHelper);31913192    this.balance = new SubstrateBalanceGroup(this);3193    this.assetRegistry = new AcalaAssetRegistryGroup(this);3194    this.xTokens = new XTokensGroup(this);3195    this.tokens = new TokensGroup(this);3196  }31973198  getSudo<T extends AcalaHelper>() {3199    // eslint-disable-next-line @typescript-eslint/naming-convention3200    const SudoHelperType = SudoHelper(this.helperBase);3201    return this.clone(SudoHelperType) as T;3202  }3203}32043205// eslint-disable-next-line @typescript-eslint/naming-convention3206function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {3207  return class extends Base {3208    scheduleFn: 'schedule' | 'scheduleAfter';3209    blocksNum: number;3210    options: ISchedulerOptions;32113212    constructor(...args: any[]) {3213      const logger = args[0] as ILogger;3214      const options = args[1] as {3215        scheduleFn: 'schedule' | 'scheduleAfter',3216        blocksNum: number,3217        options: ISchedulerOptions3218      };32193220      super(logger);32213222      this.scheduleFn = options.scheduleFn;3223      this.blocksNum = options.blocksNum;3224      this.options = options.options;3225    }32263227    executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {3228      const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);32293230      const mandatorySchedArgs = [3231        this.blocksNum,3232        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,3233        this.options.priority ?? null,3234        scheduledTx,3235      ];32363237      let schedArgs;3238      let scheduleFn;32393240      if (this.options.scheduledId) {3241        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];32423243        if (this.scheduleFn == 'schedule') {3244          scheduleFn = 'scheduleNamed';3245        } else if (this.scheduleFn == 'scheduleAfter') {3246          scheduleFn = 'scheduleNamedAfter';3247        }3248      } else {3249        schedArgs = mandatorySchedArgs;3250        scheduleFn = this.scheduleFn;3251      }32523253      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;32543255      return super.executeExtrinsic(3256        sender,3257        extrinsic,3258        schedArgs,3259        expectSuccess,3260      );3261    }3262  };3263}32643265// eslint-disable-next-line @typescript-eslint/naming-convention3266function SudoHelper<T extends ChainHelperBaseConstructor>(Base: T) {3267  return class extends Base {3268    constructor(...args: any[]) {3269      super(...args);3270    }32713272    async executeExtrinsic(3273      sender: IKeyringPair,3274      extrinsic: string,3275      params: any[],3276      expectSuccess?: boolean,3277      options: Partial<SignerOptions>|null = null,3278    ): Promise<ITransactionResult> {3279      const call = this.constructApiCall(extrinsic, params);3280      const result = await super.executeExtrinsic(3281        sender,3282        'api.tx.sudo.sudo',3283        [call],3284        expectSuccess,3285        options,3286      );32873288      if (result.status === 'Fail') return result;32893290      const data = (result.result.events.find(x => x.event.section == 'sudo' && x.event.method == 'Sudid')?.event.data as any).sudoResult;3291      if (data.isErr) {3292        if (data.asErr.isModule) {3293          const error = (result.result.events[1].event.data as any).sudoResult.asErr.asModule;3294          const metaError = super.getApi()?.registry.findMetaError(error);3295          throw new Error(`${metaError.section}.${metaError.name}`);3296        } else {3297          throw new Error(data.asErr.toHuman());3298        }3299      }3300      return result;3301    }3302  };3303}33043305export class UniqueBaseCollection {3306  helper: UniqueHelper;3307  collectionId: number;33083309  constructor(collectionId: number, uniqueHelper: UniqueHelper) {3310    this.collectionId = collectionId;3311    this.helper = uniqueHelper;3312  }33133314  async getData() {3315    return await this.helper.collection.getData(this.collectionId);3316  }33173318  async getLastTokenId() {3319    return await this.helper.collection.getLastTokenId(this.collectionId);3320  }33213322  async doesTokenExist(tokenId: number) {3323    return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);3324  }33253326  async getAdmins() {3327    return await this.helper.collection.getAdmins(this.collectionId);3328  }33293330  async getAllowList() {3331    return await this.helper.collection.getAllowList(this.collectionId);3332  }33333334  async getEffectiveLimits() {3335    return await this.helper.collection.getEffectiveLimits(this.collectionId);3336  }33373338  async getProperties(propertyKeys?: string[] | null) {3339    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);3340  }33413342  async getPropertiesConsumedSpace() {3343    return await this.helper.collection.getPropertiesConsumedSpace(this.collectionId);3344  }33453346  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {3347    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);3348  }33493350  async getOptions() {3351    return await this.helper.collection.getCollectionOptions(this.collectionId);3352  }33533354  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {3355    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);3356  }33573358  async confirmSponsorship(signer: TSigner) {3359    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);3360  }33613362  async removeSponsor(signer: TSigner) {3363    return await this.helper.collection.removeSponsor(signer, this.collectionId);3364  }33653366  async setLimits(signer: TSigner, limits: ICollectionLimits) {3367    return await this.helper.collection.setLimits(signer, this.collectionId, limits);3368  }33693370  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {3371    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);3372  }33733374  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3375    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);3376  }33773378  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {3379    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);3380  }33813382  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {3383    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);3384  }33853386  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {3387    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);3388  }33893390  async setProperties(signer: TSigner, properties: IProperty[]) {3391    return await this.helper.collection.setProperties(signer, this.collectionId, properties);3392  }33933394  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3395    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);3396  }33973398  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {3399    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);3400  }34013402  async enableNesting(signer: TSigner, permissions: INestingPermissions) {3403    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);3404  }34053406  async disableNesting(signer: TSigner) {3407    return await this.helper.collection.disableNesting(signer, this.collectionId);3408  }34093410  async burn(signer: TSigner) {3411    return await this.helper.collection.burn(signer, this.collectionId);3412  }34133414  scheduleAt<T extends UniqueHelper>(3415    executionBlockNumber: number,3416    options: ISchedulerOptions = {},3417  ) {3418    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3419    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3420  }34213422  scheduleAfter<T extends UniqueHelper>(3423    blocksBeforeExecution: number,3424    options: ISchedulerOptions = {},3425  ) {3426    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3427    return new UniqueBaseCollection(this.collectionId, scheduledHelper);3428  }34293430  getSudo<T extends UniqueHelper>() {3431    return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());3432  }3433}343434353436export class UniqueNFTCollection extends UniqueBaseCollection {3437  getTokenObject(tokenId: number) {3438    return new UniqueNFToken(tokenId, this);3439  }34403441  async getTokensByAddress(addressObj: ICrossAccountId) {3442    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);3443  }34443445  async getToken(tokenId: number, blockHashAt?: string) {3446    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);3447  }34483449  async getTokenOwner(tokenId: number, blockHashAt?: string) {3450    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3451  }34523453  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3454    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3455  }34563457  async getTokenChildren(tokenId: number, blockHashAt?: string) {3458    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);3459  }34603461  async getPropertyPermissions(propertyKeys: string[] | null = null) {3462    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);3463  }34643465  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3466    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3467  }34683469  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3470    const api = this.helper.getApi();3471    const props = (await api.query.nonfungible.tokenProperties(this.collectionId, tokenId)).toJSON();34723473    return (props! as any).consumedSpace;3474  }34753476  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {3477    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);3478  }34793480  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3481    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);3482  }34833484  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {3485    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);3486  }34873488  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {3489    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);3490  }34913492  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3493    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});3494  }34953496  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {3497    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);3498  }34993500  async burnToken(signer: TSigner, tokenId: number) {3501    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);3502  }35033504  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {3505    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);3506  }35073508  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3509    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);3510  }35113512  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3513    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3514  }35153516  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3517    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3518  }35193520  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3521    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3522  }35233524  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3525    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3526  }35273528  scheduleAt<T extends UniqueHelper>(3529    executionBlockNumber: number,3530    options: ISchedulerOptions = {},3531  ) {3532    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3533    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3534  }35353536  scheduleAfter<T extends UniqueHelper>(3537    blocksBeforeExecution: number,3538    options: ISchedulerOptions = {},3539  ) {3540    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3541    return new UniqueNFTCollection(this.collectionId, scheduledHelper);3542  }35433544  getSudo<T extends UniqueHelper>() {3545    return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());3546  }3547}354835493550export class UniqueRFTCollection extends UniqueBaseCollection {3551  getTokenObject(tokenId: number) {3552    return new UniqueRFToken(tokenId, this);3553  }35543555  async getToken(tokenId: number, blockHashAt?: string) {3556    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);3557  }35583559  async getTokenOwner(tokenId: number, blockHashAt?: string) {3560    return await this.helper.rft.getTokenOwner(this.collectionId, tokenId, blockHashAt);3561  }35623563  async getTokensByAddress(addressObj: ICrossAccountId) {3564    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);3565  }35663567  async getTop10TokenOwners(tokenId: number) {3568    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);3569  }35703571  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {3572    return await this.helper.rft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);3573  }35743575  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {3576    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);3577  }35783579  async getTokenTotalPieces(tokenId: number) {3580    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);3581  }35823583  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3584    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);3585  }35863587  async getPropertyPermissions(propertyKeys: string[] | null = null) {3588    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);3589  }35903591  async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {3592    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);3593  }35943595  async getTokenPropertiesConsumedSpace(tokenId: number): Promise<number> {3596    const api = this.helper.getApi();3597    const props = (await api.query.refungible.tokenProperties(this.collectionId, tokenId)).toJSON();35983599    return (props! as any).consumedSpace;3600  }36013602  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {3603    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);3604  }36053606  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3607    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);3608  }36093610  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {3611    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);3612  }36133614  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {3615    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);3616  }36173618  async mintToken(signer: TSigner, pieces = 1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {3619    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});3620  }36213622  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {3623    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);3624  }36253626  async burnToken(signer: TSigner, tokenId: number, amount=1n) {3627    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);3628  }36293630  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {3631    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);3632  }36333634  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {3635    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);3636  }36373638  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {3639    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);3640  }36413642  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {3643    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);3644  }36453646  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {3647    return await this.helper.rft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);3648  }36493650  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3651    return await this.helper.rft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);3652  }36533654  scheduleAt<T extends UniqueHelper>(3655    executionBlockNumber: number,3656    options: ISchedulerOptions = {},3657  ) {3658    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3659    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3660  }36613662  scheduleAfter<T extends UniqueHelper>(3663    blocksBeforeExecution: number,3664    options: ISchedulerOptions = {},3665  ) {3666    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3667    return new UniqueRFTCollection(this.collectionId, scheduledHelper);3668  }36693670  getSudo<T extends UniqueHelper>() {3671    return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());3672  }3673}367436753676export class UniqueFTCollection extends UniqueBaseCollection {3677  async getBalance(addressObj: ICrossAccountId) {3678    return await this.helper.ft.getBalance(this.collectionId, addressObj);3679  }36803681  async getTotalPieces() {3682    return await this.helper.ft.getTotalPieces(this.collectionId);3683  }36843685  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3686    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);3687  }36883689  async getTop10Owners() {3690    return await this.helper.ft.getTop10Owners(this.collectionId);3691  }36923693  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {3694    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);3695  }36963697  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {3698    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);3699  }37003701  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3702    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);3703  }37043705  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3706    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);3707  }37083709  async burnTokens(signer: TSigner, amount=1n) {3710    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);3711  }37123713  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3714    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);3715  }37163717  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3718    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);3719  }37203721  scheduleAt<T extends UniqueHelper>(3722    executionBlockNumber: number,3723    options: ISchedulerOptions = {},3724  ) {3725    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);3726    return new UniqueFTCollection(this.collectionId, scheduledHelper);3727  }37283729  scheduleAfter<T extends UniqueHelper>(3730    blocksBeforeExecution: number,3731    options: ISchedulerOptions = {},3732  ) {3733    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);3734    return new UniqueFTCollection(this.collectionId, scheduledHelper);3735  }37363737  getSudo<T extends UniqueHelper>() {3738    return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());3739  }3740}374137423743export class UniqueBaseToken {3744  collection: UniqueNFTCollection | UniqueRFTCollection;3745  collectionId: number;3746  tokenId: number;37473748  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {3749    this.collection = collection;3750    this.collectionId = collection.collectionId;3751    this.tokenId = tokenId;3752  }37533754  async getNextSponsored(addressObj: ICrossAccountId) {3755    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);3756  }37573758  async getProperties(propertyKeys?: string[] | null) {3759    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);3760  }37613762  async getTokenPropertiesConsumedSpace() {3763    return await this.collection.getTokenPropertiesConsumedSpace(this.tokenId);3764  }37653766  async setProperties(signer: TSigner, properties: IProperty[]) {3767    return await this.collection.setTokenProperties(signer, this.tokenId, properties);3768  }37693770  async deleteProperties(signer: TSigner, propertyKeys: string[]) {3771    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);3772  }37733774  async doesExist() {3775    return await this.collection.doesTokenExist(this.tokenId);3776  }37773778  nestingAccount() {3779    return this.collection.helper.util.getTokenAccount(this);3780  }37813782  scheduleAt<T extends UniqueHelper>(3783    executionBlockNumber: number,3784    options: ISchedulerOptions = {},3785  ) {3786    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3787    return new UniqueBaseToken(this.tokenId, scheduledCollection);3788  }37893790  scheduleAfter<T extends UniqueHelper>(3791    blocksBeforeExecution: number,3792    options: ISchedulerOptions = {},3793  ) {3794    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3795    return new UniqueBaseToken(this.tokenId, scheduledCollection);3796  }37973798  getSudo<T extends UniqueHelper>() {3799    return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());3800  }3801}380238033804export class UniqueNFToken extends UniqueBaseToken {3805  collection: UniqueNFTCollection;38063807  constructor(tokenId: number, collection: UniqueNFTCollection) {3808    super(tokenId, collection);3809    this.collection = collection;3810  }38113812  async getData(blockHashAt?: string) {3813    return await this.collection.getToken(this.tokenId, blockHashAt);3814  }38153816  async getOwner(blockHashAt?: string) {3817    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3818  }38193820  async getTopmostOwner(blockHashAt?: string) {3821    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3822  }38233824  async getChildren(blockHashAt?: string) {3825    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);3826  }38273828  async nest(signer: TSigner, toTokenObj: IToken) {3829    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3830  }38313832  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3833    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3834  }38353836  async transfer(signer: TSigner, addressObj: ICrossAccountId) {3837    return await this.collection.transferToken(signer, this.tokenId, addressObj);3838  }38393840  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {3841    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);3842  }38433844  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {3845    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);3846  }38473848  async isApproved(toAddressObj: ICrossAccountId) {3849    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);3850  }38513852  async burn(signer: TSigner) {3853    return await this.collection.burnToken(signer, this.tokenId);3854  }38553856  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {3857    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);3858  }38593860  scheduleAt<T extends UniqueHelper>(3861    executionBlockNumber: number,3862    options: ISchedulerOptions = {},3863  ) {3864    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3865    return new UniqueNFToken(this.tokenId, scheduledCollection);3866  }38673868  scheduleAfter<T extends UniqueHelper>(3869    blocksBeforeExecution: number,3870    options: ISchedulerOptions = {},3871  ) {3872    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3873    return new UniqueNFToken(this.tokenId, scheduledCollection);3874  }38753876  getSudo<T extends UniqueHelper>() {3877    return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3878  }3879}38803881export class UniqueRFToken extends UniqueBaseToken {3882  collection: UniqueRFTCollection;38833884  constructor(tokenId: number, collection: UniqueRFTCollection) {3885    super(tokenId, collection);3886    this.collection = collection;3887  }38883889  async getData(blockHashAt?: string) {3890    return await this.collection.getToken(this.tokenId, blockHashAt);3891  }38923893  async getOwner(blockHashAt?: string) {3894    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);3895  }38963897  async getTop10Owners() {3898    return await this.collection.getTop10TokenOwners(this.tokenId);3899  }39003901  async getTopmostOwner(blockHashAt?: string) {3902    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);3903  }39043905  async nest(signer: TSigner, toTokenObj: IToken) {3906    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);3907  }39083909  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {3910    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);3911  }39123913  async getBalance(addressObj: ICrossAccountId) {3914    return await this.collection.getTokenBalance(this.tokenId, addressObj);3915  }39163917  async getTotalPieces() {3918    return await this.collection.getTokenTotalPieces(this.tokenId);3919  }39203921  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3922    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3923  }39243925  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3926    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3927  }39283929  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3930    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3931  }39323933  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3934    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3935  }39363937  async repartition(signer: TSigner, amount: bigint) {3938    return await this.collection.repartitionToken(signer, this.tokenId, amount);3939  }39403941  async burn(signer: TSigner, amount=1n) {3942    return await this.collection.burnToken(signer, this.tokenId, amount);3943  }39443945  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3946    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3947  }39483949  scheduleAt<T extends UniqueHelper>(3950    executionBlockNumber: number,3951    options: ISchedulerOptions = {},3952  ) {3953    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);3954    return new UniqueRFToken(this.tokenId, scheduledCollection);3955  }39563957  scheduleAfter<T extends UniqueHelper>(3958    blocksBeforeExecution: number,3959    options: ISchedulerOptions = {},3960  ) {3961    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);3962    return new UniqueRFToken(this.tokenId, scheduledCollection);3963  }39643965  getSudo<T extends UniqueHelper>() {3966    return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3967  }3968}