git.delta.rocks / unique-network / refs/commits / 415e2e02d914

difftreelog

tests(nesting+properties): collection and token interfaces + make lower case not default for token addresses + more consts from old helpers included

Fahrrader2022-09-27parent: #b0b1d40.patch.diff
in: master

8 files changed

modifiedtests/src/fungible.test.tsdiffbeforeafterboth
--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -15,9 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {IKeyringPair} from '@polkadot/types/types';
-import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
-
-const U128_MAX = (1n << 128n) - 1n;
+import {itSub, usingPlaygrounds, expect, U128_MAX} from './util/playgrounds';
 
 describe('integration test: Fungible functionality:', () => {
   let alice: IKeyringPair;
modifiedtests/src/nesting/graphs.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/graphs.test.ts
+++ b/tests/src/nesting/graphs.test.ts
@@ -16,7 +16,8 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {expect, itSub, usingPlaygrounds} from '../util/playgrounds';
-import {UniqueHelper, UniqueNFTToken} from '../util/playgrounds/unique';
+import {ITokenNonfungible} from '../util/playgrounds/types';
+import {UniqueHelper} from '../util/playgrounds/unique';
 
 /**
  * ```dot
@@ -25,7 +26,7 @@
  * 8 -> 5
  * ```
  */
-async function buildComplexObjectGraph(helper: UniqueHelper, sender: IKeyringPair): Promise<UniqueNFTToken[]> {
+async function buildComplexObjectGraph(helper: UniqueHelper, sender: IKeyringPair): Promise<ITokenNonfungible[]> {
   const collection = await helper.nft.mintCollection(sender, {permissions: {nesting: {tokenOwner: true}}});
   const tokens = await collection.mintMultipleTokens(sender, Array(8).fill({owner: {Substrate: sender.address}}));
 
modifiedtests/src/nesting/nest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -35,7 +35,7 @@
     // Create an immediately nested token
     const nestedToken = await collection.mintToken(alice, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
     
     // Create a token to be nested
     const newToken = await collection.mintToken(alice);
@@ -43,14 +43,14 @@
     // Nest
     await newToken.nest(alice, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Move bundle to different user
     await targetToken.transfer(alice, {Substrate: bob.address});
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Unnest
     await newToken.unnest(bob, targetToken, {Substrate: bob.address});
@@ -65,12 +65,12 @@
 
     // Create a nested token
     const tokenC = await collection.mintToken(alice, tokenA.nestingAccount());
-    expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccount());
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenA.nestingAccountInLowerCase());
     
     // Transfer the nested token to another token
     await expect(tokenC.transferFrom(alice, tokenA.nestingAccount(), tokenB.nestingAccount())).to.be.fulfilled;
     expect(await tokenC.getTopmostOwner()).to.be.deep.equal({Substrate: alice.address});
-    expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccount());
+    expect(await tokenC.getOwner()).to.be.deep.equal(tokenB.nestingAccountInLowerCase());
   });
 
   itSub('Checks token children', async ({helper}) => {
@@ -150,13 +150,13 @@
     // Create an immediately nested token
     const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Create a token to be nested and nest
     const newToken = await collection.mintToken(bob);
     await newToken.nest(bob, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   itSub('Admin (NFT): Admin and Token Owner can operate together', async ({helper}) => {
@@ -167,13 +167,13 @@
     // Create an immediately nested token by an administrator
     const nestedToken = await collection.mintToken(bob, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Create a token to be nested and nest
     const newToken = await collection.mintToken(alice, {Substrate: charlie.address});
     await newToken.nest(charlie, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   itSub('Admin (NFT): allows an Admin to nest a token (Restricted nesting)', async ({helper}) => {
@@ -187,13 +187,13 @@
     // Create an immediately nested token
     const nestedToken = await collectionB.mintToken(bob, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Create a token to be nested and nest
     const newToken = await collectionB.mintToken(bob);
     await newToken.nest(bob, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   // ---------- Non-Fungible ----------
@@ -207,13 +207,13 @@
     // Create an immediately nested token
     const nestedToken = await collection.mintToken(charlie, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Create a token to be nested and nest
     const newToken = await collection.mintToken(charlie);
     await newToken.nest(charlie, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   itSub('NFT: allows an Owner to nest/unnest their token (Restricted nesting)', async ({helper}) => {
@@ -233,13 +233,13 @@
     // Create an immediately nested token
     const nestedToken = await collectionB.mintToken(charlie, targetToken.nestingAccount());
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Create a token to be nested and nest
     const newToken = await collectionB.mintToken(charlie);
     await newToken.nest(charlie, targetToken);
     expect(await newToken.getTopmostOwner()).to.be.deep.equal({Substrate: charlie.address});
-    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await newToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   // ---------- Fungible ----------
@@ -424,7 +424,7 @@
 
     expect(await targetToken.getChildren()).to.be.length(1);
     expect(await nestedToken.getTopmostOwner()).to.be.deep.equal({Substrate: bob.address});
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   itSub('Admin (NFT): disallows an Admin to nest a token from an unlisted collection (Restricted nesting)', async ({helper}) => {
modifiedtests/src/nesting/properties.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -14,19 +14,10 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-/*import usingApi, {executeTransaction} from '../substrate/substrate-api';
-import {
-  addCollectionAdminExpectSuccess,
-  CollectionMode,
-  createCollectionExpectSuccess,
-  setCollectionPermissionsExpectSuccess,
-  createItemExpectSuccess,
-  getCreateCollectionResult,
-  transferExpectSuccess,
-} from '../util/helpers';*/
 import {IKeyringPair} from '@polkadot/types/types';
 import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from '../util/playgrounds';
-import {UniqueCollectionBase, UniqueHelper, UniqueNFTCollection, UniqueNFTToken, UniqueRFTCollection, UniqueRFTToken} from '../util/playgrounds/unique';
+import {ICollectionBase, ICollectionNFT, ITokenNonfungible, ICollectionRFT, ITokenRefungible} from '../util/playgrounds/types';
+import {UniqueHelper} from '../util/playgrounds/unique';
 
 // ---------- COLLECTION PROPERTIES
 
@@ -46,7 +37,7 @@
     expect(await collection.getProperties()).to.be.empty;
   });
 
-  async function testSetsPropertiesForCollection(collection: UniqueCollectionBase) {
+  async function testSetsPropertiesForCollection(collection: ICollectionBase) {
     // As owner
     await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}])).to.be.fulfilled;
 
@@ -70,7 +61,7 @@
     await testSetsPropertiesForCollection(await helper.rft.mintCollection(alice));
   });
 
-  async function testCheckValidNames(collection: UniqueCollectionBase) {
+  async function testCheckValidNames(collection: ICollectionBase) {
     // alpha symbols
     await expect(collection.setProperties(alice, [{key: 'answer'}])).to.be.fulfilled;
 
@@ -104,7 +95,7 @@
     await testCheckValidNames(await helper.rft.mintCollection(alice));
   });
 
-  async function testChangesProperties(collection: UniqueCollectionBase) {
+  async function testChangesProperties(collection: ICollectionBase) {
     await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: ''}])).to.be.fulfilled;
 
     // Mutate the properties
@@ -125,7 +116,7 @@
     await testChangesProperties(await helper.rft.mintCollection(alice));
   });
 
-  async function testDeleteProperties(collection: UniqueCollectionBase) {
+  async function testDeleteProperties(collection: ICollectionBase) {
     await expect(collection.setProperties(alice, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}])).to.be.fulfilled;
 
     await expect(collection.deleteProperties(alice, ['electron'])).to.be.fulfilled;
@@ -156,7 +147,7 @@
     });
   });
   
-  async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: UniqueCollectionBase) {  
+  async function testFailsSetPropertiesIfNotOwnerOrAdmin(collection: ICollectionBase) {  
     await expect(collection.setProperties(bob, [{key: 'electron', value: 'come bond'}, {key: 'black_hole', value: 'LIGO'}]))
       .to.be.rejectedWith(/common\.NoPermission/);
 
@@ -171,7 +162,7 @@
     await testFailsSetPropertiesIfNotOwnerOrAdmin(await helper.rft.mintCollection(alice));
   });
   
-  async function testFailsSetPropertiesThatExeedLimits(collection: UniqueCollectionBase) {
+  async function testFailsSetPropertiesThatExeedLimits(collection: ICollectionBase) {
     const spaceLimit = (await (collection.helper!.api! as any).query.common.collectionProperties(collection.collectionId)).spaceLimit.toNumber();
   
     // Mute the general tx parsing error, too many bytes to process
@@ -200,7 +191,7 @@
     await testFailsSetPropertiesThatExeedLimits(await helper.rft.mintCollection(alice));
   });
   
-  async function testFailsSetMorePropertiesThanAllowed(collection: UniqueCollectionBase) {
+  async function testFailsSetMorePropertiesThanAllowed(collection: ICollectionBase) {
     const propertiesToBeSet = [];
     for (let i = 0; i < 65; i++) {
       propertiesToBeSet.push({
@@ -223,7 +214,7 @@
     await testFailsSetMorePropertiesThanAllowed(await helper.rft.mintCollection(alice));
   });
   
-  async function testFailsSetPropertiesWithInvalidNames(collection: UniqueCollectionBase) {
+  async function testFailsSetPropertiesWithInvalidNames(collection: ICollectionBase) {
     const invalidProperties = [
       [{key: 'electron', value: 'negative'}, {key: 'string theory', value: 'understandable'}],
       [{key: 'Mr/Sandman', value: 'Bring me a gene'}],
@@ -290,7 +281,7 @@
     expect(propertyRights).to.be.empty;
   });
   
-  async function testSetsAccessRightsToProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {  
+  async function testSetsAccessRightsToProperties(collection: ICollectionNFT | ICollectionRFT) {  
     await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true}}]))
       .to.be.fulfilled;
 
@@ -314,7 +305,7 @@
     await testSetsAccessRightsToProperties(await helper.rft.mintCollection(alice));
   });
   
-  async function testChangesAccessRightsToProperty(collection: UniqueNFTCollection | UniqueRFTCollection) {
+  async function testChangesAccessRightsToProperty(collection: ICollectionNFT | ICollectionRFT) {
     await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: true, collectionAdmin: true}}]))
       .to.be.fulfilled;
 
@@ -347,7 +338,7 @@
     });
   });
 
