difftreelog
Tests: code-style fixes
in: master
14 files changed
tests/src/addCollectionAdmin.test.tsdiffbeforeafterboth--- a/tests/src/addCollectionAdmin.test.ts
+++ b/tests/src/addCollectionAdmin.test.ts
@@ -110,7 +110,7 @@
const [alice, ...accounts] = await helper.arrange.createAccounts([10n, 0n, 0n, 0n, 0n, 0n, 0n, 0n], donor);
const collection = await helper.nft.mintCollection(alice, {name: 'Collection Name', description: 'Collection Description', tokenPrefix: 'COL'});
- const chainAdminLimit = (helper.api!.consts.common.collectionAdminsLimit as any).toNumber();
+ const chainAdminLimit = (helper.getApi().consts.common.collectionAdminsLimit as any).toNumber();
expect(chainAdminLimit).to.be.equal(5);
for (let i = 0; i < chainAdminLimit; i++) {
tests/src/approve.test.tsdiffbeforeafterboth--- a/tests/src/approve.test.ts
+++ b/tests/src/approve.test.ts
@@ -60,7 +60,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
});
@@ -275,7 +275,7 @@
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: alice.address});
await helper.nft.approveToken(alice, collectionId, tokenId, {Substrate: bob.address});
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.true;
- await helper.signTransaction(alice, helper.api?.tx.unique.approve({Substrate: bob.address}, collectionId, tokenId, 0));
+ await helper.signTransaction(alice, helper.constructApiCall('api.tx.unique.approve', [{Substrate: bob.address}, collectionId, tokenId, 0]));
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: bob.address})).to.be.false;
const transferTokenFromTx = async () => helper.nft.transferTokenFrom(bob, collectionId, tokenId, {Substrate: bob.address}, {Substrate: bob.address});
await expect(transferTokenFromTx()).to.be.rejected;
@@ -328,7 +328,7 @@
itSub('1 for NFT', async ({helper}) => {
const {collectionId} = await helper.nft.mintCollection(alice, {name: 'col', description: 'descr', tokenPrefix: 'COL'});
const {tokenId} = await helper.nft.mintToken(alice, {collectionId: collectionId, owner: bob.address});
- const approveTx = async () => helper.signTransaction(bob, helper.api?.tx.unique.approve({Substrate: charlie.address}, collectionId, tokenId, 2));
+ const approveTx = async () => helper.signTransaction(bob, helper.constructApiCall('api.tx.unique.approve', [{Substrate: charlie.address}, collectionId, tokenId, 2]));
await expect(approveTx()).to.be.rejected;
expect(await helper.nft.isTokenApproved(collectionId, tokenId, {Substrate: charlie.address})).to.be.false;
});
tests/src/block-production.test.tsdiffbeforeafterboth--- a/tests/src/block-production.test.ts
+++ b/tests/src/block-production.test.ts
@@ -37,7 +37,7 @@
describe('Block Production smoke test', () => {
itSub('Node produces new blocks', async ({helper}) => {
- const blocks: number[] | undefined = await getBlocks(helper.api!);
+ const blocks: number[] | undefined = await getBlocks(helper.getApi());
expect(blocks[0]).to.be.lessThan(blocks[1]);
});
});
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -178,13 +178,12 @@
tokenPrefix: 'COL',
}, 0);
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx',[collection.collectionId, {
Fungible: new Map([
[JSON.stringify({Substrate: alice.address}), 50],
[JSON.stringify({Substrate: bob.address}), 100],
]),
- }));
+ }], true);
expect(await collection.getBalance({Substrate: alice.address})).to.be.equal(50n);
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(100n);
@@ -200,8 +199,7 @@
],
});
- const api = helper.api;
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleOwners: {
users: new Map([
[JSON.stringify({Substrate: alice.address}), 1],
@@ -211,7 +209,7 @@
{key: 'k', value: 'v'},
],
},
- }));
+ }], true);
const tokenId = await collection.getLastTokenId();
expect(tokenId).to.be.equal(1);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
@@ -228,9 +226,7 @@
],
});
- const api = helper.api;
-
- await helper.signTransaction(alice, api?.tx.unique.createMultipleItemsEx(collection.collectionId, {
+ await helper.executeExtrinsic(alice, 'api.tx.unique.createMultipleItemsEx', [collection.collectionId, {
RefungibleMultipleItems: [
{
user: {Substrate: alice.address}, pieces: 1,
@@ -245,7 +241,7 @@
],
},
],
- }));
+ }], true);
expect(await collection.getLastTokenId()).to.be.equal(2);
expect(await collection.getTokenBalance(1, {Substrate: alice.address})).to.be.equal(1n);
tests/src/creditFeesToTreasury.test.tsdiffbeforeafterboth--- a/tests/src/creditFeesToTreasury.test.ts
+++ b/tests/src/creditFeesToTreasury.test.ts
@@ -70,7 +70,7 @@
});
itSub('Sender balance decreased by fee+sent amount, Treasury balance increased by fee', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -89,7 +89,7 @@
});
itSub('Treasury balance increased by failed tx fee', async ({helper}) => {
- const api = helper.api!;
+ const api = helper.getApi();
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -107,7 +107,7 @@
});
itSub('NFT Transactions also send fees to Treasury', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const treasuryBalanceBefore = await helper.balance.getSubstrate(TREASURY);
@@ -125,7 +125,7 @@
itSub('Fees are sane', async ({helper}) => {
const unique = helper.balance.getOneTokenNominal();
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const aliceBalanceBefore = await helper.balance.getSubstrate(alice.address);
@@ -140,7 +140,7 @@
});
itSub('NFT Transfer fee is close to 0.1 Unique', async ({helper}) => {
- await skipInflationBlock(helper.api!);
+ await skipInflationBlock(helper.getApi());
await helper.wait.newBlocks(1);
const collection = await helper.nft.mintCollection(alice, {
tests/src/eth/createNFTCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createNFTCollection.test.ts
+++ b/tests/src/eth/createNFTCollection.test.ts
@@ -152,7 +152,7 @@
before(async function() {
await usingEthPlaygrounds(async (helper, privateKey) => {
donor = privateKey('//Alice');
- nominal = helper.balance.getOneTokenNominal()
+ nominal = helper.balance.getOneTokenNominal();
});
});
tests/src/eth/proxy/nonFungibleProxy.test.tsdiffbeforeafterboth--- a/tests/src/eth/proxy/nonFungibleProxy.test.ts
+++ b/tests/src/eth/proxy/nonFungibleProxy.test.ts
@@ -138,23 +138,16 @@
});
//TODO: CORE-302 add eth methods
- itEth.skip('Can perform mintBulk()', async ({helper, privateKey}) => {
- const api = helper.getApi();
- const web3 = helper.getWeb3();
- const privateKeyWrapper = privateKey;
- /*
- const collection = await createCollectionExpectSuccess({
- mode: {type: 'NFT'},
- });
- const alice = privateKeyWrapper('//Alice');
+ itEth.skip('Can perform mintBulk()', async ({helper}) => {
+ const collection = await helper.nft.mintCollection(donor, {name: 'New', description: 'New collection', tokenPrefix: 'NEW'});
- const caller = await createEthAccountWithBalance(api, web3, privateKeyWrapper);
- const receiver = createEthAccount(web3);
+ const caller = await helper.eth.createAccountWithBalance(donor, 30n);
+ const receiver = helper.eth.createAccount();
- const address = collectionIdToAddress(collection);
- const contract = await proxyWrap(api, web3, new web3.eth.Contract(nonFungibleAbi as any, address, {from: caller, ...GAS_ARGS}), privateKeyWrapper);
- const changeAdminTx = api.tx.unique.addCollectionAdmin(collection, {Ethereum: contract.options.address});
- await submitTransactionAsync(alice, changeAdminTx);
+ const address = helper.ethAddress.fromCollectionId(collection.collectionId);
+ const evmCollection = helper.ethNativeContract.collection(address, 'nft', caller);
+ const contract = await proxyWrap(helper, evmCollection, donor);
+ await collection.addAdmin(donor, {Ethereum: contract.options.address});
{
const nextTokenId = await contract.methods.nextTokenId().call();
@@ -167,7 +160,7 @@
[+nextTokenId + 2, 'Test URI 2'],
],
).send({from: caller});
- const events = normalizeEvents(result.events);
+ const events = helper.eth.normalizeEvents(result.events);
expect(events).to.be.deep.equal([
{
@@ -203,7 +196,6 @@
expect(await contract.methods.tokenURI(+nextTokenId + 1).call()).to.be.equal('Test URI 1');
expect(await contract.methods.tokenURI(+nextTokenId + 2).call()).to.be.equal('Test URI 2');
}
- */
});
itEth('Can perform burn()', async ({helper}) => {
tests/src/eth/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/eth/util/playgrounds/unique.dev.ts
+++ b/tests/src/eth/util/playgrounds/unique.dev.ts
@@ -285,8 +285,8 @@
await code();
// In dev mode, the transaction might not finish processing in time
await this.helper.wait.newBlocks(1);
- }
- return await this.helper.arrange.calculcateFee(address, code);
+ };
+ return await this.helper.arrange.calculcateFee(address, wrappedCode);
}
}
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -40,9 +40,9 @@
const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
- const blockInterval = (helper.api!.consts.inflation.inflationBlockInterval as any).toBigInt();
- const totalIssuanceStart = ((await helper.api!.query.inflation.startingYearTotalIssuance()) as any).toBigInt();
- const blockInflation = (await helper.api!.query.inflation.blockInflation() as any).toBigInt();
+ const blockInterval = (helper.getApi().consts.inflation.inflationBlockInterval as any).toBigInt();
+ const totalIssuanceStart = ((await helper.callRpc('api.query.inflation.startingYearTotalIssuance', [])) as any).toBigInt();
+ const blockInflation = (await helper.callRpc('api.query.inflation.blockInflation', []) as any).toBigInt();
const YEAR = 5259600n; // 6-second block. Blocks in one year
// const YEAR = 2629800n; // 12-second block. Blocks in one year
tests/src/nesting/properties.test.tsdiffbeforeafterboth--- a/tests/src/nesting/properties.test.ts
+++ b/tests/src/nesting/properties.test.ts
@@ -276,7 +276,7 @@
itSub('Reads access rights to properties of a collection', async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
- const propertyRights = (await helper.api!.query.common.collectionPropertyPermissions(collection.collectionId)).toJSON();
+ const propertyRights = (await helper.callRpc('api.query.common.collectionPropertyPermissions', [collection.collectionId])).toJSON();
expect(propertyRights).to.be.empty;
});
@@ -817,7 +817,7 @@
).to.be.fulfilled;
}
- const originalSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const originalSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
return originalSpace;
}
@@ -840,7 +840,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -875,7 +875,7 @@
).to.be.rejectedWith(/common\.NoPermission/);
}
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -911,7 +911,7 @@
expect(await token.getProperties(['non-existent', 'now-existent'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
@@ -951,7 +951,7 @@
])).to.be.rejectedWith(/common\.NoSpaceForProperty/);
expect(await token.getProperties(['a_holy_book', 'young_years'])).to.be.empty;
- const consumedSpace = await getConsumedSpace(token.collection.helper.api, token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
+ const consumedSpace = await getConsumedSpace(token.collection.helper.getApi(), token.collectionId, token.tokenId, pieces == 1n ? 'NFT' : 'RFT');
expect(consumedSpace).to.be.equal(originalSpace);
}
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -59,7 +59,7 @@
describe('Pallet presence', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- const chain = await helper.api!.rpc.system.chain();
+ const chain = await helper.callRpc('api.rpc.system.chain', []);
const refungible = 'refungible';
const scheduler = 'scheduler';
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- a/tests/src/tx-version-presence.test.ts
+++ b/tests/src/tx-version-presence.test.ts
@@ -22,7 +22,7 @@
describe('TxVersion is present', () => {
before(async () => {
await usingPlaygrounds(async helper => {
- metadata = await helper.api!.rpc.state.getMetadata();
+ metadata = await helper.callRpc('api.rpc.state.getMetadata', []);
});
});
tests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -215,8 +215,8 @@
};
isDevNode = async () => {
- const block1 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(1));
- const block2 = await this.helper.api?.rpc.chain.getBlock(await this.helper.api?.rpc.chain.getBlockHash(2));
+ const block1 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [1])]);
+ const block2 = await this.helper.callRpc('api.rpc.chain.getBlock', [await this.helper.callRpc('api.rpc.chain.getBlockHash', [2])]);
const findCreationDate = async (block: any) => {
const humanBlock = block.toHuman();
let date;
@@ -259,7 +259,7 @@
async newBlocks(blocksCount = 1): Promise<void> {
// eslint-disable-next-line no-async-promise-executor
const promise = new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(() => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(() => {
if (blocksCount > 0) {
blocksCount--;
} else {
@@ -274,7 +274,7 @@
async forParachainBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.rpc.chain.subscribeNewHeads(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().rpc.chain.subscribeNewHeads(async (data: any) => {
if (data.number.toNumber() >= blockNumber) {
unsubscribe();
resolve();
@@ -286,7 +286,7 @@
async forRelayBlockNumber(blockNumber: bigint) {
// eslint-disable-next-line no-async-promise-executor
return new Promise<void>(async (resolve) => {
- const unsubscribe = await this.helper.api!.query.parachainSystem.validationData(async (data: any) => {
+ const unsubscribe = await this.helper.getApi().query.parachainSystem.validationData(async (data: any) => {
if (data.value.relayParentNumber.toNumber() >= blockNumber) {
// @ts-ignore
unsubscribe();
tests/src/util/playgrounds/unique.tsdiffbeforeafterboth1// 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 class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 // If ith character is 8 to f then make it uppercase84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321322 constructor(logger?: ILogger) {323 this.util = UniqueUtil;324 this.eventHelper = UniqueEventHelper;325 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();326 this.logger = logger;327 this.api = null;328 this.forcedNetwork = null;329 this.network = null;330 this.chainLog = [];331 }332333 getApi(): ApiPromise {334 if(this.api === null) throw Error('API not initialized');335 return this.api;336 }337338 clearChainLog(): void {339 this.chainLog = [];340 }341342 forceNetwork(value: TUniqueNetworks): void {343 this.forcedNetwork = value;344 }345346 async connect(wsEndpoint: string, listeners?: IApiListeners) {347 if (this.api !== null) throw Error('Already connected');348 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);349 this.api = api;350 this.network = network;351 }352353 async disconnect() {354 if (this.api === null) return;355 await this.api.disconnect();356 this.api = null;357 this.network = null;358 }359360 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {361 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;362 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;363 return 'opal';364 }365366 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {367 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});368 await api.isReady;369370 const network = await this.detectNetwork(api);371372 await api.disconnect();373374 return network;375 }376377 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{378 api: ApiPromise;379 network: TUniqueNetworks;380 }> {381 if(typeof network === 'undefined' || network === null) network = 'opal';382 const supportedRPC = {383 opal: {384 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,385 },386 quartz: {387 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,388 },389 unique: {390 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,391 },392 };393 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);394 const rpc = supportedRPC[network];395396 // TODO: investigate how to replace rpc in runtime397 // api._rpcCore.addUserInterfaces(rpc);398399 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});400401 await api.isReadyOrError;402403 if (typeof listeners === 'undefined') listeners = {};404 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {405 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;406 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);407 }408409 return {api, network};410 }411412 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {413 const {events, status} = data;414 if (status.isReady) {415 return this.transactionStatus.NOT_READY;416 }417 if (status.isBroadcast) {418 return this.transactionStatus.NOT_READY;419 }420 if (status.isInBlock || status.isFinalized) {421 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');422 if (errors.length > 0) {423 return this.transactionStatus.FAIL;424 }425 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {426 return this.transactionStatus.SUCCESS;427 }428 }429430 return this.transactionStatus.FAIL;431 }432433 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {434 const sign = (callback: any) => {435 if(options !== null) return transaction.signAndSend(sender, options, callback);436 return transaction.signAndSend(sender, callback);437 };438 // eslint-disable-next-line no-async-promise-executor439 return new Promise(async (resolve, reject) => {440 try {441 const unsub = await sign((result: any) => {442 const status = this.getTransactionStatus(result);443444 if (status === this.transactionStatus.SUCCESS) {445 this.logger.log(`${label} successful`);446 unsub();447 resolve({result, status});448 } else if (status === this.transactionStatus.FAIL) {449 let moduleError = null;450451 if (result.hasOwnProperty('dispatchError')) {452 const dispatchError = result['dispatchError'];453454 if (dispatchError) {455 if (dispatchError.isModule) {456 const modErr = dispatchError.asModule;457 const errorMeta = dispatchError.registry.findMetaError(modErr);458459 moduleError = `${errorMeta.section}.${errorMeta.name}`;460 } else {461 moduleError = dispatchError.toHuman();462 }463 } else {464 this.logger.log(result, this.logger.level.ERROR);465 }466 }467468 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);469 unsub();470 reject({status, moduleError, result});471 }472 });473 } catch (e) {474 this.logger.log(e, this.logger.level.ERROR);475 reject(e);476 }477 });478 }479480 constructApiCall(apiCall: string, params: any[]) {481 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);482 let call = this.api as any;483 for(const part of apiCall.slice(4).split('.')) {484 call = call[part];485 }486 return call(...params);487 }488489 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null/*, failureMessage='expected success'*/) {490 if(this.api === null) throw Error('API not initialized');491 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);492493 const startTime = (new Date()).getTime();494 let result: ITransactionResult;495 let events: IEvent[] = [];496 try {497 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;498 events = this.eventHelper.extractEvents(result);499 }500 catch(e) {501 if(!(e as object).hasOwnProperty('status')) throw e;502 result = e as ITransactionResult;503 }504505 const endTime = (new Date()).getTime();506507 const log = {508 executedAt: endTime,509 executionTime: endTime - startTime,510 type: this.chainLogType.EXTRINSIC,511 status: result.status,512 call: extrinsic,513 signer: this.getSignerAddress(sender),514 params,515 } as IUniqueHelperLog;516517 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;518 if(events.length > 0) log.events = events;519520 this.chainLog.push(log);521522 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);523 return result;524 }525526 async callRpc(rpc: string, params?: any[]) {527 if(typeof params === 'undefined') params = [];528 if(this.api === null) throw Error('API not initialized');529 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);530531 const startTime = (new Date()).getTime();532 let result;533 let error = null;534 const log = {535 type: this.chainLogType.RPC,536 call: rpc,537 params,538 } as IUniqueHelperLog;539540 try {541 result = await this.constructApiCall(rpc, params);542 }543 catch(e) {544 error = e;545 }546547 const endTime = (new Date()).getTime();548549 log.executedAt = endTime;550 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';551 log.executionTime = endTime - startTime;552553 this.chainLog.push(log);554555 if(error !== null) throw error;556557 return result;558 }559560 getSignerAddress(signer: IKeyringPair | string): string {561 if(typeof signer === 'string') return signer;562 return signer.address;563 }564565 fetchAllPalletNames(): string[] {566 if(this.api === null) throw Error('API not initialized');567 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());568 }569570 fetchMissingPalletNames(requiredPallets: string[]): string[] {571 const palletNames = this.fetchAllPalletNames();572 return requiredPallets.filter(p => !palletNames.includes(p));573 }574}575576577class HelperGroup {578 helper: UniqueHelper;579580 constructor(uniqueHelper: UniqueHelper) {581 this.helper = uniqueHelper;582 }583}584585586class CollectionGroup extends HelperGroup {587 /**588 * Get number of blocks when sponsored transaction is available.589 *590 * @param collectionId ID of collection591 * @param tokenId ID of token592 * @param addressObj address for which the sponsorship is checked593 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});594 * @returns number of blocks or null if sponsorship hasn't been set595 */596 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {597 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();598 }599600 /**601 * Get the number of created collections.602 *603 * @returns number of created collections604 */605 async getTotalCount(): Promise<number> {606 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();607 }608609 /**610 * Get information about the collection with additional data,611 * including the number of tokens it contains, its administrators,612 * the normalized address of the collection's owner, and decoded name and description.613 *614 * @param collectionId ID of collection615 * @example await getData(2)616 * @returns collection information object617 */618 async getData(collectionId: number): Promise<{619 id: number;620 name: string;621 description: string;622 tokensCount: number;623 admins: CrossAccountId[];624 normalizedOwner: TSubstrateAccount;625 raw: any626 } | null> {627 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);628 const humanCollection = collection.toHuman(), collectionData = {629 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],630 raw: humanCollection,631 } as any, jsonCollection = collection.toJSON();632 if (humanCollection === null) return null;633 collectionData.raw.limits = jsonCollection.limits;634 collectionData.raw.permissions = jsonCollection.permissions;635 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);636 for (const key of ['name', 'description']) {637 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);638 }639640 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))641 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)642 : 0;643 collectionData.admins = await this.getAdmins(collectionId);644645 return collectionData;646 }647648 /**649 * Get the addresses of the collection's administrators, optionally normalized.650 *651 * @param collectionId ID of collection652 * @param normalize whether to normalize the addresses to the default ss58 format653 * @example await getAdmins(1)654 * @returns array of administrators655 */656 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {657 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();658659 return normalize660 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())661 : admins;662 }663664 /**665 * Get the addresses added to the collection allow-list, optionally normalized.666 * @param collectionId ID of collection667 * @param normalize whether to normalize the addresses to the default ss58 format668 * @example await getAllowList(1)669 * @returns array of allow-listed addresses670 */671 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {672 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();673 return normalize674 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())675 : allowListed;676 }677678 /**679 * Get the effective limits of the collection instead of null for default values680 *681 * @param collectionId ID of collection682 * @example await getEffectiveLimits(2)683 * @returns object of collection limits684 */685 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {686 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();687 }688689 /**690 * Burns the collection if the signer has sufficient permissions and collection is empty.691 *692 * @param signer keyring of signer693 * @param collectionId ID of collection694 * @example await helper.collection.burn(aliceKeyring, 3);695 * @returns ```true``` if extrinsic success, otherwise ```false```696 */697 async burn(signer: TSigner, collectionId: number): Promise<boolean> {698 const result = await this.helper.executeExtrinsic(699 signer,700 'api.tx.unique.destroyCollection', [collectionId],701 true,702 );703704 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');705 }706707 /**708 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.709 *710 * @param signer keyring of signer711 * @param collectionId ID of collection712 * @param sponsorAddress Sponsor substrate address713 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")714 * @returns ```true``` if extrinsic success, otherwise ```false```715 */716 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {717 const result = await this.helper.executeExtrinsic(718 signer,719 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],720 true,721 );722723 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');724 }725726 /**727 * Confirms consent to sponsor the collection on behalf of the signer.728 *729 * @param signer keyring of signer730 * @param collectionId ID of collection731 * @example confirmSponsorship(aliceKeyring, 10)732 * @returns ```true``` if extrinsic success, otherwise ```false```733 */734 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {735 const result = await this.helper.executeExtrinsic(736 signer,737 'api.tx.unique.confirmSponsorship', [collectionId],738 true,739 );740741 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');742 }743744 /**745 * Removes the sponsor of a collection, regardless if it consented or not.746 *747 * @param signer keyring of signer748 * @param collectionId ID of collection749 * @example removeSponsor(aliceKeyring, 10)750 * @returns ```true``` if extrinsic success, otherwise ```false```751 */752 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {753 const result = await this.helper.executeExtrinsic(754 signer,755 'api.tx.unique.removeCollectionSponsor', [collectionId],756 true,757 );758759 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');760 }761762 /**763 * Sets the limits of the collection. At least one limit must be specified for a correct call.764 *765 * @param signer keyring of signer766 * @param collectionId ID of collection767 * @param limits collection limits object768 * @example769 * await setLimits(770 * aliceKeyring,771 * 10,772 * {773 * sponsorTransferTimeout: 0,774 * ownerCanDestroy: false775 * }776 * )777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.setCollectionLimits', [collectionId, limits],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');787 }788789 /**790 * Changes the owner of the collection to the new Substrate address.791 *792 * @param signer keyring of signer793 * @param collectionId ID of collection794 * @param ownerAddress substrate address of new owner795 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")796 * @returns ```true``` if extrinsic success, otherwise ```false```797 */798 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {799 const result = await this.helper.executeExtrinsic(800 signer,801 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],802 true,803 );804805 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');806 }807808 /**809 * Adds a collection administrator.810 *811 * @param signer keyring of signer812 * @param collectionId ID of collection813 * @param adminAddressObj Administrator address (substrate or ethereum)814 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})815 * @returns ```true``` if extrinsic success, otherwise ```false```816 */817 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {818 const result = await this.helper.executeExtrinsic(819 signer,820 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],821 true,822 );823824 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');825 }826827 /**828 * Removes a collection administrator.829 *830 * @param signer keyring of signer831 * @param collectionId ID of collection832 * @param adminAddressObj Administrator address (substrate or ethereum)833 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})834 * @returns ```true``` if extrinsic success, otherwise ```false```835 */836 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {837 const result = await this.helper.executeExtrinsic(838 signer,839 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],840 true,841 );842843 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');844 }845846 /**847 * Check if user is in allow list.848 * 849 * @param collectionId ID of collection850 * @param user Account to check851 * @example await getAdmins(1)852 * @returns is user in allow list853 */854 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {855 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();856 }857858 /**859 * Adds an address to allow list860 * @param signer keyring of signer861 * @param collectionId ID of collection862 * @param addressObj address to add to the allow list863 * @returns ```true``` if extrinsic success, otherwise ```false```864 */865 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {866 const result = await this.helper.executeExtrinsic(867 signer,868 'api.tx.unique.addToAllowList', [collectionId, addressObj],869 true,870 );871872 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');873 }874875 /**876 * Removes an address from allow list877 *878 * @param signer keyring of signer879 * @param collectionId ID of collection880 * @param addressObj address to remove from the allow list881 * @returns ```true``` if extrinsic success, otherwise ```false```882 */883 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {884 const result = await this.helper.executeExtrinsic(885 signer,886 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],887 true,888 );889890 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');891 }892893 /**894 * Sets onchain permissions for selected collection.895 *896 * @param signer keyring of signer897 * @param collectionId ID of collection898 * @param permissions collection permissions object899 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});900 * @returns ```true``` if extrinsic success, otherwise ```false```901 */902 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {903 const result = await this.helper.executeExtrinsic(904 signer,905 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],906 true,907 );908909 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');910 }911912 /**913 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.914 *915 * @param signer keyring of signer916 * @param collectionId ID of collection917 * @param permissions nesting permissions object918 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});919 * @returns ```true``` if extrinsic success, otherwise ```false```920 */921 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {922 return await this.setPermissions(signer, collectionId, {nesting: permissions});923 }924925 /**926 * Disables nesting for selected collection.927 *928 * @param signer keyring of signer929 * @param collectionId ID of collection930 * @example disableNesting(aliceKeyring, 10);931 * @returns ```true``` if extrinsic success, otherwise ```false```932 */933 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {934 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});935 }936937 /**938 * Sets onchain properties to the collection.939 *940 * @param signer keyring of signer941 * @param collectionId ID of collection942 * @param properties array of property objects943 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);944 * @returns ```true``` if extrinsic success, otherwise ```false```945 */946 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {947 const result = await this.helper.executeExtrinsic(948 signer,949 'api.tx.unique.setCollectionProperties', [collectionId, properties],950 true,951 );952953 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');954 }955956 /**957 * Get collection properties.958 * 959 * @param collectionId ID of collection960 * @param propertyKeys optionally filter the returned properties to only these keys961 * @example getProperties(1219, ['location', 'date', 'time', 'isParadise']);962 * @returns array of key-value pairs963 */964 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {965 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();966 }967968 /**969 * Deletes onchain properties from the collection.970 *971 * @param signer keyring of signer972 * @param collectionId ID of collection973 * @param propertyKeys array of property keys to delete974 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);975 * @returns ```true``` if extrinsic success, otherwise ```false```976 */977 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {978 const result = await this.helper.executeExtrinsic(979 signer,980 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],981 true,982 );983984 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');985 }986987 /**988 * Changes the owner of the token.989 *990 * @param signer keyring of signer991 * @param collectionId ID of collection992 * @param tokenId ID of token993 * @param addressObj address of a new owner994 * @param amount amount of tokens to be transfered. For NFT must be set to 1n995 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})996 * @returns true if the token success, otherwise false997 */998 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {999 const result = await this.helper.executeExtrinsic(1000 signer,1001 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1002 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1003 );10041005 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1006 }10071008 /**1009 *1010 * Change ownership of a token(s) on behalf of the owner.1011 *1012 * @param signer keyring of signer1013 * @param collectionId ID of collection1014 * @param tokenId ID of token1015 * @param fromAddressObj address on behalf of which the token will be sent1016 * @param toAddressObj new token owner1017 * @param amount amount of tokens to be transfered. For NFT must be set to 1n1018 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})1019 * @returns true if the token success, otherwise false1020 */1021 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1022 const result = await this.helper.executeExtrinsic(1023 signer,1024 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1025 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,1026 );1027 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1028 }10291030 /**1031 *1032 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.1033 *1034 * @param signer keyring of signer1035 * @param collectionId ID of collection1036 * @param tokenId ID of token1037 * @param amount amount of tokens to be burned. For NFT must be set to 1n1038 * @example burnToken(aliceKeyring, 10, 5);1039 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1040 */1041 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1042 const burnResult = await this.helper.executeExtrinsic(1043 signer,1044 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1045 true, // `Unable to burn token for ${label}`,1046 );1047 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1048 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1049 return burnedTokens.success;1050 }10511052 /**1053 * Destroys a concrete instance of NFT on behalf of the owner1054 *1055 * @param signer keyring of signer1056 * @param collectionId ID of collection1057 * @param tokenId ID of token1058 * @param fromAddressObj address on behalf of which the token will be burnt1059 * @param amount amount of tokens to be burned. For NFT must be set to 1n1060 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})1061 * @returns ```true``` if extrinsic success, otherwise ```false```1062 */1063 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1064 const burnResult = await this.helper.executeExtrinsic(1065 signer,1066 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1067 true, // `Unable to burn token from for ${label}`,1068 );1069 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1070 return burnedTokens.success && burnedTokens.tokens.length > 0;1071 }10721073 /**1074 * Set, change, or remove approved address to transfer the ownership of the NFT.1075 *1076 * @param signer keyring of signer1077 * @param collectionId ID of collection1078 * @param tokenId ID of token1079 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1080 * @param amount amount of token to be approved. For NFT must be set to 1n1081 * @returns ```true``` if extrinsic success, otherwise ```false```1082 */1083 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1084 const approveResult = await this.helper.executeExtrinsic(1085 signer,1086 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1087 true, // `Unable to approve token for ${label}`,1088 );10891090 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1091 }10921093 /**1094 * Get the amount of token pieces approved to transfer or burn. Normally 0.1095 *1096 * @param collectionId ID of collection1097 * @param tokenId ID of token1098 * @param toAccountObj address which is approved to use token pieces1099 * @param fromAccountObj address which may have allowed the use of its owned tokens1100 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1101 * @returns number of approved to transfer pieces1102 */1103 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1104 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1105 }11061107 /**1108 * Get the last created token ID in a collection1109 *1110 * @param collectionId ID of collection1111 * @example getLastTokenId(10);1112 * @returns id of the last created token1113 */1114 async getLastTokenId(collectionId: number): Promise<number> {1115 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1116 }11171118 /**1119 * Check if token exists1120 *1121 * @param collectionId ID of collection1122 * @param tokenId ID of token1123 * @example doesTokenExist(10, 20);1124 * @returns true if the token exists, otherwise false1125 */1126 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1127 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1128 }1129}11301131class NFTnRFT extends CollectionGroup {1132 /**1133 * Get tokens owned by account1134 *1135 * @param collectionId ID of collection1136 * @param addressObj tokens owner1137 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1138 * @returns array of token ids owned by account1139 */1140 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1141 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1142 }11431144 /**1145 * Get token data1146 *1147 * @param collectionId ID of collection1148 * @param tokenId ID of token1149 * @param propertyKeys optionally filter the token properties to only these keys1150 * @param blockHashAt optionally query the data at some block with this hash1151 * @example getToken(10, 5);1152 * @returns human readable token data1153 */1154 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1155 properties: IProperty[];1156 owner: CrossAccountId;1157 normalizedOwner: CrossAccountId;1158 }| null> {1159 let tokenData;1160 if(typeof blockHashAt === 'undefined') {1161 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1162 }1163 else {1164 if(propertyKeys.length == 0) {1165 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1166 if(!collection) return null;1167 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1168 }1169 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1170 }1171 tokenData = tokenData.toHuman();1172 if (tokenData === null || tokenData.owner === null) return null;1173 const owner = {} as any;1174 for (const key of Object.keys(tokenData.owner)) {1175 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1176 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1177 : tokenData.owner[key];1178 }1179 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1180 return tokenData;1181 }11821183 /**1184 * Set permissions to change token properties1185 *1186 * @param signer keyring of signer1187 * @param collectionId ID of collection1188 * @param permissions permissions to change a property by the collection admin or token owner1189 * @example setTokenPropertyPermissions(1190 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1191 * )1192 * @returns true if extrinsic success otherwise false1193 */1194 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1195 const result = await this.helper.executeExtrinsic(1196 signer,1197 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1198 true,1199 );12001201 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1202 }12031204 /**1205 * Get token property permissions.1206 * 1207 * @param collectionId ID of collection1208 * @param propertyKeys optionally filter the returned property permissions to only these keys1209 * @example getPropertyPermissions(1219, ['location', 'date', 'time', 'isParadise']);1210 * @returns array of key-permission pairs1211 */1212 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1213 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1214 }12151216 /**1217 * Set token properties1218 *1219 * @param signer keyring of signer1220 * @param collectionId ID of collection1221 * @param tokenId ID of token1222 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1223 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1224 * @returns ```true``` if extrinsic success, otherwise ```false```1225 */1226 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1227 const result = await this.helper.executeExtrinsic(1228 signer,1229 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1230 true,1231 );12321233 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1234 }12351236 /**1237 * Get properties, metadata assigned to a token.1238 * 1239 * @param collectionId ID of collection1240 * @param tokenId ID of token1241 * @param propertyKeys optionally filter the returned properties to only these keys1242 * @example getTokenProperties(1219, ['location', 'date', 'time', 'isParadise']);1243 * @returns array of key-value pairs1244 */1245 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1246 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1247 }12481249 /**1250 * Delete the provided properties of a token1251 * @param signer keyring of signer1252 * @param collectionId ID of collection1253 * @param tokenId ID of token1254 * @param propertyKeys property keys to be deleted1255 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1256 * @returns ```true``` if extrinsic success, otherwise ```false```1257 */1258 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1259 const result = await this.helper.executeExtrinsic(1260 signer,1261 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1262 true,1263 );12641265 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1266 }12671268 /**1269 * Mint new collection1270 *1271 * @param signer keyring of signer1272 * @param collectionOptions basic collection options and properties1273 * @param mode NFT or RFT type of a collection1274 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1275 * @returns object of the created collection1276 */1277 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1278 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1279 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1280 for (const key of ['name', 'description', 'tokenPrefix']) {1281 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);1282 }1283 const creationResult = await this.helper.executeExtrinsic(1284 signer,1285 'api.tx.unique.createCollectionEx', [collectionOptions],1286 true, // errorLabel,1287 );1288 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1289 }12901291 getCollectionObject(_collectionId: number): any {1292 return null;1293 }12941295 getTokenObject(_collectionId: number, _tokenId: number): any {1296 return null;1297 }1298}129913001301class NFTGroup extends NFTnRFT {1302 /**1303 * Get collection object1304 * @param collectionId ID of collection1305 * @example getCollectionObject(2);1306 * @returns instance of UniqueNFTCollection1307 */1308 getCollectionObject(collectionId: number): UniqueNFTCollection {1309 return new UniqueNFTCollection(collectionId, this.helper);1310 }13111312 /**1313 * Get token object1314 * @param collectionId ID of collection1315 * @param tokenId ID of token1316 * @example getTokenObject(10, 5);1317 * @returns instance of UniqueNFTToken1318 */1319 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1320 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1321 }13221323 /**1324 * Get token's owner1325 * @param collectionId ID of collection1326 * @param tokenId ID of token1327 * @param blockHashAt optionally query the data at the block with this hash1328 * @example getTokenOwner(10, 5);1329 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1330 */1331 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1332 let owner;1333 if (typeof blockHashAt === 'undefined') {1334 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1335 } else {1336 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1337 }1338 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1339 }13401341 /**1342 * Is token approved to transfer1343 * @param collectionId ID of collection1344 * @param tokenId ID of token1345 * @param toAccountObj address to be approved1346 * @returns ```true``` if extrinsic success, otherwise ```false```1347 */1348 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1349 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1350 }13511352 /**1353 * Changes the owner of the token.1354 *1355 * @param signer keyring of signer1356 * @param collectionId ID of collection1357 * @param tokenId ID of token1358 * @param addressObj address of a new owner1359 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1360 * @returns ```true``` if extrinsic success, otherwise ```false```1361 */1362 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1363 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1364 }13651366 /**1367 *1368 * Change ownership of a NFT on behalf of the owner.1369 *1370 * @param signer keyring of signer1371 * @param collectionId ID of collection1372 * @param tokenId ID of token1373 * @param fromAddressObj address on behalf of which the token will be sent1374 * @param toAddressObj new token owner1375 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1376 * @returns ```true``` if extrinsic success, otherwise ```false```1377 */1378 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1379 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1380 }13811382 /**1383 * Recursively find the address that owns the token1384 * @param collectionId ID of collection1385 * @param tokenId ID of token1386 * @param blockHashAt1387 * @example getTokenTopmostOwner(10, 5);1388 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1389 */1390 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1391 let owner;1392 if (typeof blockHashAt === 'undefined') {1393 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1394 } else {1395 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1396 }13971398 if (owner === null) return null;13991400 return owner.toHuman();1401 }14021403 /**1404 * Get tokens nested in the provided token1405 * @param collectionId ID of collection1406 * @param tokenId ID of token1407 * @param blockHashAt optionally query the data at the block with this hash1408 * @example getTokenChildren(10, 5);1409 * @returns tokens whose depth of nesting is <= 51410 */1411 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1412 let children;1413 if(typeof blockHashAt === 'undefined') {1414 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1415 } else {1416 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1417 }14181419 return children.toJSON().map((x: any) => {1420 return {collectionId: x.collection, tokenId: x.token};1421 });1422 }14231424 /**1425 * Nest one token into another1426 * @param signer keyring of signer1427 * @param tokenObj token to be nested1428 * @param rootTokenObj token to be parent1429 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1430 * @returns ```true``` if extrinsic success, otherwise ```false```1431 */1432 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1433 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1434 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1435 if(!result) {1436 throw Error('Unable to nest token!');1437 }1438 return result;1439 }14401441 /**1442 * Remove token from nested state1443 * @param signer keyring of signer1444 * @param tokenObj token to unnest1445 * @param rootTokenObj parent of a token1446 * @param toAddressObj address of a new token owner1447 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1448 * @returns ```true``` if extrinsic success, otherwise ```false```1449 */1450 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1451 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1452 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1453 if(!result) {1454 throw Error('Unable to unnest token!');1455 }1456 return result;1457 }14581459 /**1460 * Mint new collection1461 * @param signer keyring of signer1462 * @param collectionOptions Collection options1463 * @example1464 * mintCollection(aliceKeyring, {1465 * name: 'New',1466 * description: 'New collection',1467 * tokenPrefix: 'NEW',1468 * })1469 * @returns object of the created collection1470 */1471 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1472 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1473 }14741475 /**1476 * Mint new token1477 * @param signer keyring of signer1478 * @param data token data1479 * @returns created token object1480 */1481 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1482 const creationResult = await this.helper.executeExtrinsic(1483 signer,1484 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1485 nft: {1486 properties: data.properties,1487 },1488 }],1489 true,1490 );1491 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1492 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1493 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1494 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1495 }14961497 /**1498 * Mint multiple NFT tokens1499 * @param signer keyring of signer1500 * @param collectionId ID of collection1501 * @param tokens array of tokens with owner and properties1502 * @example1503 * mintMultipleTokens(aliceKeyring, 10, [{1504 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1505 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1506 * },{1507 * owner: {Ethereum: "0x9F0583DbB855d..."},1508 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1509 * }]);1510 * @returns ```true``` if extrinsic success, otherwise ```false```1511 */1512 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1513 const creationResult = await this.helper.executeExtrinsic(1514 signer,1515 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1516 true,1517 );1518 const collection = this.getCollectionObject(collectionId);1519 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1520 }15211522 /**1523 * Mint multiple NFT tokens with one owner1524 * @param signer keyring of signer1525 * @param collectionId ID of collection1526 * @param owner tokens owner1527 * @param tokens array of tokens with owner and properties1528 * @example1529 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1530 * properties: [{1531 * key: "gender",1532 * value: "female",1533 * },{1534 * key: "age",1535 * value: "33",1536 * }],1537 * }]);1538 * @returns array of newly created tokens1539 */1540 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1541 const rawTokens = [];1542 for (const token of tokens) {1543 const raw = {NFT: {properties: token.properties}};1544 rawTokens.push(raw);1545 }1546 const creationResult = await this.helper.executeExtrinsic(1547 signer,1548 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1549 true,1550 );1551 const collection = this.getCollectionObject(collectionId);1552 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1553 }15541555 /**1556 * Set, change, or remove approved address to transfer the ownership of the NFT.1557 *1558 * @param signer keyring of signer1559 * @param collectionId ID of collection1560 * @param tokenId ID of token1561 * @param toAddressObj address to approve1562 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1563 * @returns ```true``` if extrinsic success, otherwise ```false```1564 */1565 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1566 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1567 }1568}156915701571class RFTGroup extends NFTnRFT {1572 /**1573 * Get collection object1574 * @param collectionId ID of collection1575 * @example getCollectionObject(2);1576 * @returns instance of UniqueRFTCollection1577 */1578 getCollectionObject(collectionId: number): UniqueRFTCollection {1579 return new UniqueRFTCollection(collectionId, this.helper);1580 }15811582 /**1583 * Get token object1584 * @param collectionId ID of collection1585 * @param tokenId ID of token1586 * @example getTokenObject(10, 5);1587 * @returns instance of UniqueNFTToken1588 */1589 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1590 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1591 }15921593 /**1594 * Get top 10 token owners with the largest number of pieces1595 * @param collectionId ID of collection1596 * @param tokenId ID of token1597 * @example getTokenTop10Owners(10, 5);1598 * @returns array of top 10 owners1599 */1600 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1601 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1602 }16031604 /**1605 * Get number of pieces owned by address1606 * @param collectionId ID of collection1607 * @param tokenId ID of token1608 * @param addressObj address token owner1609 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1610 * @returns number of pieces ownerd by address1611 */1612 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1613 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1614 }16151616 /**1617 * Transfer pieces of token to another address1618 * @param signer keyring of signer1619 * @param collectionId ID of collection1620 * @param tokenId ID of token1621 * @param addressObj address of a new owner1622 * @param amount number of pieces to be transfered1623 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1624 * @returns ```true``` if extrinsic success, otherwise ```false```1625 */1626 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1627 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1628 }16291630 /**1631 * Change ownership of some pieces of RFT on behalf of the owner.1632 * @param signer keyring of signer1633 * @param collectionId ID of collection1634 * @param tokenId ID of token1635 * @param fromAddressObj address on behalf of which the token will be sent1636 * @param toAddressObj new token owner1637 * @param amount number of pieces to be transfered1638 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1639 * @returns ```true``` if extrinsic success, otherwise ```false```1640 */1641 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1642 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1643 }16441645 /**1646 * Mint new collection1647 * @param signer keyring of signer1648 * @param collectionOptions Collection options1649 * @example1650 * mintCollection(aliceKeyring, {1651 * name: 'New',1652 * description: 'New collection',1653 * tokenPrefix: 'NEW',1654 * })1655 * @returns object of the created collection1656 */1657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1658 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1659 }16601661 /**1662 * Mint new token1663 * @param signer keyring of signer1664 * @param data token data1665 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1666 * @returns created token object1667 */1668 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1669 const creationResult = await this.helper.executeExtrinsic(1670 signer,1671 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1672 refungible: {1673 pieces: data.pieces,1674 properties: data.properties,1675 },1676 }],1677 true,1678 );1679 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1680 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1681 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1682 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1683 }16841685 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1686 throw Error('Not implemented');1687 const creationResult = await this.helper.executeExtrinsic(1688 signer,1689 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1690 true, // `Unable to mint RFT tokens for ${label}`,1691 );1692 const collection = this.getCollectionObject(collectionId);1693 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1694 }16951696 /**1697 * Mint multiple RFT tokens with one owner1698 * @param signer keyring of signer1699 * @param collectionId ID of collection1700 * @param owner tokens owner1701 * @param tokens array of tokens with properties and pieces1702 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1703 * @returns array of newly created RFT tokens1704 */1705 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1706 const rawTokens = [];1707 for (const token of tokens) {1708 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1709 rawTokens.push(raw);1710 }1711 const creationResult = await this.helper.executeExtrinsic(1712 signer,1713 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1714 true,1715 );1716 const collection = this.getCollectionObject(collectionId);1717 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1718 }17191720 /**1721 * Destroys a concrete instance of RFT.1722 * @param signer keyring of signer1723 * @param collectionId ID of collection1724 * @param tokenId ID of token1725 * @param amount number of pieces to be burnt1726 * @example burnToken(aliceKeyring, 10, 5);1727 * @returns ```true``` if the extrinsic is successful, otherwise ```false```1728 */1729 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1730 return await super.burnToken(signer, collectionId, tokenId, amount);1731 }17321733 /**1734 * Destroys a concrete instance of RFT on behalf of the owner.1735 * @param signer keyring of signer1736 * @param collectionId ID of collection1737 * @param tokenId ID of token1738 * @param fromAddressObj address on behalf of which the token will be burnt1739 * @param amount number of pieces to be burnt1740 * @example burnTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2n)1741 * @returns ```true``` if extrinsic success, otherwise ```false```1742 */1743 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1744 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1745 }17461747 /**1748 * Set, change, or remove approved address to transfer the ownership of the RFT.1749 *1750 * @param signer keyring of signer1751 * @param collectionId ID of collection1752 * @param tokenId ID of token1753 * @param toAddressObj address to approve1754 * @param amount number of pieces to be approved1755 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1756 * @returns true if the token success, otherwise false1757 */1758 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1759 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1760 }17611762 /**1763 * Get total number of pieces1764 * @param collectionId ID of collection1765 * @param tokenId ID of token1766 * @example getTokenTotalPieces(10, 5);1767 * @returns number of pieces1768 */1769 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1770 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1771 }17721773 /**1774 * Change number of token pieces. Signer must be the owner of all token pieces.1775 * @param signer keyring of signer1776 * @param collectionId ID of collection1777 * @param tokenId ID of token1778 * @param amount new number of pieces1779 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1780 * @returns true if the repartion was success, otherwise false1781 */1782 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1783 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1784 const repartitionResult = await this.helper.executeExtrinsic(1785 signer,1786 'api.tx.unique.repartition', [collectionId, tokenId, amount],1787 true,1788 );1789 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1790 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1791 }1792}179317941795class FTGroup extends CollectionGroup {1796 /**1797 * Get collection object1798 * @param collectionId ID of collection1799 * @example getCollectionObject(2);1800 * @returns instance of UniqueFTCollection1801 */1802 getCollectionObject(collectionId: number): UniqueFTCollection {1803 return new UniqueFTCollection(collectionId, this.helper);1804 }18051806 /**1807 * Mint new fungible collection1808 * @param signer keyring of signer1809 * @param collectionOptions Collection options1810 * @param decimalPoints number of token decimals1811 * @example1812 * mintCollection(aliceKeyring, {1813 * name: 'New',1814 * description: 'New collection',1815 * tokenPrefix: 'NEW',1816 * }, 18)1817 * @returns newly created fungible collection1818 */1819 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1820 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1821 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1822 collectionOptions.mode = {fungible: decimalPoints};1823 for (const key of ['name', 'description', 'tokenPrefix']) {1824 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);1825 }1826 const creationResult = await this.helper.executeExtrinsic(1827 signer,1828 'api.tx.unique.createCollectionEx', [collectionOptions],1829 true,1830 );1831 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1832 }18331834 /**1835 * Mint tokens1836 * @param signer keyring of signer1837 * @param collectionId ID of collection1838 * @param owner address owner of new tokens1839 * @param amount amount of tokens to be meanted1840 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1841 * @returns ```true``` if extrinsic success, otherwise ```false```1842 */1843 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1844 const creationResult = await this.helper.executeExtrinsic(1845 signer,1846 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1847 fungible: {1848 value: amount,1849 },1850 }],1851 true, // `Unable to mint fungible tokens for ${label}`,1852 );1853 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1854 }18551856 /**1857 * Mint multiple Fungible tokens with one owner1858 * @param signer keyring of signer1859 * @param collectionId ID of collection1860 * @param owner tokens owner1861 * @param tokens array of tokens with properties and pieces1862 * @returns ```true``` if extrinsic success, otherwise ```false```1863 */1864 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1865 const rawTokens = [];1866 for (const token of tokens) {1867 const raw = {Fungible: {Value: token.value}};1868 rawTokens.push(raw);1869 }1870 const creationResult = await this.helper.executeExtrinsic(1871 signer,1872 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1873 true,1874 );1875 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1876 }18771878 /**1879 * Get the top 10 owners with the largest balance for the Fungible collection1880 * @param collectionId ID of collection1881 * @example getTop10Owners(10);1882 * @returns array of ```ICrossAccountId```1883 */1884 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1885 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1886 }18871888 /**1889 * Get account balance1890 * @param collectionId ID of collection1891 * @param addressObj address of owner1892 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1893 * @returns amount of fungible tokens owned by address1894 */1895 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1896 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1897 }18981899 /**1900 * Transfer tokens to address1901 * @param signer keyring of signer1902 * @param collectionId ID of collection1903 * @param toAddressObj address recipient1904 * @param amount amount of tokens to be sent1905 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1906 * @returns ```true``` if extrinsic success, otherwise ```false```1907 */1908 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1909 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1910 }19111912 /**1913 * Transfer some tokens on behalf of the owner.1914 * @param signer keyring of signer1915 * @param collectionId ID of collection1916 * @param fromAddressObj address on behalf of which tokens will be sent1917 * @param toAddressObj address where token to be sent1918 * @param amount number of tokens to be sent1919 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1920 * @returns ```true``` if extrinsic success, otherwise ```false```1921 */1922 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1923 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1924 }19251926 /**1927 * Destroy some amount of tokens1928 * @param signer keyring of signer1929 * @param collectionId ID of collection1930 * @param amount amount of tokens to be destroyed1931 * @example burnTokens(aliceKeyring, 10, 1000n);1932 * @returns ```true``` if extrinsic success, otherwise ```false```1933 */1934 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1935 return await super.burnToken(signer, collectionId, 0, amount);1936 }19371938 /**1939 * Burn some tokens on behalf of the owner.1940 * @param signer keyring of signer1941 * @param collectionId ID of collection1942 * @param fromAddressObj address on behalf of which tokens will be burnt1943 * @param amount amount of tokens to be burnt1944 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1945 * @returns ```true``` if extrinsic success, otherwise ```false```1946 */1947 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1948 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1949 }19501951 /**1952 * Get total collection supply1953 * @param collectionId1954 * @returns1955 */1956 async getTotalPieces(collectionId: number): Promise<bigint> {1957 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1958 }19591960 /**1961 * Set, change, or remove approved address to transfer tokens.1962 *1963 * @param signer keyring of signer1964 * @param collectionId ID of collection1965 * @param toAddressObj address to be approved1966 * @param amount amount of tokens to be approved1967 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1968 * @returns ```true``` if extrinsic success, otherwise ```false```1969 */1970 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1971 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1972 }19731974 /**1975 * Get amount of fungible tokens approved to transfer1976 * @param collectionId ID of collection1977 * @param fromAddressObj owner of tokens1978 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1979 * @returns number of tokens approved for the transfer1980 */1981 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1982 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1983 }1984}198519861987class ChainGroup extends HelperGroup {1988 /**1989 * Get system properties of a chain1990 * @example getChainProperties();1991 * @returns ss58Format, token decimals, and token symbol1992 */1993 getChainProperties(): IChainProperties {1994 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1995 return {1996 ss58Format: properties.ss58Format.toJSON(),1997 tokenDecimals: properties.tokenDecimals.toJSON(),1998 tokenSymbol: properties.tokenSymbol.toJSON(),1999 };2000 }20012002 /**2003 * Get chain header2004 * @example getLatestBlockNumber();2005 * @returns the number of the last block2006 */2007 async getLatestBlockNumber(): Promise<number> {2008 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2009 }20102011 /**2012 * Get block hash by block number2013 * @param blockNumber number of block2014 * @example getBlockHashByNumber(12345);2015 * @returns hash of a block2016 */2017 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2018 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2019 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2020 return blockHash;2021 }20222023 // TODO add docs2024 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2025 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2026 if (!blockHash) return null;2027 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2028 }20292030 /**2031 * Get account nonce2032 * @param address substrate address2033 * @example getNonce("5GrwvaEF5zXb26Fz...");2034 * @returns number, account's nonce2035 */2036 async getNonce(address: TSubstrateAccount): Promise<number> {2037 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2038 }2039}204020412042class BalanceGroup extends HelperGroup {2043 getCollectionCreationPrice(): bigint {2044 return 2n * this.helper.balance.getOneTokenNominal();2045 }2046 /**2047 * Representation of the native token in the smallest unit - one OPAL (OPL), QUARTZ (QTZ), or UNIQUE (UNQ).2048 * @example getOneTokenNominal()2049 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.2050 */2051 getOneTokenNominal(): bigint {2052 const chainProperties = this.helper.chain.getChainProperties();2053 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2054 }20552056 /**2057 * Get substrate address balance2058 * @param address substrate address2059 * @example getSubstrate("5GrwvaEF5zXb26Fz...")2060 * @returns amount of tokens on address2061 */2062 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2063 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2064 }20652066 /**2067 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved2068 * @param address substrate address2069 * @returns2070 */2071 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2072 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2073 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2074 }20752076 /**2077 * Get ethereum address balance2078 * @param address ethereum address2079 * @example getEthereum("0x9F0583DbB855d...")2080 * @returns amount of tokens on address2081 */2082 async getEthereum(address: TEthereumAccount): Promise<bigint> {2083 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2084 }20852086 /**2087 * Transfer tokens to substrate address2088 * @param signer keyring of signer2089 * @param address substrate address of a recipient2090 * @param amount amount of tokens to be transfered2091 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);2092 * @returns ```true``` if extrinsic success, otherwise ```false```2093 */2094 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2095 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}`*/);20962097 let transfer = {from: null, to: null, amount: 0n} as any;2098 result.result.events.forEach(({event: {data, method, section}}) => {2099 if ((section === 'balances') && (method === 'Transfer')) {2100 transfer = {2101 from: this.helper.address.normalizeSubstrate(data[0]),2102 to: this.helper.address.normalizeSubstrate(data[1]),2103 amount: BigInt(data[2]),2104 };2105 }2106 });2107 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2108 && this.helper.address.normalizeSubstrate(address) === transfer.to 2109 && BigInt(amount) === transfer.amount;2110 return isSuccess;2111 }2112}211321142115class AddressGroup extends HelperGroup {2116 /**2117 * Normalizes the address to the specified ss58 format, by default ```42```.2118 * @param address substrate address2119 * @param ss58Format format for address conversion, by default ```42```2120 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2121 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2122 */2123 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2124 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2125 }21262127 /**2128 * Get address in the connected chain format2129 * @param address substrate address2130 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2131 * @returns address in chain format2132 */2133 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2134 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2135 }21362137 /**2138 * Get substrate mirror of an ethereum address2139 * @param ethAddress ethereum address2140 * @param toChainFormat false for normalized account2141 * @example ethToSubstrate('0x9F0583DbB855d...')2142 * @returns substrate mirror of a provided ethereum address2143 */2144 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2145 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2146 }21472148 /**2149 * Get ethereum mirror of a substrate address2150 * @param subAddress substrate account2151 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2152 * @returns ethereum mirror of a provided substrate address2153 */2154 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2155 return CrossAccountId.translateSubToEth(subAddress);2156 }2157}21582159class StakingGroup extends HelperGroup {2160 /**2161 * Stake tokens for App Promotion2162 * @param signer keyring of signer2163 * @param amountToStake amount of tokens to stake2164 * @param label extra label for log2165 * @returns2166 */2167 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2168 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2169 const _stakeResult = await this.helper.executeExtrinsic(2170 signer, 'api.tx.appPromotion.stake',2171 [amountToStake], true,2172 );2173 // TODO extract info from stakeResult2174 return true;2175 }21762177 /**2178 * Unstake tokens for App Promotion2179 * @param signer keyring of signer2180 * @param amountToUnstake amount of tokens to unstake2181 * @param label extra label for log2182 * @returns block number where balances will be unlocked2183 */2184 async unstake(signer: TSigner, label?: string): Promise<number> {2185 if(typeof label === 'undefined') label = `${signer.address}`;2186 const _unstakeResult = await this.helper.executeExtrinsic(2187 signer, 'api.tx.appPromotion.unstake',2188 [], true,2189 );2190 // TODO extract block number fron events2191 return 1;2192 }21932194 /**2195 * Get total staked amount for address2196 * @param address substrate or ethereum address2197 * @returns total staked amount2198 */2199 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2200 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2201 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2202 }22032204 /**2205 * Get total staked per block2206 * @param address substrate or ethereum address2207 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2208 */2209 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2210 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2211 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2212 return { 2213 block: block.toBigInt(),2214 amount: amount.toBigInt(),2215 };2216 });2217 }22182219 /**2220 * Get total pending unstake amount for address2221 * @param address substrate or ethereum address2222 * @returns total pending unstake amount2223 */2224 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2225 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2226 }22272228 /**2229 * Get pending unstake amount per block for address2230 * @param address substrate or ethereum address2231 * @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 block2232 */2233 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2234 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2235 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2236 return {2237 block: block.toBigInt(),2238 amount: amount.toBigInt(),2239 };2240 });2241 return result;2242 }2243}22442245export class UniqueHelper extends ChainHelperBase {2246 chain: ChainGroup;2247 balance: BalanceGroup;2248 address: AddressGroup;2249 collection: CollectionGroup;2250 nft: NFTGroup;2251 rft: RFTGroup;2252 ft: FTGroup;2253 staking: StakingGroup;22542255 constructor(logger?: ILogger) {2256 super(logger);2257 this.chain = new ChainGroup(this);2258 this.balance = new BalanceGroup(this);2259 this.address = new AddressGroup(this);2260 this.collection = new CollectionGroup(this);2261 this.nft = new NFTGroup(this);2262 this.rft = new RFTGroup(this);2263 this.ft = new FTGroup(this);2264 this.staking = new StakingGroup(this);2265 }2266}226722682269export class UniqueBaseCollection {2270 helper: UniqueHelper;2271 collectionId: number;22722273 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2274 this.collectionId = collectionId;2275 this.helper = uniqueHelper;2276 }22772278 async getData() {2279 return await this.helper.collection.getData(this.collectionId);2280 }22812282 async getLastTokenId() {2283 return await this.helper.collection.getLastTokenId(this.collectionId);2284 }22852286 async doesTokenExist(tokenId: number) {2287 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2288 }22892290 async getAdmins() {2291 return await this.helper.collection.getAdmins(this.collectionId);2292 }22932294 async getAllowList() {2295 return await this.helper.collection.getAllowList(this.collectionId);2296 }22972298 async getEffectiveLimits() {2299 return await this.helper.collection.getEffectiveLimits(this.collectionId);2300 }23012302 async getProperties(propertyKeys?: string[] | null) {2303 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2304 }23052306 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2307 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2308 }23092310 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2311 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2312 }23132314 async confirmSponsorship(signer: TSigner) {2315 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2316 }23172318 async removeSponsor(signer: TSigner) {2319 return await this.helper.collection.removeSponsor(signer, this.collectionId);2320 }23212322 async setLimits(signer: TSigner, limits: ICollectionLimits) {2323 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2324 }23252326 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2327 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2328 }23292330 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2331 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2332 }23332334 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2335 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2336 }23372338 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2339 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2340 }23412342 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2343 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2344 }23452346 async setProperties(signer: TSigner, properties: IProperty[]) {2347 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2348 }23492350 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2351 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2352 }23532354 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2355 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2356 }23572358 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2359 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2360 }23612362 async disableNesting(signer: TSigner) {2363 return await this.helper.collection.disableNesting(signer, this.collectionId);2364 }23652366 async burn(signer: TSigner) {2367 return await this.helper.collection.burn(signer, this.collectionId);2368 }2369}237023712372export class UniqueNFTCollection extends UniqueBaseCollection {2373 getTokenObject(tokenId: number) {2374 return new UniqueNFToken(tokenId, this);2375 }23762377 async getTokensByAddress(addressObj: ICrossAccountId) {2378 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2379 }23802381 async getToken(tokenId: number, blockHashAt?: string) {2382 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2383 }23842385 async getTokenOwner(tokenId: number, blockHashAt?: string) {2386 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2387 }23882389 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2390 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2391 }23922393 async getTokenChildren(tokenId: number, blockHashAt?: string) {2394 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2395 }23962397 async getPropertyPermissions(propertyKeys: string[] | null = null) {2398 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2399 }24002401 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2402 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2403 }24042405 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2406 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2407 }24082409 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2410 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2411 }24122413 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2414 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2415 }24162417 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2418 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2419 }24202421 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2422 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2423 }24242425 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2426 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2427 }24282429 async burnToken(signer: TSigner, tokenId: number) {2430 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2431 }24322433 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2434 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2435 }24362437 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2438 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2439 }24402441 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2442 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2443 }24442445 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2446 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2447 }24482449 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2450 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2451 }24522453 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2454 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2455 }2456}245724582459export class UniqueRFTCollection extends UniqueBaseCollection {2460 getTokenObject(tokenId: number) {2461 return new UniqueRFToken(tokenId, this);2462 }24632464 async getToken(tokenId: number, blockHashAt?: string) {2465 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2466 }24672468 async getTokensByAddress(addressObj: ICrossAccountId) {2469 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2470 }24712472 async getTop10TokenOwners(tokenId: number) {2473 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2474 }24752476 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2477 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2478 }24792480 async getTokenTotalPieces(tokenId: number) {2481 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2482 }24832484 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2485 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2486 }24872488 async getPropertyPermissions(propertyKeys: string[] | null = null) {2489 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2490 }24912492 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2493 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2494 }24952496 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2497 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2498 }24992500 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2501 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2502 }25032504 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2505 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2506 }25072508 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2509 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2510 }25112512 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2513 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2514 }25152516 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2517 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2518 }25192520 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2521 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2522 }25232524 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2525 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2526 }25272528 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2529 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2530 }25312532 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2533 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2534 }25352536 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2537 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2538 }2539}254025412542export class UniqueFTCollection extends UniqueBaseCollection {2543 async getBalance(addressObj: ICrossAccountId) {2544 return await this.helper.ft.getBalance(this.collectionId, addressObj);2545 }25462547 async getTotalPieces() {2548 return await this.helper.ft.getTotalPieces(this.collectionId);2549 }25502551 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2552 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2553 }25542555 async getTop10Owners() {2556 return await this.helper.ft.getTop10Owners(this.collectionId);2557 }25582559 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2560 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2561 }25622563 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2564 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2565 }25662567 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2568 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2569 }25702571 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2572 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2573 }25742575 async burnTokens(signer: TSigner, amount=1n) {2576 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2577 }25782579 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2580 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2581 }25822583 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2584 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2585 }2586}258725882589export class UniqueBaseToken {2590 collection: UniqueNFTCollection | UniqueRFTCollection;2591 collectionId: number;2592 tokenId: number;25932594 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2595 this.collection = collection;2596 this.collectionId = collection.collectionId;2597 this.tokenId = tokenId;2598 }25992600 async getNextSponsored(addressObj: ICrossAccountId) {2601 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2602 }26032604 async getProperties(propertyKeys?: string[] | null) {2605 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2606 }26072608 async setProperties(signer: TSigner, properties: IProperty[]) {2609 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2610 }26112612 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2613 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2614 }26152616 async doesExist() {2617 return await this.collection.doesTokenExist(this.tokenId);2618 }26192620 nestingAccount() {2621 return this.collection.helper.util.getTokenAccount(this);2622 }2623}262426252626export class UniqueNFToken extends UniqueBaseToken {2627 collection: UniqueNFTCollection;26282629 constructor(tokenId: number, collection: UniqueNFTCollection) {2630 super(tokenId, collection);2631 this.collection = collection;2632 }26332634 async getData(blockHashAt?: string) {2635 return await this.collection.getToken(this.tokenId, blockHashAt);2636 }26372638 async getOwner(blockHashAt?: string) {2639 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2640 }26412642 async getTopmostOwner(blockHashAt?: string) {2643 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2644 }26452646 async getChildren(blockHashAt?: string) {2647 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2648 }26492650 async nest(signer: TSigner, toTokenObj: IToken) {2651 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2652 }26532654 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2655 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2656 }26572658 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2659 return await this.collection.transferToken(signer, this.tokenId, addressObj);2660 }26612662 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2663 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2664 }26652666 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2667 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2668 }26692670 async isApproved(toAddressObj: ICrossAccountId) {2671 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2672 }26732674 async burn(signer: TSigner) {2675 return await this.collection.burnToken(signer, this.tokenId);2676 }26772678 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2679 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2680 }2681}26822683export class UniqueRFToken extends UniqueBaseToken {2684 collection: UniqueRFTCollection;26852686 constructor(tokenId: number, collection: UniqueRFTCollection) {2687 super(tokenId, collection);2688 this.collection = collection;2689 }26902691 async getData(blockHashAt?: string) {2692 return await this.collection.getToken(this.tokenId, blockHashAt);2693 }26942695 async getTop10Owners() {2696 return await this.collection.getTop10TokenOwners(this.tokenId);2697 }26982699 async getBalance(addressObj: ICrossAccountId) {2700 return await this.collection.getTokenBalance(this.tokenId, addressObj);2701 }27022703 async getTotalPieces() {2704 return await this.collection.getTokenTotalPieces(this.tokenId);2705 }27062707 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2708 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2709 }27102711 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2712 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2713 }27142715 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2716 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2717 }27182719 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2720 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2721 }27222723 async repartition(signer: TSigner, amount: bigint) {2724 return await this.collection.repartitionToken(signer, this.tokenId, amount);2725 }27262727 async burn(signer: TSigner, amount=1n) {2728 return await this.collection.burnToken(signer, this.tokenId, amount);2729 }27302731 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2732 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2733 }2734}