-  async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: UniqueNFTCollection | UniqueRFTCollection) {
+  async function testPreventsFromSettingAccessRightsNotAdminOrOwner(collection: ICollectionNFT | ICollectionRFT) {
     await expect(collection.setTokenPropertyPermissions(bob, [{key: 'skullduggery', permission: {mutable: true, tokenOwner: true}}]))
       .to.be.rejectedWith(/common\.NoPermission/);
 
@@ -363,7 +354,7 @@
     await testPreventsFromSettingAccessRightsNotAdminOrOwner(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventFromAddingTooManyPossibleProperties(collection: UniqueNFTCollection | UniqueRFTCollection) {  
+  async function testPreventFromAddingTooManyPossibleProperties(collection: ICollectionNFT | ICollectionRFT) {  
     const constitution = [];
     for (let i = 0; i < 65; i++) {
       constitution.push({
@@ -387,7 +378,7 @@
     await testPreventFromAddingTooManyPossibleProperties(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventAccessRightsModifiedIfConstant(collection: UniqueNFTCollection | UniqueRFTCollection) {
+  async function testPreventAccessRightsModifiedIfConstant(collection: ICollectionNFT | ICollectionRFT) {
     await expect(collection.setTokenPropertyPermissions(alice, [{key: 'skullduggery', permission: {mutable: false, tokenOwner: true}}]))
       .to.be.fulfilled;
 
@@ -408,7 +399,7 @@
     await testPreventAccessRightsModifiedIfConstant(await helper.rft.mintCollection(alice));
   });
 
-  async function testPreventsAddingPropertiesWithInvalidNames(collection: UniqueNFTCollection | UniqueRFTCollection) {
+  async function testPreventsAddingPropertiesWithInvalidNames(collection: ICollectionNFT | ICollectionRFT) {
     const invalidProperties = [
       [{key: 'skullduggery', permission: {tokenOwner: true}}, {key: 'im possible', permission: {collectionAdmin: true}}],
       [{key: 'G#4', permission: {tokenOwner: true}}],
@@ -478,7 +469,7 @@
     ];
   });
   
-  async function testReadsYetEmptyProperties(token: UniqueNFTToken | UniqueRFTToken) {
+  async function testReadsYetEmptyProperties(token: ITokenNonfungible | ITokenRefungible) {
     const properties = await token.getProperties();
     expect(properties).to.be.empty;
 
@@ -498,7 +489,7 @@
     await testReadsYetEmptyProperties(token);
   });
 
-  async function testAssignPropertiesAccordingToPermissions(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testAssignPropertiesAccordingToPermissions(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     await token.collection.addAdmin(alice, {Substrate: bob.address});
     await token.transfer(alice, {Substrate: charlie.address}, pieces);
 
@@ -544,7 +535,7 @@
     await testAssignPropertiesAccordingToPermissions(token, 100n);
   });
 
-  async function testChangesPropertiesAccordingPermission(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testChangesPropertiesAccordingPermission(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     await token.collection.addAdmin(alice, {Substrate: bob.address});
     await token.transfer(alice, {Substrate: charlie.address}, pieces);
 
@@ -597,7 +588,7 @@
     await testChangesPropertiesAccordingPermission(token, 100n);
   });
 
-  async function testDeletePropertiesAccordingPermission(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testDeletePropertiesAccordingPermission(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     await token.collection.addAdmin(alice, {Substrate: bob.address});
     await token.transfer(alice, {Substrate: charlie.address}, pieces);
 
@@ -808,7 +799,7 @@
     return (await (mode == 'NFT' ? api.query.nonfungible : api.query.refungible).tokenProperties(collectionId, tokenId)).toJSON().consumedSpace;
   }
 
-  async function prepare(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint): Promise<number> {
+  async function prepare(token: ITokenNonfungible | ITokenRefungible, pieces: bigint): Promise<number> {
     await token.collection.addAdmin(alice, {Substrate: bob.address});
     await token.transfer(alice, {Substrate: charlie.address}, pieces);
 
@@ -832,7 +823,7 @@
     return originalSpace;
   }
 
-  async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     const originalSpace = await prepare(token, pieces);
 
     let i = 0;
@@ -867,7 +858,7 @@
     await testForbidsChangingDeletingPropertiesUserOutsideOfPermissions(token, 100n);
   });
 
-  async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testForbidsChangingDeletingPropertiesIfPropertyImmutable(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     const originalSpace = await prepare(token, pieces);
 
     let i = 0;
@@ -902,7 +893,7 @@
     await testForbidsChangingDeletingPropertiesIfPropertyImmutable(token, 100n);
   });
 
-  async function testForbidsAddingPropertiesIfPropertyNotDeclared(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testForbidsAddingPropertiesIfPropertyNotDeclared(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     const originalSpace = await prepare(token, pieces);
 
     await expect(
@@ -938,7 +929,7 @@
     await testForbidsAddingPropertiesIfPropertyNotDeclared(token, 100n);
   });
 
-  async function testForbidsAddingTooManyProperties(token: UniqueNFTToken | UniqueRFTToken, pieces: bigint) {
+  async function testForbidsAddingTooManyProperties(token: ITokenNonfungible | ITokenRefungible, pieces: bigint) {
     const originalSpace = await prepare(token, pieces);
 
     await expect(
@@ -993,7 +984,7 @@
     });
   });
 
-  async function prepare(helper: UniqueHelper): Promise<UniqueRFTToken> {
+  async function prepare(helper: UniqueHelper): Promise<ITokenRefungible> {
     const collection = await helper.rft.mintCollection(alice);
     const token = await collection.mintToken(alice, 100n);
     
modifiedtests/src/nesting/unnest.test.tsdiffbeforeafterboth
--- a/tests/src/nesting/unnest.test.ts
+++ b/tests/src/nesting/unnest.test.ts
@@ -105,11 +105,11 @@
 
     // Try to unnest
     await expect(nestedToken.unnest(bob, targetToken, {Substrate: alice.address})).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
 
     // Try to burn
     await expect(nestedToken.burnFrom(bob, targetToken.nestingAccount())).to.be.rejectedWith(/common\.ApprovedValueTooLow/);
-    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccount());
+    expect(await nestedToken.getOwner()).to.be.deep.equal(targetToken.nestingAccountInLowerCase());
   });
 
   // todo another test for creating excessive depth matryoshka with Ethereum?
modifiedtests/src/util/playgrounds/index.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/index.ts
+++ b/tests/src/util/playgrounds/index.ts
@@ -9,10 +9,16 @@
 import '../../interfaces/augment-api-events';
 import {DevUniqueHelper, SilentLogger, SilentConsole} from './unique.dev';
 
-
 chai.use(chaiAsPromised);
 export const expect = chai.expect;
 
+export const U128_MAX = (1n << 128n) - 1n;
+
+const MICROUNIQUE = 1_000_000_000_000n;
+const MILLIUNIQUE = 1_000n * MICROUNIQUE;
+const CENTIUNIQUE = 10n * MILLIUNIQUE;
+export const UNIQUE = 100n * CENTIUNIQUE;
+
 export const usingPlaygrounds = async (code: (helper: DevUniqueHelper, privateKey: (seed: string) => IKeyringPair) => Promise<void>, url: string = config.substrateUrl) => {
   const silentConsole = new SilentConsole();
   silentConsole.enable();
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -2,6 +2,7 @@
 // SPDX-License-Identifier: Apache-2.0
 
 import {IKeyringPair} from '@polkadot/types/types';
+import {UniqueHelper} from './unique';
 
 export interface IEvent {
   section: string;
@@ -106,7 +107,7 @@
   }
 }
 
-export interface IToken {
+export interface ITokenAddress {
   collectionId: number;
   tokenId: number;
 }
@@ -167,3 +168,169 @@
 export type TApiAllowedListeners = 'connected' | 'disconnected' | 'error' | 'ready' | 'decorated';
 export type TUniqueNetworks = 'opal' | 'quartz' | 'unique';
 export type TSigner = IKeyringPair; // | 'string'
+
+export interface ICollectionBase {
+  helper: UniqueHelper;
+  collectionId: number;
+  getData: () => Promise<{
+    id: number;
+    name: string;
+    description: string;
+    tokensCount: number;
+    admins: ICrossAccountId[];
+    normalizedOwner: TSubstrateAccount;
+    raw: any
+  } | null>;
+  getLastTokenId: () => Promise<number>;
+  isTokenExists: (tokenId: number) => Promise<boolean>;
+  getAdmins: () => Promise<ICrossAccountId[]>;
+  getAllowList: () => Promise<ICrossAccountId[]>;
+  getEffectiveLimits: () => Promise<ICollectionLimits>;
+  getProperties: (propertyKeys?: string[]) => Promise<IProperty[]>;
+  getTokenNextSponsored: (tokenId: number, addressObj: ICrossAccountId) => Promise<number | null>;
+  setSponsor: (signer: TSigner, sponsorAddress: TSubstrateAccount) => Promise<boolean>;
+  confirmSponsorship: (signer: TSigner) => Promise<boolean>;
+  removeSponsor: (signer: TSigner) => Promise<boolean>;
+  setLimits: (signer: TSigner, limits: ICollectionLimits) => Promise<boolean>;
+  changeOwner: (signer: TSigner, ownerAddress: TSubstrateAccount) => Promise<boolean>;
+  addAdmin: (signer: TSigner, adminAddressObj: ICrossAccountId) => Promise<boolean>;
+  addToAllowList: (signer: TSigner, addressObj: ICrossAccountId) => Promise<boolean>;
+  removeFromAllowList: (signer: TSigner, addressObj: ICrossAccountId) => Promise<boolean>;
+  removeAdmin: (signer: TSigner, adminAddressObj: ICrossAccountId) => Promise<boolean>;
+  setProperties: (signer: TSigner, properties: IProperty[]) => Promise<boolean>;
+  deleteProperties: (signer: TSigner, propertyKeys: string[]) => Promise<boolean>;
+  setPermissions: (signer: TSigner, permissions: ICollectionPermissions) => Promise<boolean>;
+  enableNesting: (signer: TSigner, permissions: INestingPermissions) => Promise<boolean>;
+  disableNesting: (signer: TSigner) => Promise<boolean>;
+  burn: (signer: TSigner) => Promise<boolean>;
+}
+
+export interface ICollectionNFT extends ICollectionBase {
+  getTokenObject: (tokenId: number) => ITokenNonfungible; // todo:playgrounds
+  getTokensByAddress: (addressObj: ICrossAccountId) => Promise<number[]>;
+  getToken: (tokenId: number, blockHashAt?: string) => Promise<{
+    properties: IProperty[];
+    owner: ICrossAccountId;
+    normalizedOwner: ICrossAccountId;
+  }| null>;
+  getTokenOwner: (tokenId: number, blockHashAt?: string) => Promise<ICrossAccountId>;
+  getTokenTopmostOwner: (tokenId: number, blockHashAt?: string) => Promise<ICrossAccountId | null>;
+  getTokenChildren: (tokenId: number, blockHashAt?: string) => Promise<ITokenAddress[]>; // todo:playgrounds
+  getPropertyPermissions: (propertyKeys?: string[]) => Promise<ITokenPropertyPermission[]>;
+  getTokenProperties: (tokenId: number, propertyKeys?: string[]) => Promise<IProperty[]>;
+  transferToken: (signer: TSigner, tokenId: number, addressObj: ICrossAccountId) => Promise<boolean>;
+  transferTokenFrom: (signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  approveToken: (signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  isTokenApproved: (tokenId: number, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  mintToken: (signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) => Promise<ITokenNonfungible>;// todo:playgrounds
+  mintMultipleTokens: (signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) => Promise<ITokenNonfungible[]>;// todo:playgrounds
+  burnToken: (signer: TSigner, tokenId: number) => Promise<{
+    success: boolean,
+    token: number | null
+  }>;
+  burnTokenFrom: (signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) => Promise<boolean>;
+  setTokenProperties: (signer: TSigner, tokenId: number, properties: IProperty[]) => Promise<boolean>;
+  deleteTokenProperties: (signer: TSigner, tokenId: number, propertyKeys: string[]) => Promise<boolean>;
+  setTokenPropertyPermissions: (signer: TSigner, permissions: ITokenPropertyPermission[]) => Promise<boolean>;
+  nestToken: (signer: TSigner, tokenId: number, toTokenObj: ITokenAddress) => Promise<boolean>;
+  unnestToken: (signer: TSigner, tokenId: number, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) => Promise<boolean>;
+}
+
+export interface ICollectionRFT extends ICollectionBase {
+  getTokenObject: (tokenId: number) => ITokenRefungible;
+  getToken: (tokenId: number, blockHashAt?: string) => Promise<{
+    properties: IProperty[];
+    owner: ICrossAccountId;
+    normalizedOwner: ICrossAccountId;
+  }| null>;
+  getTokensByAddress: (addressObj: ICrossAccountId) => Promise<number[]>;
+  getTop10TokenOwners: (tokenId: number) => Promise<ICrossAccountId[]>;
+  getTokenBalance: (tokenId: number, addressObj: ICrossAccountId) => Promise<bigint>;
+  getTokenTotalPieces: (tokenId: number) => Promise<bigint>;
+  getTokenApprovedPieces: (tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) => Promise<bigint>;
+  getPropertyPermissions: (propertyKeys?: string[] | null) => Promise<ITokenPropertyPermission[]>;
+  getTokenProperties: (tokenId: number, propertyKeys?: string[]) => Promise<IProperty[]>;
+  transferToken: (signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  transferTokenFrom: (signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  approveToken: (signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  repartitionToken: (signer: TSigner, tokenId: number, amount: bigint) => Promise<boolean>;
+  mintToken: (signer: TSigner, pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]) => Promise<ITokenRefungible>;
+  mintMultipleTokens: (signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) => Promise<ITokenRefungible[]>; // todo:playgrounds
+  burnToken: (signer: TSigner, tokenId: number, amount: bigint) => Promise<{
+    success: boolean,
+    token: number | null
+  }>;
+  burnTokenFrom: (signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount: bigint) => Promise<boolean>;
+  setTokenProperties: (signer: TSigner, tokenId: number, properties: IProperty[]) => Promise<boolean>;
+  deleteTokenProperties: (signer: TSigner, tokenId: number, propertyKeys: string[]) => Promise<boolean>;
+  setTokenPropertyPermissions: (signer: TSigner, permissions: ITokenPropertyPermission[]) => Promise<boolean>;
+}
+
+export interface ICollectionFT extends ICollectionBase {
+  getBalance: (addressObj: ICrossAccountId) => Promise<bigint>;
+  getTotalPieces: () => Promise<bigint>;
+  getApprovedTokens: (fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) => Promise<bigint>;
+  getTop10Owners: () => Promise<ICrossAccountId[]>;
+  mint: (signer: TSigner, amount: bigint, owner: ICrossAccountId) => Promise<boolean>;
+  mintWithOneOwner: (signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId) => Promise<boolean>;
+  transfer: (signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  transferFrom: (signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  burnTokens: (signer: TSigner, amount: bigint) => Promise<boolean>;
+  burnTokensFrom: (signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  approveTokens: (signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+}
+
+export interface ITokenBase extends ITokenAddress {
+  collection: ICollectionNFT | ICollectionRFT;
+  getNextSponsored: (addressObj: ICrossAccountId) => Promise<number|null>;
+  getProperties: (propertyKeys?: string[]) => Promise<IProperty[]>;
+  setProperties: (signer: TSigner, properties: IProperty[]) => Promise<boolean>;
+  deleteProperties: (signer: TSigner, propertyKeys: string[]) => Promise<boolean>;
+  nestingAccount: () => ICrossAccountId;
+  nestingAccountInLowerCase: () => ICrossAccountId;
+}
+
+export interface ITokenNonfungible extends ITokenBase {
+  collection: ICollectionNFT;
+  getData: (blockHashAt?: string) => Promise<{
+    properties: IProperty[];
+    owner: ICrossAccountId;
+    normalizedOwner: ICrossAccountId;
+  }| null>;
+  getOwner: (blockHashAt?: string) => Promise<ICrossAccountId>;
+  getTopmostOwner: (blockHashAt?: string) => Promise<ICrossAccountId | null>;
+  getChildren: (blockHashAt?: string) => Promise<ITokenAddress[]>; // todo:playgrounds
+  nest: (signer: TSigner, toTokenObj: ITokenAddress) => Promise<boolean>;
+  unnest: (signer: TSigner, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  transfer: (signer: TSigner, addressObj: ICrossAccountId) => Promise<boolean>;
+  transferFrom: (signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  approve: (signer: TSigner, toAddressObj: ICrossAccountId) => Promise<boolean>;
+  isApproved: (toAddressObj: ICrossAccountId) => Promise<boolean>;
+  burn: (signer: TSigner) => Promise<{
+    success: boolean,
+    token: number | null
+  }>;
+  burnFrom: (signer: TSigner, fromAddressObj: ICrossAccountId) => Promise<boolean>;
+}
+
+export interface ITokenRefungible extends ITokenBase {
+  collection: ICollectionRFT;
+  getData: (blockHashAt?: string) => Promise<{
+    properties: IProperty[];
+    owner: ICrossAccountId;
+    normalizedOwner: ICrossAccountId;
+  }| null>;
+  getTop10Owners: () => Promise<ICrossAccountId[]>;
+  getBalance: (addressObj: ICrossAccountId) => Promise<bigint>;
+  getTotalPieces: () => Promise<bigint>;
+  getApprovedPieces: (fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) => Promise<bigint>;
+  transfer: (signer: TSigner, addressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  transferFrom: (signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  approve: (signer: TSigner, toAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+  repartition: (signer: TSigner, amount: bigint) => Promise<boolean>;
+  burn: (signer: TSigner, amount: bigint) => Promise<{
+    success: boolean,
+    token: number | null
+  }>;
+  burnFrom: (signer: TSigner, fromAddressObj: ICrossAccountId, amount: bigint) => Promise<boolean>;
+}
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} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15  const address = {} as ICrossAccountId;16  if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17  if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18  return address;19};2021const nesting = {22  toChecksumAddress(address: string): string {23    if (typeof address === 'undefined') return '';2425    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627    address = address.toLowerCase().replace(/^0x/i,'');28    const addressHash = keccakAsHex(address).replace(/^0x/i,'');29    const checksumAddress = ['0x'];3031    for (let i = 0; i < address.length; i++) {32      // If ith character is 8 to f then make it uppercase33      if (parseInt(addressHash[i], 16) > 7) {34        checksumAddress.push(address[i].toUpperCase());35      } else {36        checksumAddress.push(address[i]);37      }38    }39    return checksumAddress.join('');40  },41  tokenIdToAddress(collectionId: number, tokenId: number) {42    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);43  },44};4546class UniqueUtil {47  static transactionStatus = {48    NOT_READY: 'NotReady',49    FAIL: 'Fail',50    SUCCESS: 'Success',51  };5253  static chainLogType = {54    EXTRINSIC: 'extrinsic',55    RPC: 'rpc',56  };5758  static getTokenAccount(token: IToken) {59    return {Ethereum: this.getTokenAddress(token).toLowerCase()};60  }6162  static getTokenAddress(token: IToken) {63    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);64  }6566  static getDefaultLogger(): ILogger {67    return {68      log(msg: any, level = 'INFO') {69        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));70      },71      level: {72        ERROR: 'ERROR',73        WARNING: 'WARNING',74        INFO: 'INFO',75      },76    };77  }7879  static vec2str(arr: string[] | number[]) {80    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');81  }8283  static str2vec(string: string) {84    if (typeof string !== 'string') return string;85    return Array.from(string).map(x => x.charCodeAt(0));86  }8788  static fromSeed(seed: string, ss58Format = 42) {89    const keyring = new Keyring({type: 'sr25519', ss58Format});90    return keyring.addFromUri(seed);91  }9293  static normalizeSubstrateAddress(address: string, ss58Format = 42) {94    return encodeAddress(decodeAddress(address), ss58Format);95  }9697  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {98    if (creationResult.status !== this.transactionStatus.SUCCESS) {99      throw Error('Unable to create collection!');100    }101102    let collectionId = null;103    creationResult.result.events.forEach(({event: {data, method, section}}) => {104      if ((section === 'common') && (method === 'CollectionCreated')) {105        collectionId = parseInt(data[0].toString(), 10);106      }107    });108109    if (collectionId === null) {110      throw Error('No CollectionCreated event was found!');111    }112113    return collectionId;114  }115116  static extractTokensFromCreationResult(creationResult: ITransactionResult) {117    if (creationResult.status !== this.transactionStatus.SUCCESS) {118      throw Error('Unable to create tokens!');119    }120    let success = false;121    const tokens = [] as any;122    creationResult.result.events.forEach(({event: {data, method, section}}) => {123      if (method === 'ExtrinsicSuccess') {124        success = true;125      } else if ((section === 'common') && (method === 'ItemCreated')) {126        tokens.push({127          collectionId: parseInt(data[0].toString(), 10),128          tokenId: parseInt(data[1].toString(), 10),129          owner: data[2].toJSON(),130        });131      }132    });133    return {success, tokens};134  }135136  static extractTokensFromBurnResult(burnResult: ITransactionResult) {137    if (burnResult.status !== this.transactionStatus.SUCCESS) {138      throw Error('Unable to burn tokens!');139    }140    let success = false;141    const tokens = [] as any;142    burnResult.result.events.forEach(({event: {data, method, section}}) => {143      if (method === 'ExtrinsicSuccess') {144        success = true;145      } else if ((section === 'common') && (method === 'ItemDestroyed')) {146        tokens.push({147          collectionId: parseInt(data[0].toString(), 10),148          tokenId: parseInt(data[1].toString(), 10),149          owner: data[2].toJSON(),150        });151      }152    });153    return {success, tokens};154  }155156  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {157    let eventId = null;158    events.forEach(({event: {data, method, section}}) => {159      if ((section === expectedSection) && (method === expectedMethod)) {160        eventId = parseInt(data[0].toString(), 10);161      }162    });163164    if (eventId === null) {165      throw Error(`No ${expectedMethod} event was found!`);166    }167    return eventId === collectionId;168  }169170  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {171    const normalizeAddress = (address: string | ICrossAccountId) => {172      if(typeof address === 'string') return address;173      const obj = {} as any;174      Object.keys(address).forEach(k => {175        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];176      });177      if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};178      if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};179      return address;180    };181    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;182    events.forEach(({event: {data, method, section}}) => {183      if ((section === 'common') && (method === 'Transfer')) {184        const hData = (data as any).toJSON();185        transfer = {186          collectionId: hData[0],187          tokenId: hData[1],188          from: normalizeAddress(hData[2]),189          to: normalizeAddress(hData[3]),190          amount: BigInt(hData[4]),191        };192      }193    });194    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;195    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);196    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);197    isSuccess = isSuccess && amount === transfer.amount;198    return isSuccess;199  }200}201202class UniqueEventHelper {203  private static extractIndex(index: any): [number, number] | string {204    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];205    return index.toJSON();206  }207208  private static extractSub(data: any, subTypes: any): {[key: string]: any} {209    let obj: any = {};210    let index = 0;211212    if (data.entries) {213      for(const [key, value] of data.entries()) {214        obj[key] = this.extractData(value, subTypes[index]);215        index++;216      }217    } else obj = data.toJSON();218219    return obj;220  }221  222  private static extractData(data: any, type: any): any {223    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();224    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();225    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);226    return data.toHuman();227  }228229  public static extractEvents(records: ITransactionResult): IEvent[] {230    const parsedEvents: IEvent[] = [];231232    records.result.events.forEach((record) => {233      const {event, phase} = record;234      const types = (event as any).typeDef;235236      const eventData: IEvent = {237        section: event.section.toString(),238        method: event.method.toString(),239        index: this.extractIndex(event.index),240        data: [],241        phase: phase.toJSON(),242      };243244      event.data.forEach((val: any, index: number) => {245        eventData.data.push(this.extractData(val, types[index]));246      });247248      parsedEvents.push(eventData);249    });250251    return parsedEvents;252  }253}254255class ChainHelperBase {256  transactionStatus = UniqueUtil.transactionStatus;257  chainLogType = UniqueUtil.chainLogType;258  util: typeof UniqueUtil;259  eventHelper: typeof UniqueEventHelper;260  logger: ILogger;261  api: ApiPromise | null;262  forcedNetwork: TUniqueNetworks | null;263  network: TUniqueNetworks | null;264  chainLog: IUniqueHelperLog[];265266  constructor(logger?: ILogger) {267    this.util = UniqueUtil;268    this.eventHelper = UniqueEventHelper;269    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();270    this.logger = logger;271    this.api = null;272    this.forcedNetwork = null;273    this.network = null;274    this.chainLog = [];275  }276277  clearChainLog(): void {278    this.chainLog = [];279  }280281  forceNetwork(value: TUniqueNetworks): void {282    this.forcedNetwork = value;283  }284285  async connect(wsEndpoint: string, listeners?: IApiListeners) {286    if (this.api !== null) throw Error('Already connected');287    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);288    this.api = api;289    this.network = network;290  }291292  async disconnect() {293    if (this.api === null) return;294    await this.api.disconnect();295    this.api = null;296    this.network = null;297  }298299  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {300    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;301    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;302    return 'opal';303  }304305  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {306    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});307    await api.isReady;308309    const network = await this.detectNetwork(api);310311    await api.disconnect();312313    return network;314  }315316  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{317    api: ApiPromise;318    network: TUniqueNetworks;319  }> {320    if(typeof network === 'undefined' || network === null) network = 'opal';321    const supportedRPC = {322      opal: {323        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,324      },325      quartz: {326        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,327      },328      unique: {329        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,330      },331    };332    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);333    const rpc = supportedRPC[network];334335    // TODO: investigate how to replace rpc in runtime336    // api._rpcCore.addUserInterfaces(rpc);337338    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});339340    await api.isReadyOrError;341342    if (typeof listeners === 'undefined') listeners = {};343    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {344      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;345      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);346    }347348    return {api, network};349  }350351  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {352    const {events, status} = data;353    if (status.isReady) {354      return this.transactionStatus.NOT_READY;355    }356    if (status.isBroadcast) {357      return this.transactionStatus.NOT_READY;358    }359    if (status.isInBlock || status.isFinalized) {360      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');361      if (errors.length > 0) {362        return this.transactionStatus.FAIL;363      }364      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {365        return this.transactionStatus.SUCCESS;366      }367    }368369    return this.transactionStatus.FAIL;370  }371372  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {373    const sign = (callback: any) => {374      if(options !== null) return transaction.signAndSend(sender, options, callback);375      return transaction.signAndSend(sender, callback);376    };377    // eslint-disable-next-line no-async-promise-executor378    return new Promise(async (resolve, reject) => {379      try {380        const unsub = await sign((result: any) => {381          const status = this.getTransactionStatus(result);382383          if (status === this.transactionStatus.SUCCESS) {384            this.logger.log(`${label} successful`);385            unsub();386            resolve({result, status});387          } else if (status === this.transactionStatus.FAIL) {388            let moduleError = null;389390            if (result.hasOwnProperty('dispatchError')) {391              const dispatchError = result['dispatchError'];392393              if (dispatchError) {394                if (dispatchError.isModule) {395                  const modErr = dispatchError.asModule;396                  const errorMeta = dispatchError.registry.findMetaError(modErr);397398                  moduleError = `${errorMeta.section}.${errorMeta.name}`;399                } else {400                  moduleError = dispatchError.toHuman();401                }402              } else {403                this.logger.log(result, this.logger.level.ERROR);404              }405            }406407            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);408            unsub();409            reject({status, moduleError, result});410          }411        });412      } catch (e) {413        this.logger.log(e, this.logger.level.ERROR);414        reject(e);415      }416    });417  }418419  constructApiCall(apiCall: string, params: any[]) {420    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);421    let call = this.api as any;422    for(const part of apiCall.slice(4).split('.')) {423      call = call[part];424    }425    return call(...params);426  }427428  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {429    if(this.api === null) throw Error('API not initialized');430    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);431432    const startTime = (new Date()).getTime();433    let result: ITransactionResult;434    let events: IEvent[] = [];435    try {436      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;437      events = this.eventHelper.extractEvents(result);438    }439    catch(e) {440      if(!(e as object).hasOwnProperty('status')) throw e;441      result = e as ITransactionResult;442    }443444    const endTime = (new Date()).getTime();445446    const log = {447      executedAt: endTime,448      executionTime: endTime - startTime,449      type: this.chainLogType.EXTRINSIC,450      status: result.status,451      call: extrinsic,452      signer: this.getSignerAddress(sender),453      params,454    } as IUniqueHelperLog;455456    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;457    if(events.length > 0) log.events = events;458459    this.chainLog.push(log);460461    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);462    return result;463  }464465  async callRpc(rpc: string, params?: any[]) {466    if(typeof params === 'undefined') params = [];467    if(this.api === null) throw Error('API not initialized');468    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);469470    const startTime = (new Date()).getTime();471    let result;472    let error = null;473    const log = {474      type: this.chainLogType.RPC,475      call: rpc,476      params,477    } as IUniqueHelperLog;478479    try {480      result = await this.constructApiCall(rpc, params);481    }482    catch(e) {483      error = e;484    }485486    const endTime = (new Date()).getTime();487488    log.executedAt = endTime;489    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';490    log.executionTime = endTime - startTime;491492    this.chainLog.push(log);493494    if(error !== null) throw error;495496    return result;497  }498499  getSignerAddress(signer: IKeyringPair | string): string {500    if(typeof signer === 'string') return signer;501    return signer.address;502  }503504  fetchAllPalletNames(): string[] {505    if(this.api === null) throw Error('API not initialized');506    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());507  }508509  fetchMissingPalletNames(requiredPallets: string[]): string[] {510    const palletNames = this.fetchAllPalletNames();511    return requiredPallets.filter(p => !palletNames.includes(p));512  }513}514515516class HelperGroup {517  helper: UniqueHelper;518519  constructor(uniqueHelper: UniqueHelper) {520    this.helper = uniqueHelper;521  }522}523524525class CollectionGroup extends HelperGroup {526  /**527 * Get number of blocks when sponsored transaction is available.528 *529 * @param collectionId ID of collection530 * @param tokenId ID of token531 * @param addressObj address for which the sponsorship is checked532 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});533 * @returns number of blocks or null if sponsorship hasn't been set534 */535  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {536    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();537  }538539  /**540   * Get the number of created collections.541   *542   * @returns number of created collections543   */544  async getTotalCount(): Promise<number> {545    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();546  }547548  /**549   * Get information about the collection with additional data,550   * including the number of tokens it contains, its administrators,551   * the normalized address of the collection's owner, and decoded name and description.552   *553   * @param collectionId ID of collection554   * @example await getData(2)555   * @returns collection information object556   */557  async getData(collectionId: number): Promise<{558    id: number;559    name: string;560    description: string;561    tokensCount: number;562    admins: ICrossAccountId[];563    normalizedOwner: TSubstrateAccount;564    raw: any565  } | null> {566    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);567    const humanCollection = collection.toHuman(), collectionData = {568      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],569      raw: humanCollection,570    } as any, jsonCollection = collection.toJSON();571    if (humanCollection === null) return null;572    collectionData.raw.limits = jsonCollection.limits;573    collectionData.raw.permissions = jsonCollection.permissions;574    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);575    for (const key of ['name', 'description']) {576      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);577    }578579    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))580      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)581      : 0;582    collectionData.admins = await this.getAdmins(collectionId);583584    return collectionData;585  }586587  /**588   * Get the addresses of the collection's administrators, optionally normalized.589   *590   * @param collectionId ID of collection591   * @param normalize whether to normalize the addresses to the default ss58 format592   * @example await getAdmins(1)593   * @returns array of administrators594   */595  async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {596    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();597598    return normalize599      ? admins.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))600      : admins;601  }602603  /**604   * Get the addresses added to the collection allow-list, optionally normalized.605   * @param collectionId ID of collection606   * @param normalize whether to normalize the addresses to the default ss58 format607   * @example await getAllowList(1)608   * @returns array of allow-listed addresses609   */610  async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {611    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612    return normalize613      ? allowListed.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))614      : allowListed;615  }616617  /**618   * Get the effective limits of the collection instead of null for default values619   *620   * @param collectionId ID of collection621   * @example await getEffectiveLimits(2)622   * @returns object of collection limits623   */624  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {625    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();626  }627628  /**629   * Burns the collection if the signer has sufficient permissions and collection is empty.630   *631   * @param signer keyring of signer632   * @param collectionId ID of collection633   * @example await helper.collection.burn(aliceKeyring, 3);634   * @returns ```true``` if extrinsic success, otherwise ```false```635   */636  async burn(signer: TSigner, collectionId: number): Promise<boolean> {637    const result = await this.helper.executeExtrinsic(638      signer,639      'api.tx.unique.destroyCollection', [collectionId],640      true,641    );642643    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');644  }645646  /**647   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.648   *649   * @param signer keyring of signer650   * @param collectionId ID of collection651   * @param sponsorAddress Sponsor substrate address652   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")653   * @returns ```true``` if extrinsic success, otherwise ```false```654   */655  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {656    const result = await this.helper.executeExtrinsic(657      signer,658      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],659      true,660    );661662    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');663  }664665  /**666   * Confirms consent to sponsor the collection on behalf of the signer.667   *668   * @param signer keyring of signer669   * @param collectionId ID of collection670   * @example confirmSponsorship(aliceKeyring, 10)671   * @returns ```true``` if extrinsic success, otherwise ```false```672   */673  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {674    const result = await this.helper.executeExtrinsic(675      signer,676      'api.tx.unique.confirmSponsorship', [collectionId],677      true,678    );679680    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');681  }682683  /**684   * Removes the sponsor of a collection, regardless if it consented or not.685   *686   * @param signer keyring of signer687   * @param collectionId ID of collection688   * @example removeSponsor(aliceKeyring, 10)689   * @returns ```true``` if extrinsic success, otherwise ```false```690   */691  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {692    const result = await this.helper.executeExtrinsic(693      signer,694      'api.tx.unique.removeCollectionSponsor', [collectionId],695      true,696    );697698    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');699  }700701  /**702   * Sets the limits of the collection. At least one limit must be specified for a correct call.703   *704   * @param signer keyring of signer705   * @param collectionId ID of collection706   * @param limits collection limits object707   * @example708   * await setLimits(709   *   aliceKeyring,710   *   10,711   *   {712   *     sponsorTransferTimeout: 0,713   *     ownerCanDestroy: false714   *   }715   * )716   * @returns ```true``` if extrinsic success, otherwise ```false```717   */718  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {719    const result = await this.helper.executeExtrinsic(720      signer,721      'api.tx.unique.setCollectionLimits', [collectionId, limits],722      true,723    );724725    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');726  }727728  /**729   * Changes the owner of the collection to the new Substrate address.730   *731   * @param signer keyring of signer732   * @param collectionId ID of collection733   * @param ownerAddress substrate address of new owner734   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")735   * @returns ```true``` if extrinsic success, otherwise ```false```736   */737  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {738    const result = await this.helper.executeExtrinsic(739      signer,740      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],741      true,742    );743744    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');745  }746747  /**748   * Adds a collection administrator.749   *750   * @param signer keyring of signer751   * @param collectionId ID of collection752   * @param adminAddressObj Administrator address (substrate or ethereum)753   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})754   * @returns ```true``` if extrinsic success, otherwise ```false```755   */756  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {757    const result = await this.helper.executeExtrinsic(758      signer,759      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],760      true,761    );762763    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');764  }765766  /**767   * Removes a collection administrator.768   *769   * @param signer keyring of signer770   * @param collectionId ID of collection771   * @param adminAddressObj Administrator address (substrate or ethereum)772   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})773   * @returns ```true``` if extrinsic success, otherwise ```false```774   */775  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {776    const result = await this.helper.executeExtrinsic(777      signer,778      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],779      true,780    );781782    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');783  }784785  /**786   * Check if user is in allow list.787   * 788   * @param collectionId ID of collection789   * @param user Account to check790   * @example await getAdmins(1)791   * @returns is user in allow list792   */793  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {794    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();795  }796797  /**798   * Adds an address to allow list799   * @param signer keyring of signer800   * @param collectionId ID of collection801   * @param addressObj address to add to the allow list802   * @returns ```true``` if extrinsic success, otherwise ```false```803   */804  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {805    const result = await this.helper.executeExtrinsic(806      signer,807      'api.tx.unique.addToAllowList', [collectionId, addressObj],808      true,809    );810811    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');812  }813814  /**815   * Removes an address from allow list816   *817   * @param signer keyring of signer818   * @param collectionId ID of collection819   * @param addressObj address to remove from the allow list820   * @returns ```true``` if extrinsic success, otherwise ```false```821   */822  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {823    const result = await this.helper.executeExtrinsic(824      signer,825      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],826      true,827    );828829    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');830  }831832  /**833   * Sets onchain permissions for selected collection.834   *835   * @param signer keyring of signer836   * @param collectionId ID of collection837   * @param permissions collection permissions object838   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});839   * @returns ```true``` if extrinsic success, otherwise ```false```840   */841  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {842    const result = await this.helper.executeExtrinsic(843      signer,844      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],845      true,846    );847848    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');849  }850851  /**852   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.853   *854   * @param signer keyring of signer855   * @param collectionId ID of collection856   * @param permissions nesting permissions object857   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});858   * @returns ```true``` if extrinsic success, otherwise ```false```859   */860  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {861    return await this.setPermissions(signer, collectionId, {nesting: permissions});862  }863864  /**865   * Disables nesting for selected collection.866   *867   * @param signer keyring of signer868   * @param collectionId ID of collection869   * @example disableNesting(aliceKeyring, 10);870   * @returns ```true``` if extrinsic success, otherwise ```false```871   */872  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {873    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});874  }875876  /**877   * Sets onchain properties to the collection.878   *879   * @param signer keyring of signer880   * @param collectionId ID of collection881   * @param properties array of property objects882   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);883   * @returns ```true``` if extrinsic success, otherwise ```false```884   */885  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {886    const result = await this.helper.executeExtrinsic(887      signer,888      'api.tx.unique.setCollectionProperties', [collectionId, properties],889      true,890    );891892    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');893  }894895  /**896   * Get collection properties.897   * 898   * @param collectionId ID of collection899   * @param propertyKeys optionally filter the returned properties to only these keys900   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);901   * @returns array of key-value pairs902   */903  async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {904    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();905  }906907  /**908   * Deletes onchain properties from the collection.909   *910   * @param signer keyring of signer911   * @param collectionId ID of collection912   * @param propertyKeys array of property keys to delete913   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);914   * @returns ```true``` if extrinsic success, otherwise ```false```915   */916  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {917    const result = await this.helper.executeExtrinsic(918      signer,919      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],920      true,921    );922923    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');924  }925926  /**927   * Changes the owner of the token.928   *929   * @param signer keyring of signer930   * @param collectionId ID of collection931   * @param tokenId ID of token932   * @param addressObj address of a new owner933   * @param amount amount of tokens to be transfered. For NFT must be set to 1n934   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})935   * @returns true if the token success, otherwise false936   */937  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {938    const result = await this.helper.executeExtrinsic(939      signer,940      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],941      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,942    );943944    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);945  }946947  /**948   *949   * Change ownership of a token(s) on behalf of the owner.950   *951   * @param signer keyring of signer952   * @param collectionId ID of collection953   * @param tokenId ID of token954   * @param fromAddressObj address on behalf of which the token will be sent955   * @param toAddressObj new token owner956   * @param amount amount of tokens to be transfered. For NFT must be set to 1n957   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})958   * @returns true if the token success, otherwise false959   */960  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {961    const result = await this.helper.executeExtrinsic(962      signer,963      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],964      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,965    );966    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);967  }968969  /**970   *971   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.972   *973   * @param signer keyring of signer974   * @param collectionId ID of collection975   * @param tokenId ID of token976   * @param amount amount of tokens to be burned. For NFT must be set to 1n977   * @example burnToken(aliceKeyring, 10, 5);978   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```979   */980  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{981    success: boolean,982    token: number | null983  }> {984    const burnResult = await this.helper.executeExtrinsic(985      signer,986      'api.tx.unique.burnItem', [collectionId, tokenId, amount],987      true, // `Unable to burn token for ${label}`,988    );989    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);990    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');991    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};992  }993994  /**995   * Destroys a concrete instance of NFT on behalf of the owner996   *997   * @param signer keyring of signer998   * @param collectionId ID of collection999   * @param tokenId ID of token1000   * @param fromAddressObj address on behalf of which the token will be burnt1001   * @param amount amount of tokens to be burned. For NFT must be set to 1n1002   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1003   * @returns ```true``` if extrinsic success, otherwise ```false```1004   */1005  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1006    const burnResult = await this.helper.executeExtrinsic(1007      signer,1008      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1009      true, // `Unable to burn token from for ${label}`,1010    );1011    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1012    return burnedTokens.success && burnedTokens.tokens.length > 0;1013  }10141015  /**1016   * Set, change, or remove approved address to transfer the ownership of the NFT.1017   *1018   * @param signer keyring of signer1019   * @param collectionId ID of collection1020   * @param tokenId ID of token1021   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1022   * @param amount amount of token to be approved. For NFT must be set to 1n1023   * @returns ```true``` if extrinsic success, otherwise ```false```1024   */1025  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1026    const approveResult = await this.helper.executeExtrinsic(1027      signer,1028      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1029      true, // `Unable to approve token for ${label}`,1030    );10311032    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1033  }10341035  /**1036   * Get the amount of token pieces approved to transfer or burn. Normally 0.1037   *1038   * @param collectionId ID of collection1039   * @param tokenId ID of token1040   * @param toAccountObj address which is approved to use token pieces1041   * @param fromAccountObj address which may have allowed the use of its owned tokens1042   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1043   * @returns number of approved to transfer pieces1044   */1045  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1046    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1047  }10481049  /**1050   * Get the last created token ID in a collection1051   *1052   * @param collectionId ID of collection1053   * @example getLastTokenId(10);1054   * @returns id of the last created token1055   */1056  async getLastTokenId(collectionId: number): Promise<number> {1057    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1058  }10591060  /**1061   * Check if token exists1062   *1063   * @param collectionId ID of collection1064   * @param tokenId ID of token1065   * @example isTokenExists(10, 20);1066   * @returns true if the token exists, otherwise false1067   */1068  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1069    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1070  }1071}10721073class NFTnRFT extends CollectionGroup {1074  /**1075   * Get tokens owned by account1076   *1077   * @param collectionId ID of collection1078   * @param addressObj tokens owner1079   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1080   * @returns array of token ids owned by account1081   */1082  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1083    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1084  }10851086  /**1087   * Get token data1088   *1089   * @param collectionId ID of collection1090   * @param tokenId ID of token1091   * @param propertyKeys optionally filter the token properties to only these keys1092   * @param blockHashAt optionally query the data at some block with this hash1093   * @example getToken(10, 5);1094   * @returns human readable token data1095   */1096  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1097    properties: IProperty[];1098    owner: ICrossAccountId;1099    normalizedOwner: ICrossAccountId;1100  }| null> {1101    let tokenData;1102    if(typeof blockHashAt === 'undefined') {1103      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1104    }1105    else {1106      if(propertyKeys.length == 0) {1107        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1108        if(!collection) return null;1109        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1110      }1111      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1112    }1113    tokenData = tokenData.toHuman();1114    if (tokenData === null || tokenData.owner === null) return null;1115    const owner = {} as any;1116    for (const key of Object.keys(tokenData.owner)) {1117      owner[key.toLocaleLowerCase()] = this.helper.address.normalizeCrossAccountIfSubstrate(tokenData.owner[key]);1118    }1119    tokenData.normalizedOwner = crossAccountIdFromLower(owner);1120    return tokenData;1121  }11221123  /**1124   * Set permissions to change token properties1125   *1126   * @param signer keyring of signer1127   * @param collectionId ID of collection1128   * @param permissions permissions to change a property by the collection admin or token owner1129   * @example setTokenPropertyPermissions(1130   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1131   * )1132   * @returns true if extrinsic success otherwise false1133   */1134  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1135    const result = await this.helper.executeExtrinsic(1136      signer,1137      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1138      true,1139    );11401141    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1142  }11431144  /**1145   * Get token property permissions.1146   * 1147   * @param collectionId ID of collection1148   * @param propertyKeys optionally filter the returned property permissions to only these keys1149   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1150   * @returns array of key-permission pairs1151   */1152  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1153    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1154  }11551156  /**1157   * Set token properties1158   *1159   * @param signer keyring of signer1160   * @param collectionId ID of collection1161   * @param tokenId ID of token1162   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1163   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1164   * @returns ```true``` if extrinsic success, otherwise ```false```1165   */1166  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1167    const result = await this.helper.executeExtrinsic(1168      signer,1169      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1170      true,1171    );11721173    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1174  }11751176  /**1177   * Get properties, metadata assigned to a token.1178   * 1179   * @param collectionId ID of collection1180   * @param tokenId ID of token1181   * @param propertyKeys optionally filter the returned properties to only these keys1182   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1183   * @returns array of key-value pairs1184   */1185  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1186    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1187  }11881189  /**1190   * Delete the provided properties of a token1191   * @param signer keyring of signer1192   * @param collectionId ID of collection1193   * @param tokenId ID of token1194   * @param propertyKeys property keys to be deleted1195   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1196   * @returns ```true``` if extrinsic success, otherwise ```false```1197   */1198  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1199    const result = await this.helper.executeExtrinsic(1200      signer,1201      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1202      true,1203    );12041205    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1206  }12071208  /**1209   * Mint new collection1210   *1211   * @param signer keyring of signer1212   * @param collectionOptions basic collection options and properties1213   * @param mode NFT or RFT type of a collection1214   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1215   * @returns object of the created collection1216   */1217  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1218    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1219    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1220    for (const key of ['name', 'description', 'tokenPrefix']) {1221      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);1222    }1223    const creationResult = await this.helper.executeExtrinsic(1224      signer,1225      'api.tx.unique.createCollectionEx', [collectionOptions],1226      true, // errorLabel,1227    );1228    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1229  }12301231  getCollectionObject(_collectionId: number): any {1232    return null;1233  }12341235  getTokenObject(_collectionId: number, _tokenId: number): any {1236    return null;1237  }1238}123912401241class NFTGroup extends NFTnRFT {1242  /**1243   * Get collection object1244   * @param collectionId ID of collection1245   * @example getCollectionObject(2);1246   * @returns instance of UniqueNFTCollection1247   */1248  getCollectionObject(collectionId: number): UniqueNFTCollection {1249    return new UniqueNFTCollection(collectionId, this.helper);1250  }12511252  /**1253   * Get token object1254   * @param collectionId ID of collection1255   * @param tokenId ID of token1256   * @example getTokenObject(10, 5);1257   * @returns instance of UniqueNFTToken1258   */1259  getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1260    return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1261  }12621263  /**1264   * Get token's owner1265   * @param collectionId ID of collection1266   * @param tokenId ID of token1267   * @param blockHashAt optionally query the data at the block with this hash1268   * @example getTokenOwner(10, 5);1269   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1270   */1271  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1272    let owner;1273    if (typeof blockHashAt === 'undefined') {1274      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1275    } else {1276      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1277    }1278    return crossAccountIdFromLower(owner.toJSON());1279  }12801281  /**1282   * Is token approved to transfer1283   * @param collectionId ID of collection1284   * @param tokenId ID of token1285   * @param toAccountObj address to be approved1286   * @returns ```true``` if extrinsic success, otherwise ```false```1287   */1288  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1289    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1290  }12911292  /**1293   * Changes the owner of the token.1294   *1295   * @param signer keyring of signer1296   * @param collectionId ID of collection1297   * @param tokenId ID of token1298   * @param addressObj address of a new owner1299   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1300   * @returns ```true``` if extrinsic success, otherwise ```false```1301   */1302  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1303    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1304  }13051306  /**1307   *1308   * Change ownership of a NFT on behalf of the owner.1309   *1310   * @param signer keyring of signer1311   * @param collectionId ID of collection1312   * @param tokenId ID of token1313   * @param fromAddressObj address on behalf of which the token will be sent1314   * @param toAddressObj new token owner1315   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1316   * @returns ```true``` if extrinsic success, otherwise ```false```1317   */1318  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1319    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1320  }13211322  /**1323   * Recursively find the address that owns the token1324   * @param collectionId ID of collection1325   * @param tokenId ID of token1326   * @param blockHashAt1327   * @example getTokenTopmostOwner(10, 5);1328   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1329   */1330  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1331    let owner;1332    if (typeof blockHashAt === 'undefined') {1333      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1334    } else {1335      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1336    }13371338    if (owner === null) return null;13391340    return owner.toHuman();1341  }13421343  /**1344   * Get tokens nested in the provided token1345   * @param collectionId ID of collection1346   * @param tokenId ID of token1347   * @param blockHashAt optionally query the data at the block with this hash1348   * @example getTokenChildren(10, 5);1349   * @returns tokens whose depth of nesting is <= 51350   */1351  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1352    let children;1353    if(typeof blockHashAt === 'undefined') {1354      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1355    } else {1356      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1357    }13581359    return children.toJSON().map((x: any) => {1360      return {collectionId: x.collection, tokenId: x.token};1361    });1362  }13631364  /**1365   * Nest one token into another1366   * @param signer keyring of signer1367   * @param tokenObj token to be nested1368   * @param rootTokenObj token to be parent1369   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1370   * @returns ```true``` if extrinsic success, otherwise ```false```1371   */1372  async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1373    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1374    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1375    if(!result) {1376      throw Error('Unable to nest token!');1377    }1378    return result;1379  }13801381  /**1382   * Remove token from nested state1383   * @param signer keyring of signer1384   * @param tokenObj token to unnest1385   * @param rootTokenObj parent of a token1386   * @param toAddressObj address of a new token owner1387   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1388   * @returns ```true``` if extrinsic success, otherwise ```false```1389   */1390  async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1391    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1392    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1393    if(!result) {1394      throw Error('Unable to unnest token!');1395    }1396    return result;1397  }13981399  /**1400   * Mint new collection1401   * @param signer keyring of signer1402   * @param collectionOptions Collection options1403   * @example1404   * mintCollection(aliceKeyring, {1405   *   name: 'New',1406   *   description: 'New collection',1407   *   tokenPrefix: 'NEW',1408   * })1409   * @returns object of the created collection1410   */1411  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1412    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1413  }14141415  /**1416   * Mint new token1417   * @param signer keyring of signer1418   * @param data token data1419   * @returns created token object1420   */1421  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1422    const creationResult = await this.helper.executeExtrinsic(1423      signer,1424      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1425        nft: {1426          properties: data.properties,1427        },1428      }],1429      true,1430    );1431    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1432    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1433    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1434    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1435  }14361437  /**1438   * Mint multiple NFT tokens1439   * @param signer keyring of signer1440   * @param collectionId ID of collection1441   * @param tokens array of tokens with owner and properties1442   * @example1443   * mintMultipleTokens(aliceKeyring, 10, [{1444   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1445   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1446   *   },{1447   *     owner: {Ethereum: "0x9F0583DbB855d..."},1448   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1449   * }]);1450   * @returns ```true``` if extrinsic success, otherwise ```false```1451   */1452  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1453    const creationResult = await this.helper.executeExtrinsic(1454      signer,1455      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1456      true,1457    );1458    const collection = this.getCollectionObject(collectionId);1459    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1460  }14611462  /**1463   * Mint multiple NFT tokens with one owner1464   * @param signer keyring of signer1465   * @param collectionId ID of collection1466   * @param owner tokens owner1467   * @param tokens array of tokens with owner and properties1468   * @example1469   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1470   *   properties: [{1471   *   key: "gender",1472   *   value: "female",1473   *  },{1474   *   key: "age",1475   *   value: "33",1476   *  }],1477   * }]);1478   * @returns array of newly created tokens1479   */1480  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1481    const rawTokens = [];1482    for (const token of tokens) {1483      const raw = {NFT: {properties: token.properties}};1484      rawTokens.push(raw);1485    }1486    const creationResult = await this.helper.executeExtrinsic(1487      signer,1488      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1489      true,1490    );1491    const collection = this.getCollectionObject(collectionId);1492    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1493  }14941495  /**1496   * Set, change, or remove approved address to transfer the ownership of the NFT.1497   *1498   * @param signer keyring of signer1499   * @param collectionId ID of collection1500   * @param tokenId ID of token1501   * @param toAddressObj address to approve1502   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1503   * @returns ```true``` if extrinsic success, otherwise ```false```1504   */1505  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1506    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1507  }1508}150915101511class RFTGroup extends NFTnRFT {1512  /**1513   * Get collection object1514   * @param collectionId ID of collection1515   * @example getCollectionObject(2);1516   * @returns instance of UniqueRFTCollection1517   */1518  getCollectionObject(collectionId: number): UniqueRFTCollection {1519    return new UniqueRFTCollection(collectionId, this.helper);1520  }15211522  /**1523   * Get token object1524   * @param collectionId ID of collection1525   * @param tokenId ID of token1526   * @example getTokenObject(10, 5);1527   * @returns instance of UniqueNFTToken1528   */1529  getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1530    return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1531  }15321533  /**1534   * Get top 10 token owners with the largest number of pieces1535   * @param collectionId ID of collection1536   * @param tokenId ID of token1537   * @example getTokenTop10Owners(10, 5);1538   * @returns array of top 10 owners1539   */1540  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1541    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1542  }15431544  /**1545   * Get number of pieces owned by address1546   * @param collectionId ID of collection1547   * @param tokenId ID of token1548   * @param addressObj address token owner1549   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1550   * @returns number of pieces ownerd by address1551   */1552  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1553    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1554  }15551556  /**1557   * Transfer pieces of token to another address1558   * @param signer keyring of signer1559   * @param collectionId ID of collection1560   * @param tokenId ID of token1561   * @param addressObj address of a new owner1562   * @param amount number of pieces to be transfered1563   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1564   * @returns ```true``` if extrinsic success, otherwise ```false```1565   */1566  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1567    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1568  }15691570  /**1571   * Change ownership of some pieces of RFT on behalf of the owner.1572   * @param signer keyring of signer1573   * @param collectionId ID of collection1574   * @param tokenId ID of token1575   * @param fromAddressObj address on behalf of which the token will be sent1576   * @param toAddressObj new token owner1577   * @param amount number of pieces to be transfered1578   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1579   * @returns ```true``` if extrinsic success, otherwise ```false```1580   */1581  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1582    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1583  }15841585  /**1586   * Mint new collection1587   * @param signer keyring of signer1588   * @param collectionOptions Collection options1589   * @example1590   * mintCollection(aliceKeyring, {1591   *   name: 'New',1592   *   description: 'New collection',1593   *   tokenPrefix: 'NEW',1594   * })1595   * @returns object of the created collection1596   */1597  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1598    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1599  }16001601  /**1602   * Mint new token1603   * @param signer keyring of signer1604   * @param data token data1605   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1606   * @returns created token object1607   */1608  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1609    const creationResult = await this.helper.executeExtrinsic(1610      signer,1611      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1612        refungible: {1613          pieces: data.pieces,1614          properties: data.properties,1615        },1616      }],1617      true,1618    );1619    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1620    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1621    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1622    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1623  }16241625  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1626    throw Error('Not implemented');1627    const creationResult = await this.helper.executeExtrinsic(1628      signer,1629      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1630      true, // `Unable to mint RFT tokens for ${label}`,1631    );1632    const collection = this.getCollectionObject(collectionId);1633    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1634  }16351636  /**1637   * Mint multiple RFT tokens with one owner1638   * @param signer keyring of signer1639   * @param collectionId ID of collection1640   * @param owner tokens owner1641   * @param tokens array of tokens with properties and pieces1642   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1643   * @returns array of newly created RFT tokens1644   */1645  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1646    const rawTokens = [];1647    for (const token of tokens) {1648      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1649      rawTokens.push(raw);1650    }1651    const creationResult = await this.helper.executeExtrinsic(1652      signer,1653      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1654      true,1655    );1656    const collection = this.getCollectionObject(collectionId);1657    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1658  }16591660  /**1661   * Destroys a concrete instance of RFT.1662   * @param signer keyring of signer1663   * @param collectionId ID of collection1664   * @param tokenId ID of token1665   * @param amount number of pieces to be burnt1666   * @example burnToken(aliceKeyring, 10, 5);1667   * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1668   */1669  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1670    return await super.burnToken(signer, collectionId, tokenId, amount);1671  }16721673  /**1674   * Destroys a concrete instance of RFT on behalf of the owner.1675   * @param signer keyring of signer1676   * @param collectionId ID of collection1677   * @param tokenId ID of token1678   * @param fromAddressObj address on behalf of which the token will be burnt1679   * @param amount number of pieces to be burnt1680   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1681   * @returns ```true``` if extrinsic success, otherwise ```false```1682   */1683  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1684    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1685  }16861687  /**1688   * Set, change, or remove approved address to transfer the ownership of the RFT.1689   *1690   * @param signer keyring of signer1691   * @param collectionId ID of collection1692   * @param tokenId ID of token1693   * @param toAddressObj address to approve1694   * @param amount number of pieces to be approved1695   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1696   * @returns true if the token success, otherwise false1697   */1698  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1699    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1700  }17011702  /**1703   * Get total number of pieces1704   * @param collectionId ID of collection1705   * @param tokenId ID of token1706   * @example getTokenTotalPieces(10, 5);1707   * @returns number of pieces1708   */1709  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1710    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1711  }17121713  /**1714   * Change number of token pieces. Signer must be the owner of all token pieces.1715   * @param signer keyring of signer1716   * @param collectionId ID of collection1717   * @param tokenId ID of token1718   * @param amount new number of pieces1719   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1720   * @returns true if the repartion was success, otherwise false1721   */1722  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1723    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1724    const repartitionResult = await this.helper.executeExtrinsic(1725      signer,1726      'api.tx.unique.repartition', [collectionId, tokenId, amount],1727      true,1728    );1729    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1730    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1731  }1732}173317341735class FTGroup extends CollectionGroup {1736  /**1737   * Get collection object1738   * @param collectionId ID of collection1739   * @example getCollectionObject(2);1740   * @returns instance of UniqueFTCollection1741   */1742  getCollectionObject(collectionId: number): UniqueFTCollection {1743    return new UniqueFTCollection(collectionId, this.helper);1744  }17451746  /**1747   * Mint new fungible collection1748   * @param signer keyring of signer1749   * @param collectionOptions Collection options1750   * @param decimalPoints number of token decimals1751   * @example1752   * mintCollection(aliceKeyring, {1753   *   name: 'New',1754   *   description: 'New collection',1755   *   tokenPrefix: 'NEW',1756   * }, 18)1757   * @returns newly created fungible collection1758   */1759  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1760    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1761    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1762    collectionOptions.mode = {fungible: decimalPoints};1763    for (const key of ['name', 'description', 'tokenPrefix']) {1764      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);1765    }1766    const creationResult = await this.helper.executeExtrinsic(1767      signer,1768      'api.tx.unique.createCollectionEx', [collectionOptions],1769      true,1770    );1771    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1772  }17731774  /**1775   * Mint tokens1776   * @param signer keyring of signer1777   * @param collectionId ID of collection1778   * @param owner address owner of new tokens1779   * @param amount amount of tokens to be meanted1780   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1781   * @returns ```true``` if extrinsic success, otherwise ```false```1782   */1783  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1784    const creationResult = await this.helper.executeExtrinsic(1785      signer,1786      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1787        fungible: {1788          value: amount,1789        },1790      }],1791      true, // `Unable to mint fungible tokens for ${label}`,1792    );1793    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1794  }17951796  /**1797   * Mint multiple Fungible tokens with one owner1798   * @param signer keyring of signer1799   * @param collectionId ID of collection1800   * @param owner tokens owner1801   * @param tokens array of tokens with properties and pieces1802   * @returns ```true``` if extrinsic success, otherwise ```false```1803   */1804  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1805    const rawTokens = [];1806    for (const token of tokens) {1807      const raw = {Fungible: {Value: token.value}};1808      rawTokens.push(raw);1809    }1810    const creationResult = await this.helper.executeExtrinsic(1811      signer,1812      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1813      true,1814    );1815    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1816  }18171818  /**1819   * Get the top 10 owners with the largest balance for the Fungible collection1820   * @param collectionId ID of collection1821   * @example getTop10Owners(10);1822   * @returns array of ```ICrossAccountId```1823   */1824  async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1825    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1826  }18271828  /**1829   * Get account balance1830   * @param collectionId ID of collection1831   * @param addressObj address of owner1832   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1833   * @returns amount of fungible tokens owned by address1834   */1835  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1836    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1837  }18381839  /**1840   * Transfer tokens to address1841   * @param signer keyring of signer1842   * @param collectionId ID of collection1843   * @param toAddressObj address recipient1844   * @param amount amount of tokens to be sent1845   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1846   * @returns ```true``` if extrinsic success, otherwise ```false```1847   */1848  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1849    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1850  }18511852  /**1853   * Transfer some tokens on behalf of the owner.1854   * @param signer keyring of signer1855   * @param collectionId ID of collection1856   * @param fromAddressObj address on behalf of which tokens will be sent1857   * @param toAddressObj address where token to be sent1858   * @param amount number of tokens to be sent1859   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1860   * @returns ```true``` if extrinsic success, otherwise ```false```1861   */1862  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1863    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1864  }18651866  /**1867   * Destroy some amount of tokens1868   * @param signer keyring of signer1869   * @param collectionId ID of collection1870   * @param amount amount of tokens to be destroyed1871   * @example burnTokens(aliceKeyring, 10, 1000n);1872   * @returns ```true``` if extrinsic success, otherwise ```false```1873   */1874  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1875    return (await super.burnToken(signer, collectionId, 0, amount)).success;1876  }18771878  /**1879   * Burn some tokens on behalf of the owner.1880   * @param signer keyring of signer1881   * @param collectionId ID of collection1882   * @param fromAddressObj address on behalf of which tokens will be burnt1883   * @param amount amount of tokens to be burnt1884   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1885   * @returns ```true``` if extrinsic success, otherwise ```false```1886   */1887  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1888    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1889  }18901891  /**1892   * Get total collection supply1893   * @param collectionId1894   * @returns1895   */1896  async getTotalPieces(collectionId: number): Promise<bigint> {1897    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1898  }18991900  /**1901   * Set, change, or remove approved address to transfer tokens.1902   *1903   * @param signer keyring of signer1904   * @param collectionId ID of collection1905   * @param toAddressObj address to be approved1906   * @param amount amount of tokens to be approved1907   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1908   * @returns ```true``` if extrinsic success, otherwise ```false```1909   */1910  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1911    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1912  }19131914  /**1915   * Get amount of fungible tokens approved to transfer1916   * @param collectionId ID of collection1917   * @param fromAddressObj owner of tokens1918   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1919   * @returns number of tokens approved for the transfer1920   */1921  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1922    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1923  }1924}192519261927class ChainGroup extends HelperGroup {1928  /**1929   * Get system properties of a chain1930   * @example getChainProperties();1931   * @returns ss58Format, token decimals, and token symbol1932   */1933  getChainProperties(): IChainProperties {1934    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1935    return {1936      ss58Format: properties.ss58Format.toJSON(),1937      tokenDecimals: properties.tokenDecimals.toJSON(),1938      tokenSymbol: properties.tokenSymbol.toJSON(),1939    };1940  }19411942  /**1943   * Get chain header1944   * @example getLatestBlockNumber();1945   * @returns the number of the last block1946   */1947  async getLatestBlockNumber(): Promise<number> {1948    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1949  }19501951  /**1952   * Get block hash by block number1953   * @param blockNumber number of block1954   * @example getBlockHashByNumber(12345);1955   * @returns hash of a block1956   */1957  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1958    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1959    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1960    return blockHash;1961  }19621963  // TODO add docs1964  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1965    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1966    if (!blockHash) return null;1967    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1968  }19691970  /**1971   * Get account nonce1972   * @param address substrate address1973   * @example getNonce("5GrwvaEF5zXb26Fz...");1974   * @returns number, account's nonce1975   */1976  async getNonce(address: TSubstrateAccount): Promise<number> {1977    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1978  }1979}198019811982class BalanceGroup extends HelperGroup {1983  /**1984   * Representation of the native token in the smallest unit1985   * @example getOneTokenNominal()1986   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1987   */1988  getOneTokenNominal(): bigint {1989    const chainProperties = this.helper.chain.getChainProperties();1990    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1991  }19921993  /**1994   * Get substrate address balance1995   * @param address substrate address1996   * @example getSubstrate("5GrwvaEF5zXb26Fz...")1997   * @returns amount of tokens on address1998   */1999  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2000    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2001  }20022003  /**2004   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2005   * @param address substrate address2006   * @returns2007   */2008  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2009    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2010    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2011  }20122013  /**2014   * Get ethereum address balance2015   * @param address ethereum address2016   * @example getEthereum("0x9F0583DbB855d...")2017   * @returns amount of tokens on address2018   */2019  async getEthereum(address: TEthereumAccount): Promise<bigint> {2020    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2021  }20222023  /**2024   * Transfer tokens to substrate address2025   * @param signer keyring of signer2026   * @param address substrate address of a recipient2027   * @param amount amount of tokens to be transfered2028   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2029   * @returns ```true``` if extrinsic success, otherwise ```false```2030   */2031  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2032    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}`*/);20332034    let transfer = {from: null, to: null, amount: 0n} as any;2035    result.result.events.forEach(({event: {data, method, section}}) => {2036      if ((section === 'balances') && (method === 'Transfer')) {2037        transfer = {2038          from: this.helper.address.normalizeSubstrate(data[0]),2039          to: this.helper.address.normalizeSubstrate(data[1]),2040          amount: BigInt(data[2]),2041        };2042      }2043    });2044    let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2045    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2046    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2047    return isSuccess;2048  }2049}205020512052class AddressGroup extends HelperGroup {2053  /**2054   * Normalizes the address to the specified ss58 format, by default ```42```.2055   * @param address substrate address2056   * @param ss58Format format for address conversion, by default ```42```2057   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2058   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2059   */2060  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2061    return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2062  }20632064  /**2065   * Normalizes the address of an account ONLY if it's Substrate to the specified ss58 format, by default ```42```.2066   * @param account account of either Substrate type or Ethereum, but only Substrate will be changed2067   * @param ss58Format format for address conversion, by default ```42```2068   * @example normalizeCrossAccountIfSubstrate({Substrate: "unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx"}) // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2069   * @returns untouched ethereum account or substrate account converted to normalized (i.e., starting with 5) or specified explicitly representation2070   */2071  normalizeCrossAccountIfSubstrate(account: ICrossAccountId, ss58Format = 42): ICrossAccountId  {2072    return account.Substrate2073      ? {Substrate: this.normalizeSubstrate(account.Substrate, ss58Format)}2074      : account;2075  }20762077  /**2078   * Get address in the connected chain format2079   * @param address substrate address2080   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2081   * @returns address in chain format2082   */2083  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2084    const info = this.helper.chain.getChainProperties();2085    return encodeAddress(decodeAddress(address), info.ss58Format);2086  }20872088  /**2089   * Get substrate mirror of an ethereum address2090   * @param ethAddress ethereum address2091   * @param toChainFormat false for normalized account2092   * @example ethToSubstrate('0x9F0583DbB855d...')2093   * @returns substrate mirror of a provided ethereum address2094   */2095  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2096    if(!toChainFormat) return evmToAddress(ethAddress);2097    const info = this.helper.chain.getChainProperties();2098    return evmToAddress(ethAddress, info.ss58Format);2099  }21002101  /**2102   * Get ethereum mirror of a substrate address2103   * @param subAddress substrate account2104   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2105   * @returns ethereum mirror of a provided substrate address2106   */2107  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2108    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2109  }2110}21112112class StakingGroup extends HelperGroup {2113  /**2114   * Stake tokens for App Promotion2115   * @param signer keyring of signer2116   * @param amountToStake amount of tokens to stake2117   * @param label extra label for log2118   * @returns2119   */2120  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2121    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2122    const stakeResult = await this.helper.executeExtrinsic(2123      signer, 'api.tx.appPromotion.stake',2124      [amountToStake], true,2125    );2126    // TODO extract info from stakeResult2127    return true;2128  }21292130  /**2131   * Unstake tokens for App Promotion2132   * @param signer keyring of signer2133   * @param amountToUnstake amount of tokens to unstake2134   * @param label extra label for log2135   * @returns block number where balances will be unlocked2136   */2137  async unstake(signer: TSigner, label?: string): Promise<number> {2138    if(typeof label === 'undefined') label = `${signer.address}`;2139    const unstakeResult = await this.helper.executeExtrinsic(2140      signer, 'api.tx.appPromotion.unstake',2141      [], true,2142    );2143    // TODO extract block number fron events2144    return 1;2145  }21462147  /**2148   * Get total staked amount for address2149   * @param address substrate or ethereum address2150   * @returns total staked amount2151   */2152  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2153    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2154    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2155  }21562157  /**2158   * Get total staked per block2159   * @param address substrate or ethereum address2160   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2161   */2162  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2163    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2164    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2165      return { 2166        block: block.toBigInt(),2167        amount: amount.toBigInt(),2168      };2169    });2170  }21712172  /**2173   * Get total pending unstake amount for address2174   * @param address substrate or ethereum address2175   * @returns total pending unstake amount2176   */2177  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2178    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2179  }21802181  /**2182   * Get pending unstake amount per block for address2183   * @param address substrate or ethereum address2184   * @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 block2185   */2186  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2187    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2188    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2189      return {2190        block: block.toBigInt(),2191        amount: amount.toBigInt(),2192      };2193    });2194    return result;2195  }2196}21972198export class UniqueHelper extends ChainHelperBase {2199  chain: ChainGroup;2200  balance: BalanceGroup;2201  address: AddressGroup;2202  collection: CollectionGroup;2203  nft: NFTGroup;2204  rft: RFTGroup;2205  ft: FTGroup;2206  staking: StakingGroup;22072208  constructor(logger?: ILogger) {2209    super(logger);2210    this.chain = new ChainGroup(this);2211    this.balance = new BalanceGroup(this);2212    this.address = new AddressGroup(this);2213    this.collection = new CollectionGroup(this);2214    this.nft = new NFTGroup(this);2215    this.rft = new RFTGroup(this);2216    this.ft = new FTGroup(this);2217    this.staking = new StakingGroup(this);2218  }2219}222022212222export class UniqueCollectionBase {2223  helper: UniqueHelper;2224  collectionId: number;22252226  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2227    this.collectionId = collectionId;2228    this.helper = uniqueHelper;2229  }22302231  async getData() {2232    return await this.helper.collection.getData(this.collectionId);2233  }22342235  async getLastTokenId() {2236    return await this.helper.collection.getLastTokenId(this.collectionId);2237  }22382239  async isTokenExists(tokenId: number) {2240    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2241  }22422243  async getAdmins() {2244    return await this.helper.collection.getAdmins(this.collectionId);2245  }22462247  async getAllowList() {2248    return await this.helper.collection.getAllowList(this.collectionId);2249  }22502251  async getEffectiveLimits() {2252    return await this.helper.collection.getEffectiveLimits(this.collectionId);2253  }22542255  async getProperties(propertyKeys: string[] | null = null) {2256    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2257  }22582259  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2260    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2261  }22622263  async confirmSponsorship(signer: TSigner) {2264    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2265  }22662267  async removeSponsor(signer: TSigner) {2268    return await this.helper.collection.removeSponsor(signer, this.collectionId);2269  }22702271  async setLimits(signer: TSigner, limits: ICollectionLimits) {2272    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2273  }22742275  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2276    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2277  }22782279  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2280    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2281  }22822283  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2284    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2285  }22862287  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2288    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2289  }22902291  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2292    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2293  }22942295  async setProperties(signer: TSigner, properties: IProperty[]) {2296    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2297  }22982299  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2300    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2301  }23022303  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2304    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2305  }23062307  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2308    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2309  }23102311  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2312    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2313  }23142315  async disableNesting(signer: TSigner) {2316    return await this.helper.collection.disableNesting(signer, this.collectionId);2317  }23182319  async burn(signer: TSigner) {2320    return await this.helper.collection.burn(signer, this.collectionId);2321  }2322}232323242325export class UniqueNFTCollection extends UniqueCollectionBase {2326  getTokenObject(tokenId: number) {2327    return new UniqueNFTToken(tokenId, this);2328  }23292330  async getTokensByAddress(addressObj: ICrossAccountId) {2331    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2332  }23332334  async getToken(tokenId: number, blockHashAt?: string) {2335    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2336  }23372338  async getTokenOwner(tokenId: number, blockHashAt?: string) {2339    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2340  }23412342  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2343    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2344  }23452346  async getTokenChildren(tokenId: number, blockHashAt?: string) {2347    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2348  }23492350  async getPropertyPermissions(propertyKeys: string[] | null = null) {2351    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2352  }23532354  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2355    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2356  }23572358  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2359    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2360  }23612362  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2363    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2364  }23652366  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2367    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2368  }23692370  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2371    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2372  }23732374  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2375    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2376  }23772378  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2379    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2380  }23812382  async burnToken(signer: TSigner, tokenId: number) {2383    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2384  }23852386  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2387    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2388  }23892390  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2391    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2392  }23932394  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2395    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2396  }23972398  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2399    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2400  }24012402  async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2403    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2404  }24052406  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2407    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2408  }2409}241024112412export class UniqueRFTCollection extends UniqueCollectionBase {2413  getTokenObject(tokenId: number) {2414    return new UniqueRFTToken(tokenId, this);2415  }24162417  async getToken(tokenId: number, blockHashAt?: string) {2418    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2419  }24202421  async getTokensByAddress(addressObj: ICrossAccountId) {2422    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2423  }24242425  async getTop10TokenOwners(tokenId: number) {2426    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2427  }24282429  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2430    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2431  }24322433  async getTokenTotalPieces(tokenId: number) {2434    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2435  }24362437  async getPropertyPermissions(propertyKeys: string[] | null = null) {2438    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2439  }24402441  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2442    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2443  }24442445  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2446    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2447  }24482449  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2450    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2451  }24522453  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2454    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2455  }24562457  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2458    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2459  }24602461  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2462    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2463  }24642465  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2466    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2467  }24682469  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2470    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2471  }24722473  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2474    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2475  }24762477  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {2478    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2479  }24802481  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2482    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2483  }24842485  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2486    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2487  }24882489  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2490    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2491  }2492}249324942495export class UniqueFTCollection extends UniqueCollectionBase {2496  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2497    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2498  }24992500  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2501    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2502  }25032504  async getBalance(addressObj: ICrossAccountId) {2505    return await this.helper.ft.getBalance(this.collectionId, addressObj);2506  }25072508  async getTop10Owners() {2509    return await this.helper.ft.getTop10Owners(this.collectionId);2510  }25112512  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2513    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2514  }25152516  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2517    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2518  }25192520  async burnTokens(signer: TSigner, amount=1n) {2521    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2522  }25232524  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2525    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2526  }25272528  async getTotalPieces() {2529    return await this.helper.ft.getTotalPieces(this.collectionId);2530  }25312532  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2533    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2534  }25352536  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2537    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2538  }2539}254025412542export class UniqueTokenBase implements IToken {2543  collection: UniqueNFTCollection | UniqueRFTCollection;2544  collectionId: number;2545  tokenId: number;25462547  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2548    this.collection = collection;2549    this.collectionId = collection.collectionId;2550    this.tokenId = tokenId;2551  }25522553  async getNextSponsored(addressObj: ICrossAccountId) {2554    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2555  }25562557  async getProperties(propertyKeys: string[] | null = null) {2558    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2559  }25602561  async setProperties(signer: TSigner, properties: IProperty[]) {2562    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2563  }25642565  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2566    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2567  }25682569  nestingAccount() {2570    return this.collection.helper.util.getTokenAccount(this);2571  }2572}257325742575export class UniqueNFTToken extends UniqueTokenBase {2576  collection: UniqueNFTCollection;25772578  constructor(tokenId: number, collection: UniqueNFTCollection) {2579    super(tokenId, collection);2580    this.collection = collection;2581  }25822583  async getData(blockHashAt?: string) {2584    return await this.collection.getToken(this.tokenId, blockHashAt);2585  }25862587  async getOwner(blockHashAt?: string) {2588    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2589  }25902591  async getTopmostOwner(blockHashAt?: string) {2592    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2593  }25942595  async getChildren(blockHashAt?: string) {2596    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2597  }25982599  async nest(signer: TSigner, toTokenObj: IToken) {2600    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2601  }26022603  async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2604    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2605  }26062607  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2608    return await this.collection.transferToken(signer, this.tokenId, addressObj);2609  }26102611  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2612    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2613  }26142615  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2616    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2617  }26182619  async isApproved(toAddressObj: ICrossAccountId) {2620    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2621  }26222623  async burn(signer: TSigner) {2624    return await this.collection.burnToken(signer, this.tokenId);2625  }26262627  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2628    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2629  }2630}26312632export class UniqueRFTToken extends UniqueTokenBase {2633  collection: UniqueRFTCollection;26342635  constructor(tokenId: number, collection: UniqueRFTCollection) {2636    super(tokenId, collection);2637    this.collection = collection;2638  }26392640  async getData(blockHashAt?: string) {2641    return await this.collection.getToken(this.tokenId, blockHashAt);2642  }26432644  async getTop10Owners() {2645    return await this.collection.getTop10TokenOwners(this.tokenId);2646  }26472648  async getBalance(addressObj: ICrossAccountId) {2649    return await this.collection.getTokenBalance(this.tokenId, addressObj);2650  }26512652  async getTotalPieces() {2653    return await this.collection.getTokenTotalPieces(this.tokenId);2654  }26552656  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2657    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2658  }26592660  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2661    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2662  }26632664  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2665    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2666  }26672668  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2669    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2670  }26712672  async repartition(signer: TSigner, amount: bigint) {2673    return await this.collection.repartitionToken(signer, this.tokenId, amount);2674  }26752676  async burn(signer: TSigner, amount=1n) {2677    return await this.collection.burnToken(signer, this.tokenId, amount);2678  }26792680  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2681    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2682  }2683}
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} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, ITokenAddress, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks, ICollectionBase, ICollectionNFT, ICollectionRFT, ITokenBase, ITokenNonfungible, ITokenRefungible, ICollectionFT} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15  const address = {} as ICrossAccountId;16  if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17  if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18  return address;19};2021const nesting = {22  toChecksumAddress(address: string): string {23    if (typeof address === 'undefined') return '';2425    if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627    address = address.toLowerCase().replace(/^0x/i,'');28    const addressHash = keccakAsHex(address).replace(/^0x/i,'');29    const checksumAddress = ['0x'];3031    for (let i = 0; i < address.length; i++) {32      // If ith character is 8 to f then make it uppercase33      if (parseInt(addressHash[i], 16) > 7) {34        checksumAddress.push(address[i].toUpperCase());35      } else {36        checksumAddress.push(address[i]);37      }38    }39    return checksumAddress.join('');40  },41  tokenIdToAddress(collectionId: number, tokenId: number) {42    return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);43  },44};4546class UniqueUtil {47  static transactionStatus = {48    NOT_READY: 'NotReady',49    FAIL: 'Fail',50    SUCCESS: 'Success',51  };5253  static chainLogType = {54    EXTRINSIC: 'extrinsic',55    RPC: 'rpc',56  };5758  static getTokenAccount(token: ITokenAddress): ICrossAccountId {59    return {Ethereum: this.getTokenAddress(token)};60  }6162  static getTokenAccountInLowerCase(token: ITokenAddress): ICrossAccountId {63    return {Ethereum: this.getTokenAddress(token).toLowerCase()};64  }6566  static getTokenAddress(token: ITokenAddress): string {67    return nesting.tokenIdToAddress(token.collectionId, token.tokenId);68  }6970  static getDefaultLogger(): ILogger {71    return {72      log(msg: any, level = 'INFO') {73        console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));74      },75      level: {76        ERROR: 'ERROR',77        WARNING: 'WARNING',78        INFO: 'INFO',79      },80    };81  }8283  static vec2str(arr: string[] | number[]) {84    return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');85  }8687  static str2vec(string: string) {88    if (typeof string !== 'string') return string;89    return Array.from(string).map(x => x.charCodeAt(0));90  }9192  static fromSeed(seed: string, ss58Format = 42) {93    const keyring = new Keyring({type: 'sr25519', ss58Format});94    return keyring.addFromUri(seed);95  }9697  static normalizeSubstrateAddress(address: string, ss58Format = 42) {98    return encodeAddress(decodeAddress(address), ss58Format);99  }100101  static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {102    if (creationResult.status !== this.transactionStatus.SUCCESS) {103      throw Error('Unable to create collection!');104    }105106    let collectionId = null;107    creationResult.result.events.forEach(({event: {data, method, section}}) => {108      if ((section === 'common') && (method === 'CollectionCreated')) {109        collectionId = parseInt(data[0].toString(), 10);110      }111    });112113    if (collectionId === null) {114      throw Error('No CollectionCreated event was found!');115    }116117    return collectionId;118  }119120  static extractTokensFromCreationResult(creationResult: ITransactionResult) {121    if (creationResult.status !== this.transactionStatus.SUCCESS) {122      throw Error('Unable to create tokens!');123    }124    let success = false;125    const tokens = [] as any;126    creationResult.result.events.forEach(({event: {data, method, section}}) => {127      if (method === 'ExtrinsicSuccess') {128        success = true;129      } else if ((section === 'common') && (method === 'ItemCreated')) {130        tokens.push({131          collectionId: parseInt(data[0].toString(), 10),132          tokenId: parseInt(data[1].toString(), 10),133          owner: data[2].toJSON(),134        });135      }136    });137    return {success, tokens};138  }139140  static extractTokensFromBurnResult(burnResult: ITransactionResult) {141    if (burnResult.status !== this.transactionStatus.SUCCESS) {142      throw Error('Unable to burn tokens!');143    }144    let success = false;145    const tokens = [] as any;146    burnResult.result.events.forEach(({event: {data, method, section}}) => {147      if (method === 'ExtrinsicSuccess') {148        success = true;149      } else if ((section === 'common') && (method === 'ItemDestroyed')) {150        tokens.push({151          collectionId: parseInt(data[0].toString(), 10),152          tokenId: parseInt(data[1].toString(), 10),153          owner: data[2].toJSON(),154        });155      }156    });157    return {success, tokens};158  }159160  static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {161    let eventId = null;162    events.forEach(({event: {data, method, section}}) => {163      if ((section === expectedSection) && (method === expectedMethod)) {164        eventId = parseInt(data[0].toString(), 10);165      }166    });167168    if (eventId === null) {169      throw Error(`No ${expectedMethod} event was found!`);170    }171    return eventId === collectionId;172  }173174  static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {175    const normalizeAddress = (address: string | ICrossAccountId) => {176      if(typeof address === 'string') return address;177      const obj = {} as any;178      Object.keys(address).forEach(k => {179        obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];180      });181      if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};182      if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};183      return address;184    };185    let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;186    events.forEach(({event: {data, method, section}}) => {187      if ((section === 'common') && (method === 'Transfer')) {188        const hData = (data as any).toJSON();189        transfer = {190          collectionId: hData[0],191          tokenId: hData[1],192          from: normalizeAddress(hData[2]),193          to: normalizeAddress(hData[3]),194          amount: BigInt(hData[4]),195        };196      }197    });198    let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;199    isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);200    isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);201    isSuccess = isSuccess && amount === transfer.amount;202    return isSuccess;203  }204}205206class UniqueEventHelper {207  private static extractIndex(index: any): [number, number] | string {208    if(index.toRawType() === '[u8;2]') return [index[0], index[1]];209    return index.toJSON();210  }211212  private static extractSub(data: any, subTypes: any): {[key: string]: any} {213    let obj: any = {};214    let index = 0;215216    if (data.entries) {217      for(const [key, value] of data.entries()) {218        obj[key] = this.extractData(value, subTypes[index]);219        index++;220      }221    } else obj = data.toJSON();222223    return obj;224  }225  226  private static extractData(data: any, type: any): any {227    if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();228    if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();229    if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);230    return data.toHuman();231  }232233  public static extractEvents(records: ITransactionResult): IEvent[] {234    const parsedEvents: IEvent[] = [];235236    records.result.events.forEach((record) => {237      const {event, phase} = record;238      const types = (event as any).typeDef;239240      const eventData: IEvent = {241        section: event.section.toString(),242        method: event.method.toString(),243        index: this.extractIndex(event.index),244        data: [],245        phase: phase.toJSON(),246      };247248      event.data.forEach((val: any, index: number) => {249        eventData.data.push(this.extractData(val, types[index]));250      });251252      parsedEvents.push(eventData);253    });254255    return parsedEvents;256  }257}258259class ChainHelperBase {260  transactionStatus = UniqueUtil.transactionStatus;261  chainLogType = UniqueUtil.chainLogType;262  util: typeof UniqueUtil;263  eventHelper: typeof UniqueEventHelper;264  logger: ILogger;265  api: ApiPromise | null;266  forcedNetwork: TUniqueNetworks | null;267  network: TUniqueNetworks | null;268  chainLog: IUniqueHelperLog[];269270  constructor(logger?: ILogger) {271    this.util = UniqueUtil;272    this.eventHelper = UniqueEventHelper;273    if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();274    this.logger = logger;275    this.api = null;276    this.forcedNetwork = null;277    this.network = null;278    this.chainLog = [];279  }280281  clearChainLog(): void {282    this.chainLog = [];283  }284285  forceNetwork(value: TUniqueNetworks): void {286    this.forcedNetwork = value;287  }288289  async connect(wsEndpoint: string, listeners?: IApiListeners) {290    if (this.api !== null) throw Error('Already connected');291    const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);292    this.api = api;293    this.network = network;294  }295296  async disconnect() {297    if (this.api === null) return;298    await this.api.disconnect();299    this.api = null;300    this.network = null;301  }302303  static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {304    const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;305    if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;306    return 'opal';307  }308309  static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {310    const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});311    await api.isReady;312313    const network = await this.detectNetwork(api);314315    await api.disconnect();316317    return network;318  }319320  static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{321    api: ApiPromise;322    network: TUniqueNetworks;323  }> {324    if(typeof network === 'undefined' || network === null) network = 'opal';325    const supportedRPC = {326      opal: {327        unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,328      },329      quartz: {330        unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,331      },332      unique: {333        unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,334      },335    };336    if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);337    const rpc = supportedRPC[network];338339    // TODO: investigate how to replace rpc in runtime340    // api._rpcCore.addUserInterfaces(rpc);341342    const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});343344    await api.isReadyOrError;345346    if (typeof listeners === 'undefined') listeners = {};347    for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {348      if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;349      api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);350    }351352    return {api, network};353  }354355  getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {356    const {events, status} = data;357    if (status.isReady) {358      return this.transactionStatus.NOT_READY;359    }360    if (status.isBroadcast) {361      return this.transactionStatus.NOT_READY;362    }363    if (status.isInBlock || status.isFinalized) {364      const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');365      if (errors.length > 0) {366        return this.transactionStatus.FAIL;367      }368      if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {369        return this.transactionStatus.SUCCESS;370      }371    }372373    return this.transactionStatus.FAIL;374  }375376  signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {377    const sign = (callback: any) => {378      if(options !== null) return transaction.signAndSend(sender, options, callback);379      return transaction.signAndSend(sender, callback);380    };381    // eslint-disable-next-line no-async-promise-executor382    return new Promise(async (resolve, reject) => {383      try {384        const unsub = await sign((result: any) => {385          const status = this.getTransactionStatus(result);386387          if (status === this.transactionStatus.SUCCESS) {388            this.logger.log(`${label} successful`);389            unsub();390            resolve({result, status});391          } else if (status === this.transactionStatus.FAIL) {392            let moduleError = null;393394            if (result.hasOwnProperty('dispatchError')) {395              const dispatchError = result['dispatchError'];396397              if (dispatchError) {398                if (dispatchError.isModule) {399                  const modErr = dispatchError.asModule;400                  const errorMeta = dispatchError.registry.findMetaError(modErr);401402                  moduleError = `${errorMeta.section}.${errorMeta.name}`;403                } else {404                  moduleError = dispatchError.toHuman();405                }406              } else {407                this.logger.log(result, this.logger.level.ERROR);408              }409            }410411            this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);412            unsub();413            reject({status, moduleError, result});414          }415        });416      } catch (e) {417        this.logger.log(e, this.logger.level.ERROR);418        reject(e);419      }420    });421  }422423  constructApiCall(apiCall: string, params: any[]) {424    if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);425    let call = this.api as any;426    for(const part of apiCall.slice(4).split('.')) {427      call = call[part];428    }429    return call(...params);430  }431432  async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {433    if(this.api === null) throw Error('API not initialized');434    if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);435436    const startTime = (new Date()).getTime();437    let result: ITransactionResult;438    let events: IEvent[] = [];439    try {440      result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;441      events = this.eventHelper.extractEvents(result);442    }443    catch(e) {444      if(!(e as object).hasOwnProperty('status')) throw e;445      result = e as ITransactionResult;446    }447448    const endTime = (new Date()).getTime();449450    const log = {451      executedAt: endTime,452      executionTime: endTime - startTime,453      type: this.chainLogType.EXTRINSIC,454      status: result.status,455      call: extrinsic,456      signer: this.getSignerAddress(sender),457      params,458    } as IUniqueHelperLog;459460    if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;461    if(events.length > 0) log.events = events;462463    this.chainLog.push(log);464465    if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);466    return result;467  }468469  async callRpc(rpc: string, params?: any[]) {470    if(typeof params === 'undefined') params = [];471    if(this.api === null) throw Error('API not initialized');472    if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);473474    const startTime = (new Date()).getTime();475    let result;476    let error = null;477    const log = {478      type: this.chainLogType.RPC,479      call: rpc,480      params,481    } as IUniqueHelperLog;482483    try {484      result = await this.constructApiCall(rpc, params);485    }486    catch(e) {487      error = e;488    }489490    const endTime = (new Date()).getTime();491492    log.executedAt = endTime;493    log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';494    log.executionTime = endTime - startTime;495496    this.chainLog.push(log);497498    if(error !== null) throw error;499500    return result;501  }502503  getSignerAddress(signer: IKeyringPair | string): string {504    if(typeof signer === 'string') return signer;505    return signer.address;506  }507508  fetchAllPalletNames(): string[] {509    if(this.api === null) throw Error('API not initialized');510    return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());511  }512513  fetchMissingPalletNames(requiredPallets: string[]): string[] {514    const palletNames = this.fetchAllPalletNames();515    return requiredPallets.filter(p => !palletNames.includes(p));516  }517}518519520class HelperGroup {521  helper: UniqueHelper;522523  constructor(uniqueHelper: UniqueHelper) {524    this.helper = uniqueHelper;525  }526}527528529class CollectionGroup extends HelperGroup {530  /**531 * Get number of blocks when sponsored transaction is available.532 *533 * @param collectionId ID of collection534 * @param tokenId ID of token535 * @param addressObj address for which the sponsorship is checked536 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});537 * @returns number of blocks or null if sponsorship hasn't been set538 */539  async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {540    return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();541  }542543  /**544   * Get the number of created collections.545   *546   * @returns number of created collections547   */548  async getTotalCount(): Promise<number> {549    return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();550  }551552  /**553   * Get information about the collection with additional data,554   * including the number of tokens it contains, its administrators,555   * the normalized address of the collection's owner, and decoded name and description.556   *557   * @param collectionId ID of collection558   * @example await getData(2)559   * @returns collection information object560   */561  async getData(collectionId: number): Promise<{562    id: number;563    name: string;564    description: string;565    tokensCount: number;566    admins: ICrossAccountId[];567    normalizedOwner: TSubstrateAccount;568    raw: any569  } | null> {570    const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);571    const humanCollection = collection.toHuman(), collectionData = {572      id: collectionId, name: null, description: null, tokensCount: 0, admins: [],573      raw: humanCollection,574    } as any, jsonCollection = collection.toJSON();575    if (humanCollection === null) return null;576    collectionData.raw.limits = jsonCollection.limits;577    collectionData.raw.permissions = jsonCollection.permissions;578    collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);579    for (const key of ['name', 'description']) {580      collectionData[key] = this.helper.util.vec2str(humanCollection[key]);581    }582583    collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))584      ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)585      : 0;586    collectionData.admins = await this.getAdmins(collectionId);587588    return collectionData;589  }590591  /**592   * Get the addresses of the collection's administrators, optionally normalized.593   *594   * @param collectionId ID of collection595   * @param normalize whether to normalize the addresses to the default ss58 format596   * @example await getAdmins(1)597   * @returns array of administrators598   */599  async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {600    const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();601602    return normalize603      ? admins.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))604      : admins;605  }606607  /**608   * Get the addresses added to the collection allow-list, optionally normalized.609   * @param collectionId ID of collection610   * @param normalize whether to normalize the addresses to the default ss58 format611   * @example await getAllowList(1)612   * @returns array of allow-listed addresses613   */614  async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {615    const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();616    return normalize617      ? allowListed.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))618      : allowListed;619  }620621  /**622   * Get the effective limits of the collection instead of null for default values623   *624   * @param collectionId ID of collection625   * @example await getEffectiveLimits(2)626   * @returns object of collection limits627   */628  async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {629    return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();630  }631632  /**633   * Burns the collection if the signer has sufficient permissions and collection is empty.634   *635   * @param signer keyring of signer636   * @param collectionId ID of collection637   * @example await helper.collection.burn(aliceKeyring, 3);638   * @returns ```true``` if extrinsic success, otherwise ```false```639   */640  async burn(signer: TSigner, collectionId: number): Promise<boolean> {641    const result = await this.helper.executeExtrinsic(642      signer,643      'api.tx.unique.destroyCollection', [collectionId],644      true,645    );646647    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');648  }649650  /**651   * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.652   *653   * @param signer keyring of signer654   * @param collectionId ID of collection655   * @param sponsorAddress Sponsor substrate address656   * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")657   * @returns ```true``` if extrinsic success, otherwise ```false```658   */659  async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {660    const result = await this.helper.executeExtrinsic(661      signer,662      'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],663      true,664    );665666    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');667  }668669  /**670   * Confirms consent to sponsor the collection on behalf of the signer.671   *672   * @param signer keyring of signer673   * @param collectionId ID of collection674   * @example confirmSponsorship(aliceKeyring, 10)675   * @returns ```true``` if extrinsic success, otherwise ```false```676   */677  async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {678    const result = await this.helper.executeExtrinsic(679      signer,680      'api.tx.unique.confirmSponsorship', [collectionId],681      true,682    );683684    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');685  }686687  /**688   * Removes the sponsor of a collection, regardless if it consented or not.689   *690   * @param signer keyring of signer691   * @param collectionId ID of collection692   * @example removeSponsor(aliceKeyring, 10)693   * @returns ```true``` if extrinsic success, otherwise ```false```694   */695  async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {696    const result = await this.helper.executeExtrinsic(697      signer,698      'api.tx.unique.removeCollectionSponsor', [collectionId],699      true,700    );701702    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');703  }704705  /**706   * Sets the limits of the collection. At least one limit must be specified for a correct call.707   *708   * @param signer keyring of signer709   * @param collectionId ID of collection710   * @param limits collection limits object711   * @example712   * await setLimits(713   *   aliceKeyring,714   *   10,715   *   {716   *     sponsorTransferTimeout: 0,717   *     ownerCanDestroy: false718   *   }719   * )720   * @returns ```true``` if extrinsic success, otherwise ```false```721   */722  async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {723    const result = await this.helper.executeExtrinsic(724      signer,725      'api.tx.unique.setCollectionLimits', [collectionId, limits],726      true,727    );728729    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');730  }731732  /**733   * Changes the owner of the collection to the new Substrate address.734   *735   * @param signer keyring of signer736   * @param collectionId ID of collection737   * @param ownerAddress substrate address of new owner738   * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")739   * @returns ```true``` if extrinsic success, otherwise ```false```740   */741  async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {742    const result = await this.helper.executeExtrinsic(743      signer,744      'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],745      true,746    );747748    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');749  }750751  /**752   * Adds a collection administrator.753   *754   * @param signer keyring of signer755   * @param collectionId ID of collection756   * @param adminAddressObj Administrator address (substrate or ethereum)757   * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})758   * @returns ```true``` if extrinsic success, otherwise ```false```759   */760  async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {761    const result = await this.helper.executeExtrinsic(762      signer,763      'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],764      true,765    );766767    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');768  }769770  /**771   * Removes a collection administrator.772   *773   * @param signer keyring of signer774   * @param collectionId ID of collection775   * @param adminAddressObj Administrator address (substrate or ethereum)776   * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})777   * @returns ```true``` if extrinsic success, otherwise ```false```778   */779  async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {780    const result = await this.helper.executeExtrinsic(781      signer,782      'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],783      true,784    );785786    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');787  }788789  /**790   * Check if user is in allow list.791   * 792   * @param collectionId ID of collection793   * @param user Account to check794   * @example await getAdmins(1)795   * @returns is user in allow list796   */797  async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {798    return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();799  }800801  /**802   * Adds an address to allow list803   * @param signer keyring of signer804   * @param collectionId ID of collection805   * @param addressObj address to add to the allow list806   * @returns ```true``` if extrinsic success, otherwise ```false```807   */808  async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {809    const result = await this.helper.executeExtrinsic(810      signer,811      'api.tx.unique.addToAllowList', [collectionId, addressObj],812      true,813    );814815    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');816  }817818  /**819   * Removes an address from allow list820   *821   * @param signer keyring of signer822   * @param collectionId ID of collection823   * @param addressObj address to remove from the allow list824   * @returns ```true``` if extrinsic success, otherwise ```false```825   */826  async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {827    const result = await this.helper.executeExtrinsic(828      signer,829      'api.tx.unique.removeFromAllowList', [collectionId, addressObj],830      true,831    );832833    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');834  }835836  /**837   * Sets onchain permissions for selected collection.838   *839   * @param signer keyring of signer840   * @param collectionId ID of collection841   * @param permissions collection permissions object842   * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});843   * @returns ```true``` if extrinsic success, otherwise ```false```844   */845  async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {846    const result = await this.helper.executeExtrinsic(847      signer,848      'api.tx.unique.setCollectionPermissions', [collectionId, permissions],849      true,850    );851852    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');853  }854855  /**856   * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.857   *858   * @param signer keyring of signer859   * @param collectionId ID of collection860   * @param permissions nesting permissions object861   * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});862   * @returns ```true``` if extrinsic success, otherwise ```false```863   */864  async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {865    return await this.setPermissions(signer, collectionId, {nesting: permissions});866  }867868  /**869   * Disables nesting for selected collection.870   *871   * @param signer keyring of signer872   * @param collectionId ID of collection873   * @example disableNesting(aliceKeyring, 10);874   * @returns ```true``` if extrinsic success, otherwise ```false```875   */876  async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {877    return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});878  }879880  /**881   * Sets onchain properties to the collection.882   *883   * @param signer keyring of signer884   * @param collectionId ID of collection885   * @param properties array of property objects886   * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);887   * @returns ```true``` if extrinsic success, otherwise ```false```888   */889  async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {890    const result = await this.helper.executeExtrinsic(891      signer,892      'api.tx.unique.setCollectionProperties', [collectionId, properties],893      true,894    );895896    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');897  }898899  /**900   * Get collection properties.901   * 902   * @param collectionId ID of collection903   * @param propertyKeys optionally filter the returned properties to only these keys904   * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);905   * @returns array of key-value pairs906   */907  async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {908    return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();909  }910911  /**912   * Deletes onchain properties from the collection.913   *914   * @param signer keyring of signer915   * @param collectionId ID of collection916   * @param propertyKeys array of property keys to delete917   * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);918   * @returns ```true``` if extrinsic success, otherwise ```false```919   */920  async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {921    const result = await this.helper.executeExtrinsic(922      signer,923      'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],924      true,925    );926927    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');928  }929930  /**931   * Changes the owner of the token.932   *933   * @param signer keyring of signer934   * @param collectionId ID of collection935   * @param tokenId ID of token936   * @param addressObj address of a new owner937   * @param amount amount of tokens to be transfered. For NFT must be set to 1n938   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})939   * @returns true if the token success, otherwise false940   */941  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {942    const result = await this.helper.executeExtrinsic(943      signer,944      'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],945      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,946    );947948    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);949  }950951  /**952   *953   * Change ownership of a token(s) on behalf of the owner.954   *955   * @param signer keyring of signer956   * @param collectionId ID of collection957   * @param tokenId ID of token958   * @param fromAddressObj address on behalf of which the token will be sent959   * @param toAddressObj new token owner960   * @param amount amount of tokens to be transfered. For NFT must be set to 1n961   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})962   * @returns true if the token success, otherwise false963   */964  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {965    const result = await this.helper.executeExtrinsic(966      signer,967      'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],968      true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,969    );970    return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);971  }972973  /**974   *975   * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.976   *977   * @param signer keyring of signer978   * @param collectionId ID of collection979   * @param tokenId ID of token980   * @param amount amount of tokens to be burned. For NFT must be set to 1n981   * @example burnToken(aliceKeyring, 10, 5);982   * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```983   */984  async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{985    success: boolean,986    token: number | null987  }> {988    const burnResult = await this.helper.executeExtrinsic(989      signer,990      'api.tx.unique.burnItem', [collectionId, tokenId, amount],991      true, // `Unable to burn token for ${label}`,992    );993    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);994    if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');995    return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};996  }997998  /**999   * Destroys a concrete instance of NFT on behalf of the owner1000   *1001   * @param signer keyring of signer1002   * @param collectionId ID of collection1003   * @param tokenId ID of token1004   * @param fromAddressObj address on behalf of which the token will be burnt1005   * @param amount amount of tokens to be burned. For NFT must be set to 1n1006   * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1007   * @returns ```true``` if extrinsic success, otherwise ```false```1008   */1009  async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1010    const burnResult = await this.helper.executeExtrinsic(1011      signer,1012      'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1013      true, // `Unable to burn token from for ${label}`,1014    );1015    const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1016    return burnedTokens.success && burnedTokens.tokens.length > 0;1017  }10181019  /**1020   * Set, change, or remove approved address to transfer the ownership of the NFT.1021   *1022   * @param signer keyring of signer1023   * @param collectionId ID of collection1024   * @param tokenId ID of token1025   * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1026   * @param amount amount of token to be approved. For NFT must be set to 1n1027   * @returns ```true``` if extrinsic success, otherwise ```false```1028   */1029  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1030    const approveResult = await this.helper.executeExtrinsic(1031      signer,1032      'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1033      true, // `Unable to approve token for ${label}`,1034    );10351036    return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1037  }10381039  /**1040   * Get the amount of token pieces approved to transfer or burn. Normally 0.1041   *1042   * @param collectionId ID of collection1043   * @param tokenId ID of token1044   * @param toAccountObj address which is approved to use token pieces1045   * @param fromAccountObj address which may have allowed the use of its owned tokens1046   * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1047   * @returns number of approved to transfer pieces1048   */1049  async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1050    return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1051  }10521053  /**1054   * Get the last created token ID in a collection1055   *1056   * @param collectionId ID of collection1057   * @example getLastTokenId(10);1058   * @returns id of the last created token1059   */1060  async getLastTokenId(collectionId: number): Promise<number> {1061    return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1062  }10631064  /**1065   * Check if token exists1066   *1067   * @param collectionId ID of collection1068   * @param tokenId ID of token1069   * @example isTokenExists(10, 20);1070   * @returns true if the token exists, otherwise false1071   */1072  async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1073    return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1074  }1075}10761077class NFTnRFT extends CollectionGroup {1078  /**1079   * Get tokens owned by account1080   *1081   * @param collectionId ID of collection1082   * @param addressObj tokens owner1083   * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1084   * @returns array of token ids owned by account1085   */1086  async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1087    return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1088  }10891090  /**1091   * Get token data1092   *1093   * @param collectionId ID of collection1094   * @param tokenId ID of token1095   * @param propertyKeys optionally filter the token properties to only these keys1096   * @param blockHashAt optionally query the data at some block with this hash1097   * @example getToken(10, 5);1098   * @returns human readable token data1099   */1100  async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1101    properties: IProperty[];1102    owner: ICrossAccountId;1103    normalizedOwner: ICrossAccountId;1104  }| null> {1105    let tokenData;1106    if(typeof blockHashAt === 'undefined') {1107      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1108    }1109    else {1110      if(propertyKeys.length == 0) {1111        const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112        if(!collection) return null;1113        propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1114      }1115      tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1116    }1117    tokenData = tokenData.toHuman();1118    if (tokenData === null || tokenData.owner === null) return null;1119    const owner = {} as any;1120    for (const key of Object.keys(tokenData.owner)) {1121      owner[key.toLocaleLowerCase()] = this.helper.address.normalizeCrossAccountIfSubstrate(tokenData.owner[key]);1122    }1123    tokenData.normalizedOwner = crossAccountIdFromLower(owner);1124    return tokenData;1125  }11261127  /**1128   * Set permissions to change token properties1129   *1130   * @param signer keyring of signer1131   * @param collectionId ID of collection1132   * @param permissions permissions to change a property by the collection admin or token owner1133   * @example setTokenPropertyPermissions(1134   *   aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1135   * )1136   * @returns true if extrinsic success otherwise false1137   */1138  async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1139    const result = await this.helper.executeExtrinsic(1140      signer,1141      'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1142      true,1143    );11441145    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1146  }11471148  /**1149   * Get token property permissions.1150   * 1151   * @param collectionId ID of collection1152   * @param propertyKeys optionally filter the returned property permissions to only these keys1153   * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1154   * @returns array of key-permission pairs1155   */1156  async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1157    return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1158  }11591160  /**1161   * Set token properties1162   *1163   * @param signer keyring of signer1164   * @param collectionId ID of collection1165   * @param tokenId ID of token1166   * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1167   * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1168   * @returns ```true``` if extrinsic success, otherwise ```false```1169   */1170  async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1171    const result = await this.helper.executeExtrinsic(1172      signer,1173      'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1174      true,1175    );11761177    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1178  }11791180  /**1181   * Get properties, metadata assigned to a token.1182   * 1183   * @param collectionId ID of collection1184   * @param tokenId ID of token1185   * @param propertyKeys optionally filter the returned properties to only these keys1186   * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1187   * @returns array of key-value pairs1188   */1189  async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1190    return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1191  }11921193  /**1194   * Delete the provided properties of a token1195   * @param signer keyring of signer1196   * @param collectionId ID of collection1197   * @param tokenId ID of token1198   * @param propertyKeys property keys to be deleted1199   * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1200   * @returns ```true``` if extrinsic success, otherwise ```false```1201   */1202  async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1203    const result = await this.helper.executeExtrinsic(1204      signer,1205      'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1206      true,1207    );12081209    return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1210  }12111212  /**1213   * Mint new collection1214   *1215   * @param signer keyring of signer1216   * @param collectionOptions basic collection options and properties1217   * @param mode NFT or RFT type of a collection1218   * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1219   * @returns object of the created collection1220   */1221  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1222    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1223    collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1224    for (const key of ['name', 'description', 'tokenPrefix']) {1225      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);1226    }1227    const creationResult = await this.helper.executeExtrinsic(1228      signer,1229      'api.tx.unique.createCollectionEx', [collectionOptions],1230      true, // errorLabel,1231    );1232    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1233  }12341235  getCollectionObject(_collectionId: number): any {1236    return null;1237  }12381239  getTokenObject(_collectionId: number, _tokenId: number): any {1240    return null;1241  }1242}124312441245class NFTGroup extends NFTnRFT {1246  /**1247   * Get collection object1248   * @param collectionId ID of collection1249   * @example getCollectionObject(2);1250   * @returns instance of UniqueNFTCollection1251   */1252  getCollectionObject(collectionId: number): UniqueNFTCollection {1253    return new UniqueNFTCollection(collectionId, this.helper);1254  }12551256  /**1257   * Get token object1258   * @param collectionId ID of collection1259   * @param tokenId ID of token1260   * @example getTokenObject(10, 5);1261   * @returns instance of UniqueNFTToken1262   */1263  getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1264    return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1265  }12661267  /**1268   * Get token's owner1269   * @param collectionId ID of collection1270   * @param tokenId ID of token1271   * @param blockHashAt optionally query the data at the block with this hash1272   * @example getTokenOwner(10, 5);1273   * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1274   */1275  async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1276    let owner;1277    if (typeof blockHashAt === 'undefined') {1278      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1279    } else {1280      owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1281    }1282    return crossAccountIdFromLower(owner.toJSON());1283  }12841285  /**1286   * Is token approved to transfer1287   * @param collectionId ID of collection1288   * @param tokenId ID of token1289   * @param toAccountObj address to be approved1290   * @returns ```true``` if extrinsic success, otherwise ```false```1291   */1292  async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1293    return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1294  }12951296  /**1297   * Changes the owner of the token.1298   *1299   * @param signer keyring of signer1300   * @param collectionId ID of collection1301   * @param tokenId ID of token1302   * @param addressObj address of a new owner1303   * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1304   * @returns ```true``` if extrinsic success, otherwise ```false```1305   */1306  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1307    return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1308  }13091310  /**1311   *1312   * Change ownership of a NFT on behalf of the owner.1313   *1314   * @param signer keyring of signer1315   * @param collectionId ID of collection1316   * @param tokenId ID of token1317   * @param fromAddressObj address on behalf of which the token will be sent1318   * @param toAddressObj new token owner1319   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1320   * @returns ```true``` if extrinsic success, otherwise ```false```1321   */1322  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1323    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1324  }13251326  /**1327   * Recursively find the address that owns the token1328   * @param collectionId ID of collection1329   * @param tokenId ID of token1330   * @param blockHashAt1331   * @example getTokenTopmostOwner(10, 5);1332   * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1333   */1334  async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1335    let owner;1336    if (typeof blockHashAt === 'undefined') {1337      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1338    } else {1339      owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1340    }13411342    if (owner === null) return null;13431344    return owner.toHuman();1345  }13461347  /**1348   * Get tokens nested in the provided token1349   * @param collectionId ID of collection1350   * @param tokenId ID of token1351   * @param blockHashAt optionally query the data at the block with this hash1352   * @example getTokenChildren(10, 5);1353   * @returns tokens whose depth of nesting is <= 51354   */1355  async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ITokenAddress[]> {1356    let children;1357    if(typeof blockHashAt === 'undefined') {1358      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1359    } else {1360      children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1361    }13621363    return children.toJSON().map((x: any) => {1364      return {collectionId: x.collection, tokenId: x.token};1365    });1366  }13671368  /**1369   * Nest one token into another1370   * @param signer keyring of signer1371   * @param tokenObj token to be nested1372   * @param rootTokenObj token to be parent1373   * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1374   * @returns ```true``` if extrinsic success, otherwise ```false```1375   */1376  async nestToken(signer: TSigner, tokenObj: ITokenAddress, rootTokenObj: ITokenAddress): Promise<boolean> {1377    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1378    const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1379    if(!result) {1380      throw Error('Unable to nest token!');1381    }1382    return result;1383  }13841385  /**1386   * Remove token from nested state1387   * @param signer keyring of signer1388   * @param tokenObj token to unnest1389   * @param rootTokenObj parent of a token1390   * @param toAddressObj address of a new token owner1391   * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1392   * @returns ```true``` if extrinsic success, otherwise ```false```1393   */1394  async unnestToken(signer: TSigner, tokenObj: ITokenAddress, rootTokenObj: ITokenAddress, toAddressObj: ICrossAccountId): Promise<boolean> {1395    const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1396    const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1397    if(!result) {1398      throw Error('Unable to unnest token!');1399    }1400    return result;1401  }14021403  /**1404   * Mint new collection1405   * @param signer keyring of signer1406   * @param collectionOptions Collection options1407   * @example1408   * mintCollection(aliceKeyring, {1409   *   name: 'New',1410   *   description: 'New collection',1411   *   tokenPrefix: 'NEW',1412   * })1413   * @returns object of the created collection1414   */1415  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1416    return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1417  }14181419  /**1420   * Mint new token1421   * @param signer keyring of signer1422   * @param data token data1423   * @returns created token object1424   */1425  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1426    const creationResult = await this.helper.executeExtrinsic(1427      signer,1428      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1429        nft: {1430          properties: data.properties,1431        },1432      }],1433      true,1434    );1435    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1436    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1437    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1438    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1439  }14401441  /**1442   * Mint multiple NFT tokens1443   * @param signer keyring of signer1444   * @param collectionId ID of collection1445   * @param tokens array of tokens with owner and properties1446   * @example1447   * mintMultipleTokens(aliceKeyring, 10, [{1448   *     owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1449   *     properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1450   *   },{1451   *     owner: {Ethereum: "0x9F0583DbB855d..."},1452   *     properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1453   * }]);1454   * @returns ```true``` if extrinsic success, otherwise ```false```1455   */1456  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1457    const creationResult = await this.helper.executeExtrinsic(1458      signer,1459      'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1460      true,1461    );1462    const collection = this.getCollectionObject(collectionId);1463    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1464  }14651466  /**1467   * Mint multiple NFT tokens with one owner1468   * @param signer keyring of signer1469   * @param collectionId ID of collection1470   * @param owner tokens owner1471   * @param tokens array of tokens with owner and properties1472   * @example1473   * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1474   *   properties: [{1475   *   key: "gender",1476   *   value: "female",1477   *  },{1478   *   key: "age",1479   *   value: "33",1480   *  }],1481   * }]);1482   * @returns array of newly created tokens1483   */1484  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1485    const rawTokens = [];1486    for (const token of tokens) {1487      const raw = {NFT: {properties: token.properties}};1488      rawTokens.push(raw);1489    }1490    const creationResult = await this.helper.executeExtrinsic(1491      signer,1492      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1493      true,1494    );1495    const collection = this.getCollectionObject(collectionId);1496    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1497  }14981499  /**1500   * Set, change, or remove approved address to transfer the ownership of the NFT.1501   *1502   * @param signer keyring of signer1503   * @param collectionId ID of collection1504   * @param tokenId ID of token1505   * @param toAddressObj address to approve1506   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1507   * @returns ```true``` if extrinsic success, otherwise ```false```1508   */1509  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1510    return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1511  }1512}151315141515class RFTGroup extends NFTnRFT {1516  /**1517   * Get collection object1518   * @param collectionId ID of collection1519   * @example getCollectionObject(2);1520   * @returns instance of UniqueRFTCollection1521   */1522  getCollectionObject(collectionId: number): UniqueRFTCollection {1523    return new UniqueRFTCollection(collectionId, this.helper);1524  }15251526  /**1527   * Get token object1528   * @param collectionId ID of collection1529   * @param tokenId ID of token1530   * @example getTokenObject(10, 5);1531   * @returns instance of UniqueNFTToken1532   */1533  getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1534    return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1535  }15361537  /**1538   * Get top 10 token owners with the largest number of pieces1539   * @param collectionId ID of collection1540   * @param tokenId ID of token1541   * @example getTokenTop10Owners(10, 5);1542   * @returns array of top 10 owners1543   */1544  async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1545    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1546  }15471548  /**1549   * Get number of pieces owned by address1550   * @param collectionId ID of collection1551   * @param tokenId ID of token1552   * @param addressObj address token owner1553   * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1554   * @returns number of pieces ownerd by address1555   */1556  async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1557    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1558  }15591560  /**1561   * Transfer pieces of token to another address1562   * @param signer keyring of signer1563   * @param collectionId ID of collection1564   * @param tokenId ID of token1565   * @param addressObj address of a new owner1566   * @param amount number of pieces to be transfered1567   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1568   * @returns ```true``` if extrinsic success, otherwise ```false```1569   */1570  async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1571    return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1572  }15731574  /**1575   * Change ownership of some pieces of RFT on behalf of the owner.1576   * @param signer keyring of signer1577   * @param collectionId ID of collection1578   * @param tokenId ID of token1579   * @param fromAddressObj address on behalf of which the token will be sent1580   * @param toAddressObj new token owner1581   * @param amount number of pieces to be transfered1582   * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1583   * @returns ```true``` if extrinsic success, otherwise ```false```1584   */1585  async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1586    return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1587  }15881589  /**1590   * Mint new collection1591   * @param signer keyring of signer1592   * @param collectionOptions Collection options1593   * @example1594   * mintCollection(aliceKeyring, {1595   *   name: 'New',1596   *   description: 'New collection',1597   *   tokenPrefix: 'NEW',1598   * })1599   * @returns object of the created collection1600   */1601  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1602    return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1603  }16041605  /**1606   * Mint new token1607   * @param signer keyring of signer1608   * @param data token data1609   * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1610   * @returns created token object1611   */1612  async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1613    const creationResult = await this.helper.executeExtrinsic(1614      signer,1615      'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1616        refungible: {1617          pieces: data.pieces,1618          properties: data.properties,1619        },1620      }],1621      true,1622    );1623    const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1624    if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1625    if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1626    return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1627  }16281629  async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1630    throw Error('Not implemented');1631    const creationResult = await this.helper.executeExtrinsic(1632      signer,1633      'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1634      true, // `Unable to mint RFT tokens for ${label}`,1635    );1636    const collection = this.getCollectionObject(collectionId);1637    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1638  }16391640  /**1641   * Mint multiple RFT tokens with one owner1642   * @param signer keyring of signer1643   * @param collectionId ID of collection1644   * @param owner tokens owner1645   * @param tokens array of tokens with properties and pieces1646   * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1647   * @returns array of newly created RFT tokens1648   */1649  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1650    const rawTokens = [];1651    for (const token of tokens) {1652      const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1653      rawTokens.push(raw);1654    }1655    const creationResult = await this.helper.executeExtrinsic(1656      signer,1657      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1658      true,1659    );1660    const collection = this.getCollectionObject(collectionId);1661    return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1662  }16631664  /**1665   * Destroys a concrete instance of RFT.1666   * @param signer keyring of signer1667   * @param collectionId ID of collection1668   * @param tokenId ID of token1669   * @param amount number of pieces to be burnt1670   * @example burnToken(aliceKeyring, 10, 5);1671   * @returns ```true``` and burnt token number, if extrinsic is successful. Otherwise ```false``` and ```null```1672   */1673  async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1674    return await super.burnToken(signer, collectionId, tokenId, amount);1675  }16761677  /**1678   * Destroys a concrete instance of RFT on behalf of the owner.1679   * @param signer keyring of signer1680   * @param collectionId ID of collection1681   * @param tokenId ID of token1682   * @param fromAddressObj address on behalf of which the token will be burnt1683   * @param amount number of pieces to be burnt1684   * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1685   * @returns ```true``` if extrinsic success, otherwise ```false```1686   */1687  async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1688    return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1689  }16901691  /**1692   * Set, change, or remove approved address to transfer the ownership of the RFT.1693   *1694   * @param signer keyring of signer1695   * @param collectionId ID of collection1696   * @param tokenId ID of token1697   * @param toAddressObj address to approve1698   * @param amount number of pieces to be approved1699   * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1700   * @returns true if the token success, otherwise false1701   */1702  async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1703    return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1704  }17051706  /**1707   * Get total number of pieces1708   * @param collectionId ID of collection1709   * @param tokenId ID of token1710   * @example getTokenTotalPieces(10, 5);1711   * @returns number of pieces1712   */1713  async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1714    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1715  }17161717  /**1718   * Change number of token pieces. Signer must be the owner of all token pieces.1719   * @param signer keyring of signer1720   * @param collectionId ID of collection1721   * @param tokenId ID of token1722   * @param amount new number of pieces1723   * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1724   * @returns true if the repartion was success, otherwise false1725   */1726  async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1727    const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1728    const repartitionResult = await this.helper.executeExtrinsic(1729      signer,1730      'api.tx.unique.repartition', [collectionId, tokenId, amount],1731      true,1732    );1733    if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1734    return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1735  }1736}173717381739class FTGroup extends CollectionGroup {1740  /**1741   * Get collection object1742   * @param collectionId ID of collection1743   * @example getCollectionObject(2);1744   * @returns instance of UniqueFTCollection1745   */1746  getCollectionObject(collectionId: number): UniqueFTCollection {1747    return new UniqueFTCollection(collectionId, this.helper);1748  }17491750  /**1751   * Mint new fungible collection1752   * @param signer keyring of signer1753   * @param collectionOptions Collection options1754   * @param decimalPoints number of token decimals1755   * @example1756   * mintCollection(aliceKeyring, {1757   *   name: 'New',1758   *   description: 'New collection',1759   *   tokenPrefix: 'NEW',1760   * }, 18)1761   * @returns newly created fungible collection1762   */1763  async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1764    collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1765    if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1766    collectionOptions.mode = {fungible: decimalPoints};1767    for (const key of ['name', 'description', 'tokenPrefix']) {1768      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);1769    }1770    const creationResult = await this.helper.executeExtrinsic(1771      signer,1772      'api.tx.unique.createCollectionEx', [collectionOptions],1773      true,1774    );1775    return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1776  }17771778  /**1779   * Mint tokens1780   * @param signer keyring of signer1781   * @param collectionId ID of collection1782   * @param owner address owner of new tokens1783   * @param amount amount of tokens to be meanted1784   * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1785   * @returns ```true``` if extrinsic success, otherwise ```false```1786   */1787  async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1788    const creationResult = await this.helper.executeExtrinsic(1789      signer,1790      'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1791        fungible: {1792          value: amount,1793        },1794      }],1795      true, // `Unable to mint fungible tokens for ${label}`,1796    );1797    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1798  }17991800  /**1801   * Mint multiple Fungible tokens with one owner1802   * @param signer keyring of signer1803   * @param collectionId ID of collection1804   * @param owner tokens owner1805   * @param tokens array of tokens with properties and pieces1806   * @returns ```true``` if extrinsic success, otherwise ```false```1807   */1808  async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1809    const rawTokens = [];1810    for (const token of tokens) {1811      const raw = {Fungible: {Value: token.value}};1812      rawTokens.push(raw);1813    }1814    const creationResult = await this.helper.executeExtrinsic(1815      signer,1816      'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1817      true,1818    );1819    return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1820  }18211822  /**1823   * Get the top 10 owners with the largest balance for the Fungible collection1824   * @param collectionId ID of collection1825   * @example getTop10Owners(10);1826   * @returns array of ```ICrossAccountId```1827   */1828  async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1829    return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1830  }18311832  /**1833   * Get account balance1834   * @param collectionId ID of collection1835   * @param addressObj address of owner1836   * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1837   * @returns amount of fungible tokens owned by address1838   */1839  async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1840    return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1841  }18421843  /**1844   * Transfer tokens to address1845   * @param signer keyring of signer1846   * @param collectionId ID of collection1847   * @param toAddressObj address recipient1848   * @param amount amount of tokens to be sent1849   * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1850   * @returns ```true``` if extrinsic success, otherwise ```false```1851   */1852  async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1853    return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1854  }18551856  /**1857   * Transfer some tokens on behalf of the owner.1858   * @param signer keyring of signer1859   * @param collectionId ID of collection1860   * @param fromAddressObj address on behalf of which tokens will be sent1861   * @param toAddressObj address where token to be sent1862   * @param amount number of tokens to be sent1863   * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1864   * @returns ```true``` if extrinsic success, otherwise ```false```1865   */1866  async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1867    return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1868  }18691870  /**1871   * Destroy some amount of tokens1872   * @param signer keyring of signer1873   * @param collectionId ID of collection1874   * @param amount amount of tokens to be destroyed1875   * @example burnTokens(aliceKeyring, 10, 1000n);1876   * @returns ```true``` if extrinsic success, otherwise ```false```1877   */1878  async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1879    return (await super.burnToken(signer, collectionId, 0, amount)).success;1880  }18811882  /**1883   * Burn some tokens on behalf of the owner.1884   * @param signer keyring of signer1885   * @param collectionId ID of collection1886   * @param fromAddressObj address on behalf of which tokens will be burnt1887   * @param amount amount of tokens to be burnt1888   * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1889   * @returns ```true``` if extrinsic success, otherwise ```false```1890   */1891  async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1892    return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1893  }18941895  /**1896   * Get total collection supply1897   * @param collectionId1898   * @returns1899   */1900  async getTotalPieces(collectionId: number): Promise<bigint> {1901    return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1902  }19031904  /**1905   * Set, change, or remove approved address to transfer tokens.1906   *1907   * @param signer keyring of signer1908   * @param collectionId ID of collection1909   * @param toAddressObj address to be approved1910   * @param amount amount of tokens to be approved1911   * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1912   * @returns ```true``` if extrinsic success, otherwise ```false```1913   */1914  async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1915    return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1916  }19171918  /**1919   * Get amount of fungible tokens approved to transfer1920   * @param collectionId ID of collection1921   * @param fromAddressObj owner of tokens1922   * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1923   * @returns number of tokens approved for the transfer1924   */1925  async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1926    return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1927  }1928}192919301931class ChainGroup extends HelperGroup {1932  /**1933   * Get system properties of a chain1934   * @example getChainProperties();1935   * @returns ss58Format, token decimals, and token symbol1936   */1937  getChainProperties(): IChainProperties {1938    const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1939    return {1940      ss58Format: properties.ss58Format.toJSON(),1941      tokenDecimals: properties.tokenDecimals.toJSON(),1942      tokenSymbol: properties.tokenSymbol.toJSON(),1943    };1944  }19451946  /**1947   * Get chain header1948   * @example getLatestBlockNumber();1949   * @returns the number of the last block1950   */1951  async getLatestBlockNumber(): Promise<number> {1952    return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1953  }19541955  /**1956   * Get block hash by block number1957   * @param blockNumber number of block1958   * @example getBlockHashByNumber(12345);1959   * @returns hash of a block1960   */1961  async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1962    const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1963    if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1964    return blockHash;1965  }19661967  // TODO add docs1968  async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1969    const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1970    if (!blockHash) return null;1971    return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1972  }19731974  /**1975   * Get account nonce1976   * @param address substrate address1977   * @example getNonce("5GrwvaEF5zXb26Fz...");1978   * @returns number, account's nonce1979   */1980  async getNonce(address: TSubstrateAccount): Promise<number> {1981    return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1982  }1983}198419851986class BalanceGroup extends HelperGroup {1987  /**1988   * Representation of the native token in the smallest unit1989   * @example getOneTokenNominal()1990   * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1991   */1992  getOneTokenNominal(): bigint {1993    const chainProperties = this.helper.chain.getChainProperties();1994    return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1995  }19961997  /**1998   * Get substrate address balance1999   * @param address substrate address2000   * @example getSubstrate("5GrwvaEF5zXb26Fz...")2001   * @returns amount of tokens on address2002   */2003  async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2004    return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2005  }20062007  /**2008   * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2009   * @param address substrate address2010   * @returns2011   */2012  async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2013    const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2014    return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2015  }20162017  /**2018   * Get ethereum address balance2019   * @param address ethereum address2020   * @example getEthereum("0x9F0583DbB855d...")2021   * @returns amount of tokens on address2022   */2023  async getEthereum(address: TEthereumAccount): Promise<bigint> {2024    return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2025  }20262027  /**2028   * Transfer tokens to substrate address2029   * @param signer keyring of signer2030   * @param address substrate address of a recipient2031   * @param amount amount of tokens to be transfered2032   * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2033   * @returns ```true``` if extrinsic success, otherwise ```false```2034   */2035  async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2036    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}`*/);20372038    let transfer = {from: null, to: null, amount: 0n} as any;2039    result.result.events.forEach(({event: {data, method, section}}) => {2040      if ((section === 'balances') && (method === 'Transfer')) {2041        transfer = {2042          from: this.helper.address.normalizeSubstrate(data[0]),2043          to: this.helper.address.normalizeSubstrate(data[1]),2044          amount: BigInt(data[2]),2045        };2046      }2047    });2048    let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2049    isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2050    isSuccess = isSuccess && BigInt(amount) === transfer.amount;2051    return isSuccess;2052  }2053}205420552056class AddressGroup extends HelperGroup {2057  /**2058   * Normalizes the address to the specified ss58 format, by default ```42```.2059   * @param address substrate address2060   * @param ss58Format format for address conversion, by default ```42```2061   * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2062   * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2063   */2064  normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2065    return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2066  }20672068  /**2069   * Normalizes the address of an account ONLY if it's Substrate to the specified ss58 format, by default ```42```.2070   * @param account account of either Substrate type or Ethereum, but only Substrate will be changed2071   * @param ss58Format format for address conversion, by default ```42```2072   * @example normalizeCrossAccountIfSubstrate({Substrate: "unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx"}) // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2073   * @returns untouched ethereum account or substrate account converted to normalized (i.e., starting with 5) or specified explicitly representation2074   */2075  normalizeCrossAccountIfSubstrate(account: ICrossAccountId, ss58Format = 42): ICrossAccountId  {2076    return account.Substrate2077      ? {Substrate: this.normalizeSubstrate(account.Substrate, ss58Format)}2078      : account;2079  }20802081  /**2082   * Get address in the connected chain format2083   * @param address substrate address2084   * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2085   * @returns address in chain format2086   */2087  async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2088    const info = this.helper.chain.getChainProperties();2089    return encodeAddress(decodeAddress(address), info.ss58Format);2090  }20912092  /**2093   * Get substrate mirror of an ethereum address2094   * @param ethAddress ethereum address2095   * @param toChainFormat false for normalized account2096   * @example ethToSubstrate('0x9F0583DbB855d...')2097   * @returns substrate mirror of a provided ethereum address2098   */2099  async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2100    if(!toChainFormat) return evmToAddress(ethAddress);2101    const info = this.helper.chain.getChainProperties();2102    return evmToAddress(ethAddress, info.ss58Format);2103  }21042105  /**2106   * Get ethereum mirror of a substrate address2107   * @param subAddress substrate account2108   * @example substrateToEth("5DnSF6RRjwteE3BrC...")2109   * @returns ethereum mirror of a provided substrate address2110   */2111  substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2112    return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2113  }2114}21152116class StakingGroup extends HelperGroup {2117  /**2118   * Stake tokens for App Promotion2119   * @param signer keyring of signer2120   * @param amountToStake amount of tokens to stake2121   * @param label extra label for log2122   * @returns2123   */2124  async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2125    if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2126    const stakeResult = await this.helper.executeExtrinsic(2127      signer, 'api.tx.appPromotion.stake',2128      [amountToStake], true,2129    );2130    // TODO extract info from stakeResult2131    return true;2132  }21332134  /**2135   * Unstake tokens for App Promotion2136   * @param signer keyring of signer2137   * @param amountToUnstake amount of tokens to unstake2138   * @param label extra label for log2139   * @returns block number where balances will be unlocked2140   */2141  async unstake(signer: TSigner, label?: string): Promise<number> {2142    if(typeof label === 'undefined') label = `${signer.address}`;2143    const unstakeResult = await this.helper.executeExtrinsic(2144      signer, 'api.tx.appPromotion.unstake',2145      [], true,2146    );2147    // TODO extract block number fron events2148    return 1;2149  }21502151  /**2152   * Get total staked amount for address2153   * @param address substrate or ethereum address2154   * @returns total staked amount2155   */2156  async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2157    if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2158    return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2159  }21602161  /**2162   * Get total staked per block2163   * @param address substrate or ethereum address2164   * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2165   */2166  async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2167    const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2168    return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2169      return { 2170        block: block.toBigInt(),2171        amount: amount.toBigInt(),2172      };2173    });2174  }21752176  /**2177   * Get total pending unstake amount for address2178   * @param address substrate or ethereum address2179   * @returns total pending unstake amount2180   */2181  async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2182    return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2183  }21842185  /**2186   * Get pending unstake amount per block for address2187   * @param address substrate or ethereum address2188   * @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 block2189   */2190  async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2191    const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2192    const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2193      return {2194        block: block.toBigInt(),2195        amount: amount.toBigInt(),2196      };2197    });2198    return result;2199  }2200}22012202export class UniqueHelper extends ChainHelperBase {2203  chain: ChainGroup;2204  balance: BalanceGroup;2205  address: AddressGroup;2206  collection: CollectionGroup;2207  nft: NFTGroup;2208  rft: RFTGroup;2209  ft: FTGroup;2210  staking: StakingGroup;22112212  constructor(logger?: ILogger) {2213    super(logger);2214    this.chain = new ChainGroup(this);2215    this.balance = new BalanceGroup(this);2216    this.address = new AddressGroup(this);2217    this.collection = new CollectionGroup(this);2218    this.nft = new NFTGroup(this);2219    this.rft = new RFTGroup(this);2220    this.ft = new FTGroup(this);2221    this.staking = new StakingGroup(this);2222  }2223}222422252226class UniqueCollectionBase implements ICollectionBase {2227  helper: UniqueHelper;2228  collectionId: number;22292230  constructor(collectionId: number, uniqueHelper: UniqueHelper) {2231    this.collectionId = collectionId;2232    this.helper = uniqueHelper;2233  }22342235  async getData() {2236    return await this.helper.collection.getData(this.collectionId);2237  }22382239  async getLastTokenId() {2240    return await this.helper.collection.getLastTokenId(this.collectionId);2241  }22422243  async isTokenExists(tokenId: number) {2244    return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2245  }22462247  async getAdmins() {2248    return await this.helper.collection.getAdmins(this.collectionId);2249  }22502251  async getAllowList() {2252    return await this.helper.collection.getAllowList(this.collectionId);2253  }22542255  async getEffectiveLimits() {2256    return await this.helper.collection.getEffectiveLimits(this.collectionId);2257  }22582259  async getProperties(propertyKeys: string[] | null = null) {2260    return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2261  }22622263  async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2264    return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2265  }22662267  async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2268    return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2269  }22702271  async confirmSponsorship(signer: TSigner) {2272    return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2273  }22742275  async removeSponsor(signer: TSigner) {2276    return await this.helper.collection.removeSponsor(signer, this.collectionId);2277  }22782279  async setLimits(signer: TSigner, limits: ICollectionLimits) {2280    return await this.helper.collection.setLimits(signer, this.collectionId, limits);2281  }22822283  async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2284    return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2285  }22862287  async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2288    return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2289  }22902291  async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2292    return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2293  }22942295  async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2296    return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2297  }22982299  async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2300    return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2301  }23022303  async setProperties(signer: TSigner, properties: IProperty[]) {2304    return await this.helper.collection.setProperties(signer, this.collectionId, properties);2305  }23062307  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2308    return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2309  }23102311  async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2312    return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2313  }23142315  async enableNesting(signer: TSigner, permissions: INestingPermissions) {2316    return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2317  }23182319  async disableNesting(signer: TSigner) {2320    return await this.helper.collection.disableNesting(signer, this.collectionId);2321  }23222323  async burn(signer: TSigner) {2324    return await this.helper.collection.burn(signer, this.collectionId);2325  }2326}232723282329class UniqueNFTCollection extends UniqueCollectionBase implements ICollectionNFT {2330  getTokenObject(tokenId: number) {2331    return new UniqueNFTToken(tokenId, this);2332  }23332334  async getTokensByAddress(addressObj: ICrossAccountId) {2335    return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2336  }23372338  async getToken(tokenId: number, blockHashAt?: string) {2339    return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2340  }23412342  async getTokenOwner(tokenId: number, blockHashAt?: string) {2343    return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2344  }23452346  async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2347    return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2348  }23492350  async getTokenChildren(tokenId: number, blockHashAt?: string) {2351    return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2352  }23532354  async getPropertyPermissions(propertyKeys: string[] | null = null) {2355    return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2356  }23572358  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2359    return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2360  }23612362  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2363    return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2364  }23652366  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2367    return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2368  }23692370  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2371    return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2372  }23732374  async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2375    return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2376  }23772378  async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2379    return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2380  }23812382  async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2383    return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2384  }23852386  async burnToken(signer: TSigner, tokenId: number) {2387    return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2388  }23892390  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2391    return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2392  }23932394  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2395    return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2396  }23972398  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2399    return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2400  }24012402  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2403    return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2404  }24052406  async nestToken(signer: TSigner, tokenId: number, toTokenObj: ITokenAddress) {2407    return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2408  }24092410  async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) {2411    return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2412  }2413}241424152416class UniqueRFTCollection extends UniqueCollectionBase implements ICollectionRFT {2417  getTokenObject(tokenId: number) {2418    return new UniqueRFTToken(tokenId, this);2419  }24202421  async getToken(tokenId: number, blockHashAt?: string) {2422    return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2423  }24242425  async getTokensByAddress(addressObj: ICrossAccountId) {2426    return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2427  }24282429  async getTop10TokenOwners(tokenId: number) {2430    return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2431  }24322433  async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2434    return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2435  }24362437  async getTokenTotalPieces(tokenId: number) {2438    return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2439  }24402441  async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2442    return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2443  }24442445  async getPropertyPermissions(propertyKeys: string[] | null = null) {2446    return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2447  }24482449  async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2450    return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2451  }24522453  async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2454    return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2455  }24562457  async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2458    return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2459  }24602461  async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2462    return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2463  }24642465  async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2466    return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2467  }24682469  async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2470    return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2471  }24722473  async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2474    return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2475  }24762477  async burnToken(signer: TSigner, tokenId: number, amount=1n) {2478    return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2479  }24802481  async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId,  amount=1n) {2482    return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2483  }24842485  async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2486    return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2487  }24882489  async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2490    return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2491  }24922493  async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2494    return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2495  }2496}249724982499class UniqueFTCollection extends UniqueCollectionBase implements ICollectionFT {2500  async getBalance(addressObj: ICrossAccountId) {2501    return await this.helper.ft.getBalance(this.collectionId, addressObj);2502  }25032504  async getTotalPieces() {2505    return await this.helper.ft.getTotalPieces(this.collectionId);2506  }25072508  async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2509    return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2510  }25112512  async getTop10Owners() {2513    return await this.helper.ft.getTop10Owners(this.collectionId);2514  }25152516  async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2517    return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2518  }25192520  async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2521    return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2522  }25232524  async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2525    return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2526  }25272528  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2529    return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2530  }25312532  async burnTokens(signer: TSigner, amount=1n) {2533    return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2534  }25352536  async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2537    return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2538  }25392540  async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2541    return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2542  }2543}254425452546class UniqueTokenBase implements ITokenBase {2547  collection: UniqueNFTCollection | UniqueRFTCollection;2548  collectionId: number;2549  tokenId: number;25502551  constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2552    this.collection = collection;2553    this.collectionId = collection.collectionId;2554    this.tokenId = tokenId;2555  }25562557  async getNextSponsored(addressObj: ICrossAccountId) {2558    return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2559  }25602561  async getProperties(propertyKeys: string[] | null = null) {2562    return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2563  }25642565  async setProperties(signer: TSigner, properties: IProperty[]) {2566    return await this.collection.setTokenProperties(signer, this.tokenId, properties);2567  }25682569  async deleteProperties(signer: TSigner, propertyKeys: string[]) {2570    return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2571  }25722573  nestingAccount() {2574    return this.collection.helper.util.getTokenAccount(this);2575  }25762577  nestingAccountInLowerCase() {2578    return this.collection.helper.util.getTokenAccountInLowerCase(this);2579  }2580}258125822583class UniqueNFTToken extends UniqueTokenBase implements ITokenNonfungible {2584  collection: UniqueNFTCollection;25852586  constructor(tokenId: number, collection: UniqueNFTCollection) {2587    super(tokenId, collection);2588    this.collection = collection;2589  }25902591  async getData(blockHashAt?: string) {2592    return await this.collection.getToken(this.tokenId, blockHashAt);2593  }25942595  async getOwner(blockHashAt?: string) {2596    return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2597  }25982599  async getTopmostOwner(blockHashAt?: string) {2600    return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2601  }26022603  async getChildren(blockHashAt?: string) {2604    return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2605  }26062607  async nest(signer: TSigner, toTokenObj: ITokenAddress) {2608    return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2609  }26102611  async unnest(signer: TSigner, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) {2612    return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2613  }26142615  async transfer(signer: TSigner, addressObj: ICrossAccountId) {2616    return await this.collection.transferToken(signer, this.tokenId, addressObj);2617  }26182619  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2620    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2621  }26222623  async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2624    return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2625  }26262627  async isApproved(toAddressObj: ICrossAccountId) {2628    return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2629  }26302631  async burn(signer: TSigner) {2632    return await this.collection.burnToken(signer, this.tokenId);2633  }26342635  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2636    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2637  }2638}26392640class UniqueRFTToken extends UniqueTokenBase implements ITokenRefungible {2641  collection: UniqueRFTCollection;26422643  constructor(tokenId: number, collection: UniqueRFTCollection) {2644    super(tokenId, collection);2645    this.collection = collection;2646  }26472648  async getData(blockHashAt?: string) {2649    return await this.collection.getToken(this.tokenId, blockHashAt);2650  }26512652  async getTop10Owners() {2653    return await this.collection.getTop10TokenOwners(this.tokenId);2654  }26552656  async getBalance(addressObj: ICrossAccountId) {2657    return await this.collection.getTokenBalance(this.tokenId, addressObj);2658  }26592660  async getTotalPieces() {2661    return await this.collection.getTokenTotalPieces(this.tokenId);2662  }26632664  async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2665    return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2666  }26672668  async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2669    return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2670  }26712672  async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2673    return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2674  }26752676  async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2677    return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2678  }26792680  async repartition(signer: TSigner, amount: bigint) {2681    return await this.collection.repartitionToken(signer, this.tokenId, amount);2682  }26832684  async burn(signer: TSigner, amount=1n) {2685    return await this.collection.burnToken(signer, this.tokenId, amount);2686  }26872688  async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2689    return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2690  }2691}