difftreelog
tests: thorough event logging + a few more tests refactored
in: master
7 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -64,6 +64,7 @@
"testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",
"testBurnItem": "mocha --timeout 9999999 -r ts-node/register ./**/burnItem.test.ts",
"testAdminTransferAndBurn": "mocha --timeout 9999999 -r ts-node/register ./**/adminTransferAndBurn.test.ts",
+ "testMintModes": "mocha --timeout 9999999 -r ts-node/register ./**/mintModes.test.ts",
"testSetMintPermission": "mocha --timeout 9999999 -r ts-node/register ./**/setMintPermission.test.ts",
"testSetPublicAccessMode": "mocha --timeout 9999999 -r ts-node/register ./**/setPublicAccessMode.test.ts",
"testCreditFeesToTreasury": "mocha --timeout 9999999 -r ts-node/register ./**/creditFeesToTreasury.test.ts",
tests/src/fungible.test.tsdiffbeforeafterboth--- a/tests/src/fungible.test.ts
+++ b/tests/src/fungible.test.ts
@@ -15,18 +15,18 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
import {IKeyringPair} from '@polkadot/types/types';
-import {U128_MAX} from './util/helpers';
import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
-// todo:playgrounds get rid of globals
-let alice: IKeyringPair;
-let bob: IKeyringPair;
+const U128_MAX = (1n << 128n) - 1n;
describe('integration test: Fungible functionality:', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async () => {
await usingPlaygrounds(async (helper, privateKey) => {
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
@@ -82,7 +82,7 @@
expect(await collection.getBalance({Substrate: bob.address})).to.be.equal(60n);
expect(await collection.getBalance(ethAcc)).to.be.equal(140n);
- await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejected;
+ await expect(collection.transfer(alice, {Substrate: bob.address}, 350n)).to.eventually.be.rejectedWith(/common\.TokenValueTooLow/);
});
itSub('Tokens multiple creation', async ({helper}) => {
tests/src/inflation.test.tsdiffbeforeafterboth--- a/tests/src/inflation.test.ts
+++ b/tests/src/inflation.test.ts
@@ -14,42 +14,45 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import chai from 'chai';
-import chaiAsPromised from 'chai-as-promised';
-import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from './substrate/substrate-api';
-
-chai.use(chaiAsPromised);
-const expect = chai.expect;
+import {IKeyringPair} from '@polkadot/types/types';
+import {expect, itSub, usingPlaygrounds} from './util/playgrounds';
+// todo:playgrounds requires sudo, look into on the later stage
describe('integration test: Inflation', () => {
- it('First year inflation is 10%', async () => {
- await usingApi(async (api, privateKeyWrapper) => {
+ let superuser: IKeyringPair;
- // Make sure non-sudo can't start inflation
- const tx = api.tx.inflation.startInflation(1);
- const bob = privateKeyWrapper('//Bob');
- await expect(submitTransactionExpectFailAsync(bob, tx)).to.be.rejected;
+ before(async () => {
+ await usingPlaygrounds(async (_, privateKey) => {
+ superuser = privateKey('//Alice');
+ });
+ });
+
+ itSub('First year inflation is 10%', async ({helper}) => {
+ // Make sure non-sudo can't start inflation
+ const [bob] = await helper.arrange.createAccounts([10n], superuser);
- // Start inflation on relay block 1 (Alice is sudo)
- const alice = privateKeyWrapper('//Alice');
- const sudoTx = api.tx.sudo.sudo(tx as any);
- await submitTransactionAsync(alice, sudoTx);
+ await expect(helper.executeExtrinsic(bob, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
- const blockInterval = (api.consts.inflation.inflationBlockInterval).toBigInt();
- const totalIssuanceStart = (await api.query.inflation.startingYearTotalIssuance()).toBigInt();
- const blockInflation = (await api.query.inflation.blockInflation()).toBigInt();
+ // Make sure superuser can't start inflation without explicit sudo
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.inflation.startInflation', [1])).to.be.rejectedWith(/BadOrigin/);
- const YEAR = 5259600n; // 6-second block. Blocks in one year
- // const YEAR = 2629800n; // 12-second block. Blocks in one year
+ // Start inflation on relay block 1 (Alice is sudo)
+ const tx = helper.constructApiCall('api.tx.inflation.startInflation', [1]);
+ await expect(helper.executeExtrinsic(superuser, 'api.tx.sudo.sudo', [tx])).to.not.be.rejected;
- const totalExpectedInflation = totalIssuanceStart / 10n;
- const totalActualInflation = blockInflation * YEAR / blockInterval;
+ 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 tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
- const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
+ const YEAR = 5259600n; // 6-second block. Blocks in one year
+ // const YEAR = 2629800n; // 12-second block. Blocks in one year
+
+ const totalExpectedInflation = totalIssuanceStart / 10n;
+ const totalActualInflation = blockInflation * YEAR / blockInterval;
+
+ const tolerance = 0.00001; // Relative difference per year between theoretical and actual inflation
+ const expectedInflation = totalExpectedInflation / totalActualInflation - 1n;
- expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
- });
+ expect(Math.abs(Number(expectedInflation))).to.be.lessThanOrEqual(tolerance);
});
-
});
tests/src/refungible.test.tsdiffbeforeafterboth--- a/tests/src/refungible.test.ts
+++ b/tests/src/refungible.test.ts
@@ -17,17 +17,18 @@
import {IKeyringPair} from '@polkadot/types/types';
import {itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds, expect} from './util/playgrounds';
-let alice: IKeyringPair;
-let bob: IKeyringPair;
const MAX_REFUNGIBLE_PIECES = 1_000_000_000_000_000_000_000n;
describe('integration test: Refungible functionality:', async () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
before(async function() {
await usingPlaygrounds(async (helper, privateKey) => {
requirePalletsOrSkip(this, helper, [Pallets.ReFungible]);
- alice = privateKey('//Alice');
- bob = privateKey('//Bob');
+ const donor = privateKey('//Alice');
+ [alice, bob] = await helper.arrange.createAccounts([100n, 10n], donor);
});
});
@@ -209,36 +210,38 @@
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
await token.repartition(alice, 200n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
- method: 'ItemCreated',
+ const chainEvents = helper.chainLog.slice(-1)[0].events;
+ expect(chainEvents).to.deep.include({
section: 'common',
- index: '0x4202',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '100',
+ method: 'ItemCreated',
+ index: [66, 2],
+ data: [
+ collection.collectionId,
+ token.tokenId,
+ {substrate: alice.address},
+ 100n,
],
- }]);
+ phase: {applyExtrinsic: 2},
+ });
});
itSub('Repartition with decreased amount', async ({helper}) => {
const collection = await helper.rft.mintCollection(alice, {name: 'test', description: 'test', tokenPrefix: 'test'});
const token = await collection.mintToken(alice, 100n);
await token.repartition(alice, 50n);
- const chainEvents = helper.chainLog.slice(-1)[0].events.map((x: any) => x.event);
- expect(chainEvents).to.include.deep.members([{
+ const chainEvents = helper.chainLog.slice(-1)[0].events;
+ expect(chainEvents).to.deep.include({
method: 'ItemDestroyed',
section: 'common',
- index: '0x4203',
- data: [
- helper.api!.createType('u32', collection.collectionId).toHuman(),
- helper.api!.createType('u32', token.tokenId).toHuman(),
- {Substrate: alice.address},
- '50',
+ index: [66, 3],
+ data: [
+ collection.collectionId,
+ token.tokenId,
+ {substrate: alice.address},
+ 50n,
],
- }]);
+ phase: {applyExtrinsic: 2},
+ });
});
itSub('Create new collection with properties', async ({helper}) => {
tests/src/tx-version-presence.test.tsdiffbeforeafterboth--- a/tests/src/tx-version-presence.test.ts
+++ b/tests/src/tx-version-presence.test.ts
@@ -14,7 +14,7 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import { Metadata } from '@polkadot/types';
+import {Metadata} from '@polkadot/types';
import {itSub, usingPlaygrounds, expect} from './util/playgrounds';
let metadata: Metadata;
tests/src/util/playgrounds/types.tsdiffbeforeafterboth--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -3,20 +3,31 @@
import {IKeyringPair} from '@polkadot/types/types';
-export interface IChainEvent {
- data: any;
+export interface IEvent {
+ section: string;
method: string;
- section: string;
+ index: [number, number] | string;
+ data: any[];
+ phase: {applyExtrinsic: number} | 'Initialization',
}
export interface ITransactionResult {
- status: 'Fail' | 'Success';
- result: {
- events: {
- event: IChainEvent
- }[];
- },
- moduleError?: string;
+ status: 'Fail' | 'Success';
+ result: {
+ events: {
+ phase: any, // {ApplyExtrinsic: number} | 'Initialization',
+ event: IEvent;
+ // topics: any[];
+ }[];
+ },
+ moduleError?: string;
+}
+
+export interface ISubscribeBlockEventsData {
+ number: number;
+ hash: string;
+ timestamp: number;
+ events: IEvent[];
}
export interface ILogger {
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} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 // If ith character is 8 to f then make it uppercase33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getNestingTokenAddress(collectionId: number, tokenId: number) {59 return nesting.tokenIdToAddress(collectionId, tokenId);60 }6162 static getDefaultLogger(): ILogger {63 return {64 log(msg: any, level = 'INFO') {65 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66 },67 level: {68 ERROR: 'ERROR',69 WARNING: 'WARNING',70 INFO: 'INFO',71 },72 };73 }7475 static vec2str(arr: string[] | number[]) {76 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77 }7879 static str2vec(string: string) {80 if (typeof string !== 'string') return string;81 return Array.from(string).map(x => x.charCodeAt(0));82 }8384 static fromSeed(seed: string, ss58Format = 42) {85 const keyring = new Keyring({type: 'sr25519', ss58Format});86 return keyring.addFromUri(seed);87 }8889 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');96 }9798 let collectionId = null;99 creationResult.result.events.forEach(({event: {data, method, section}}) => {100 if ((section === 'common') && (method === 'CollectionCreated')) {101 collectionId = parseInt(data[0].toString(), 10);102 }103 });104105 if (collectionId === null) {106 throw Error('No CollectionCreated event was found!');107 }108109 return collectionId;110 }111112 static extractTokensFromCreationResult(creationResult: ITransactionResult) {113 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 throw Error('Unable to create tokens!');115 }116 let success = false;117 const tokens = [] as any;118 creationResult.result.events.forEach(({event: {data, method, section}}) => {119 if (method === 'ExtrinsicSuccess') {120 success = true;121 } else if ((section === 'common') && (method === 'ItemCreated')) {122 tokens.push({123 collectionId: parseInt(data[0].toString(), 10),124 tokenId: parseInt(data[1].toString(), 10),125 owner: data[2].toJSON(),126 });127 }128 });129 return {success, tokens};130 }131132 static extractTokensFromBurnResult(burnResult: ITransactionResult) {133 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 throw Error('Unable to burn tokens!');135 }136 let success = false;137 const tokens = [] as any;138 burnResult.result.events.forEach(({event: {data, method, section}}) => {139 if (method === 'ExtrinsicSuccess') {140 success = true;141 } else if ((section === 'common') && (method === 'ItemDestroyed')) {142 tokens.push({143 collectionId: parseInt(data[0].toString(), 10),144 tokenId: parseInt(data[1].toString(), 10),145 owner: data[2].toJSON(),146 });147 }148 });149 return {success, tokens};150 }151152 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153 let eventId = null;154 events.forEach(({event: {data, method, section}}) => {155 if ((section === expectedSection) && (method === expectedMethod)) {156 eventId = parseInt(data[0].toString(), 10);157 }158 });159160 if (eventId === null) {161 throw Error(`No ${expectedMethod} event was found!`);162 }163 return eventId === collectionId;164 }165166 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167 const normalizeAddress = (address: string | ICrossAccountId) => {168 if(typeof address === 'string') return address;169 const obj = {} as any;170 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175 return address;176 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178 events.forEach(({event: {data, method, section}}) => {179 if ((section === 'common') && (method === 'Transfer')) {180 const hData = (data as any).toJSON();181 transfer = {182 collectionId: hData[0],183 tokenId: hData[1],184 from: normalizeAddress(hData[2]),185 to: normalizeAddress(hData[3]),186 amount: BigInt(hData[4]),187 };188 }189 });190 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193 isSuccess = isSuccess && amount === transfer.amount;194 return isSuccess;195 }196}197198199class ChainHelperBase {200 transactionStatus = UniqueUtil.transactionStatus;201 chainLogType = UniqueUtil.chainLogType;202 util: typeof UniqueUtil;203 logger: ILogger;204 api: ApiPromise | null;205 forcedNetwork: TUniqueNetworks | null;206 network: TUniqueNetworks | null;207 chainLog: IUniqueHelperLog[];208209 constructor(logger?: ILogger) {210 this.util = UniqueUtil;211 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();212 this.logger = logger;213 this.api = null;214 this.forcedNetwork = null;215 this.network = null;216 this.chainLog = [];217 }218219 clearChainLog(): void {220 this.chainLog = [];221 }222223 forceNetwork(value: TUniqueNetworks): void {224 this.forcedNetwork = value;225 }226227 async connect(wsEndpoint: string, listeners?: IApiListeners) {228 if (this.api !== null) throw Error('Already connected');229 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);230 this.api = api;231 this.network = network;232 }233234 async disconnect() {235 if (this.api === null) return;236 await this.api.disconnect();237 this.api = null;238 this.network = null;239 }240241 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {242 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;243 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;244 return 'opal';245 }246247 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {248 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});249 await api.isReady;250251 const network = await this.detectNetwork(api);252253 await api.disconnect();254255 return network;256 }257258 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{259 api: ApiPromise;260 network: TUniqueNetworks;261 }> {262 if(typeof network === 'undefined' || network === null) network = 'opal';263 const supportedRPC = {264 opal: {265 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,266 },267 quartz: {268 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,269 },270 unique: {271 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,272 },273 };274 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);275 const rpc = supportedRPC[network];276277 // TODO: investigate how to replace rpc in runtime278 // api._rpcCore.addUserInterfaces(rpc);279280 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});281282 await api.isReadyOrError;283284 if (typeof listeners === 'undefined') listeners = {};285 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {286 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;287 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);288 }289290 return {api, network};291 }292293 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {294 const {events, status} = data;295 if (status.isReady) {296 return this.transactionStatus.NOT_READY;297 }298 if (status.isBroadcast) {299 return this.transactionStatus.NOT_READY;300 }301 if (status.isInBlock || status.isFinalized) {302 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');303 if (errors.length > 0) {304 return this.transactionStatus.FAIL;305 }306 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {307 return this.transactionStatus.SUCCESS;308 }309 }310311 return this.transactionStatus.FAIL;312 }313314 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {315 const sign = (callback: any) => {316 if(options !== null) return transaction.signAndSend(sender, options, callback);317 return transaction.signAndSend(sender, callback);318 };319 // eslint-disable-next-line no-async-promise-executor320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false/*, failureMessage='expected success'*/) {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 signer: this.getSignerAddress(sender),392 params,393 } as IUniqueHelperLog;394395 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;396 if(events.length > 0) log.events = events;397398 this.chainLog.push(log);399400 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);401 return result;402 }403404 async callRpc(rpc: string, params?: any[]) {405 if(typeof params === 'undefined') params = [];406 if(this.api === null) throw Error('API not initialized');407 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);408409 const startTime = (new Date()).getTime();410 let result;411 let error = null;412 const log = {413 type: this.chainLogType.RPC,414 call: rpc,415 params,416 } as IUniqueHelperLog;417418 try {419 result = await this.constructApiCall(rpc, params);420 }421 catch(e) {422 error = e;423 }424425 const endTime = (new Date()).getTime();426427 log.executedAt = endTime;428 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';429 log.executionTime = endTime - startTime;430431 this.chainLog.push(log);432433 if(error !== null) throw error;434435 return result;436 }437438 getSignerAddress(signer: IKeyringPair | string): string {439 if(typeof signer === 'string') return signer;440 return signer.address;441 }442443 fetchAllPalletNames(): string[] {444 if(this.api === null) throw Error('API not initialized');445 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());446 }447448 fetchMissingPalletNames(requiredPallets: string[]): string[] {449 const palletNames = this.fetchAllPalletNames();450 return requiredPallets.filter(p => !palletNames.includes(p));451 }452}453454455class HelperGroup {456 helper: UniqueHelper;457458 constructor(uniqueHelper: UniqueHelper) {459 this.helper = uniqueHelper;460 }461}462463464class CollectionGroup extends HelperGroup {465 /**466 * Get number of blocks when sponsored transaction is available.467 *468 * @param collectionId ID of collection469 * @param tokenId ID of token470 * @param addressObj address for which the sponsorship is checked471 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});472 * @returns number of blocks or null if sponsorship hasn't been set473 */474 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {475 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();476 }477478 /**479 * Get the number of created collections.480 *481 * @returns number of created collections482 */483 async getTotalCount(): Promise<number> {484 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();485 }486487 /**488 * Get information about the collection with additional data,489 * including the number of tokens it contains, its administrators,490 * the normalized address of the collection's owner, and decoded name and description.491 *492 * @param collectionId ID of collection493 * @example await getData(2)494 * @returns collection information object495 */496 async getData(collectionId: number): Promise<{497 id: number;498 name: string;499 description: string;500 tokensCount: number;501 admins: ICrossAccountId[];502 normalizedOwner: TSubstrateAccount;503 raw: any504 } | null> {505 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);506 const humanCollection = collection.toHuman(), collectionData = {507 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],508 raw: humanCollection,509 } as any, jsonCollection = collection.toJSON();510 if (humanCollection === null) return null;511 collectionData.raw.limits = jsonCollection.limits;512 collectionData.raw.permissions = jsonCollection.permissions;513 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);514 for (const key of ['name', 'description']) {515 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);516 }517518 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))519 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)520 : 0;521 collectionData.admins = await this.getAdmins(collectionId);522523 return collectionData;524 }525526 /**527 * Get the addresses of the collection's administrators, optionally normalized.528 *529 * @param collectionId ID of collection530 * @param normalize whether to normalize the addresses to the default ss58 format531 * @example await getAdmins(1)532 * @returns array of administrators533 */534 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {535 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();536537 return normalize538 ? admins.map((address: any) => {539 return address.Substrate540 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}541 : address;542 })543 : admins;544 }545546 /**547 * Get the addresses added to the collection allow-list, optionally normalized.548 * @param collectionId ID of collection549 * @param normalize whether to normalize the addresses to the default ss58 format550 * @example await getAllowList(1)551 * @returns array of allow-listed addresses552 */553 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {554 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();555 return normalize556 ? allowListed.map((address: any) => {557 return address.Substrate558 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}559 : address;560 })561 : allowListed;562 }563564 /**565 * Get the effective limits of the collection instead of null for default values566 *567 * @param collectionId ID of collection568 * @example await getEffectiveLimits(2)569 * @returns object of collection limits570 */571 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {572 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();573 }574575 /**576 * Burns the collection if the signer has sufficient permissions and collection is empty.577 *578 * @param signer keyring of signer579 * @param collectionId ID of collection580 * @example await helper.collection.burn(aliceKeyring, 3);581 * @returns ```true``` if extrinsic success, otherwise ```false```582 */583 async burn(signer: TSigner, collectionId: number): Promise<boolean> {584 const result = await this.helper.executeExtrinsic(585 signer,586 'api.tx.unique.destroyCollection', [collectionId],587 true,588 );589590 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');591 }592593 /**594 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.595 *596 * @param signer keyring of signer597 * @param collectionId ID of collection598 * @param sponsorAddress Sponsor substrate address599 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")600 * @returns ```true``` if extrinsic success, otherwise ```false```601 */602 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {603 const result = await this.helper.executeExtrinsic(604 signer,605 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],606 true,607 );608609 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');610 }611612 /**613 * Confirms consent to sponsor the collection on behalf of the signer.614 *615 * @param signer keyring of signer616 * @param collectionId ID of collection617 * @example confirmSponsorship(aliceKeyring, 10)618 * @returns ```true``` if extrinsic success, otherwise ```false```619 */620 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {621 const result = await this.helper.executeExtrinsic(622 signer,623 'api.tx.unique.confirmSponsorship', [collectionId],624 true,625 );626627 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');628 }629630 /**631 * Removes the sponsor of a collection, regardless if it consented or not.632 *633 * @param signer keyring of signer634 * @param collectionId ID of collection635 * @example removeSponsor(aliceKeyring, 10)636 * @returns ```true``` if extrinsic success, otherwise ```false```637 */638 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {639 const result = await this.helper.executeExtrinsic(640 signer,641 'api.tx.unique.removeCollectionSponsor', [collectionId],642 true,643 );644645 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');646 }647648 /**649 * Sets the limits of the collection. At least one limit must be specified for a correct call.650 *651 * @param signer keyring of signer652 * @param collectionId ID of collection653 * @param limits collection limits object654 * @example655 * await setLimits(656 * aliceKeyring,657 * 10,658 * {659 * sponsorTransferTimeout: 0,660 * ownerCanDestroy: false661 * }662 * )663 * @returns ```true``` if extrinsic success, otherwise ```false```664 */665 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {666 const result = await this.helper.executeExtrinsic(667 signer,668 'api.tx.unique.setCollectionLimits', [collectionId, limits],669 true,670 );671672 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');673 }674675 /**676 * Changes the owner of the collection to the new Substrate address.677 *678 * @param signer keyring of signer679 * @param collectionId ID of collection680 * @param ownerAddress substrate address of new owner681 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")682 * @returns ```true``` if extrinsic success, otherwise ```false```683 */684 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {685 const result = await this.helper.executeExtrinsic(686 signer,687 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],688 true,689 );690691 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');692 }693694 /**695 * Adds a collection administrator.696 *697 * @param signer keyring of signer698 * @param collectionId ID of collection699 * @param adminAddressObj Administrator address (substrate or ethereum)700 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})701 * @returns ```true``` if extrinsic success, otherwise ```false```702 */703 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {704 const result = await this.helper.executeExtrinsic(705 signer,706 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],707 true,708 );709710 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');711 }712713 /**714 * Removes a collection administrator.715 *716 * @param signer keyring of signer717 * @param collectionId ID of collection718 * @param adminAddressObj Administrator address (substrate or ethereum)719 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})720 * @returns ```true``` if extrinsic success, otherwise ```false```721 */722 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');730 }731732 /**733 * Check if user is in allow list.734 * 735 * @param collectionId ID of collection736 * @param user Account to check737 * @example await getAdmins(1)738 * @returns is user in allow list739 */740 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {741 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();742 }743744 /**745 * Adds an address to allow list746 * @param signer keyring of signer747 * @param collectionId ID of collection748 * @param addressObj address to add to the allow list749 * @returns ```true``` if extrinsic success, otherwise ```false```750 */751 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {752 const result = await this.helper.executeExtrinsic(753 signer,754 'api.tx.unique.addToAllowList', [collectionId, addressObj],755 true,756 );757758 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');759 }760761 /**762 * Removes an address from allow list763 *764 * @param signer keyring of signer765 * @param collectionId ID of collection766 * @param addressObj address to remove from the allow list767 * @returns ```true``` if extrinsic success, otherwise ```false```768 */769 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {770 const result = await this.helper.executeExtrinsic(771 signer,772 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],773 true,774 );775776 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');777 }778779 /**780 * Sets onchain permissions for selected collection.781 *782 * @param signer keyring of signer783 * @param collectionId ID of collection784 * @param permissions collection permissions object785 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});786 * @returns ```true``` if extrinsic success, otherwise ```false```787 */788 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {789 const result = await this.helper.executeExtrinsic(790 signer,791 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],792 true,793 );794795 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');796 }797798 /**799 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.800 *801 * @param signer keyring of signer802 * @param collectionId ID of collection803 * @param permissions nesting permissions object804 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});805 * @returns ```true``` if extrinsic success, otherwise ```false```806 */807 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {808 return await this.setPermissions(signer, collectionId, {nesting: permissions});809 }810811 /**812 * Disables nesting for selected collection.813 *814 * @param signer keyring of signer815 * @param collectionId ID of collection816 * @example disableNesting(aliceKeyring, 10);817 * @returns ```true``` if extrinsic success, otherwise ```false```818 */819 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {820 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});821 }822823 /**824 * Sets onchain properties to the collection.825 *826 * @param signer keyring of signer827 * @param collectionId ID of collection828 * @param properties array of property objects829 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);830 * @returns ```true``` if extrinsic success, otherwise ```false```831 */832 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {833 const result = await this.helper.executeExtrinsic(834 signer,835 'api.tx.unique.setCollectionProperties', [collectionId, properties],836 true,837 );838839 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');840 }841842 /**843 * Deletes onchain properties from the collection.844 *845 * @param signer keyring of signer846 * @param collectionId ID of collection847 * @param propertyKeys array of property keys to delete848 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);849 * @returns ```true``` if extrinsic success, otherwise ```false```850 */851 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {852 const result = await this.helper.executeExtrinsic(853 signer,854 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],855 true,856 );857858 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');859 }860861 /**862 * Changes the owner of the token.863 *864 * @param signer keyring of signer865 * @param collectionId ID of collection866 * @param tokenId ID of token867 * @param addressObj address of a new owner868 * @param amount amount of tokens to be transfered. For NFT must be set to 1n869 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})870 * @returns true if the token success, otherwise false871 */872 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {873 const result = await this.helper.executeExtrinsic(874 signer,875 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],876 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,877 );878879 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);880 }881882 /**883 *884 * Change ownership of a token(s) on behalf of the owner.885 *886 * @param signer keyring of signer887 * @param collectionId ID of collection888 * @param tokenId ID of token889 * @param fromAddressObj address on behalf of which the token will be sent890 * @param toAddressObj new token owner891 * @param amount amount of tokens to be transfered. For NFT must be set to 1n892 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})893 * @returns true if the token success, otherwise false894 */895 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {896 const result = await this.helper.executeExtrinsic(897 signer,898 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],899 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,900 );901 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);902 }903904 /**905 *906 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.907 *908 * @param signer keyring of signer909 * @param collectionId ID of collection910 * @param tokenId ID of token911 * @param amount amount of tokens to be burned. For NFT must be set to 1n912 * @example burnToken(aliceKeyring, 10, 5);913 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```914 */915 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{916 success: boolean,917 token: number | null918 }> {919 const burnResult = await this.helper.executeExtrinsic(920 signer,921 'api.tx.unique.burnItem', [collectionId, tokenId, amount],922 true, // `Unable to burn token for ${label}`,923 );924 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);925 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');926 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};927 }928929 /**930 * Destroys a concrete instance of NFT on behalf of the owner931 *932 * @param signer keyring of signer933 * @param collectionId ID of collection934 * @param fromAddressObj address on behalf of which the token will be burnt935 * @param tokenId ID of token936 * @param amount amount of tokens to be burned. For NFT must be set to 1n937 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})938 * @returns ```true``` if extrinsic success, otherwise ```false```939 */940 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {941 const burnResult = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],944 true, // `Unable to burn token from for ${label}`,945 );946 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);947 return burnedTokens.success && burnedTokens.tokens.length > 0;948 }949950 /**951 * Set, change, or remove approved address to transfer the ownership of the NFT.952 *953 * @param signer keyring of signer954 * @param collectionId ID of collection955 * @param tokenId ID of token956 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens957 * @param amount amount of token to be approved. For NFT must be set to 1n958 * @returns ```true``` if extrinsic success, otherwise ```false```959 */960 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {961 const approveResult = await this.helper.executeExtrinsic(962 signer,963 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],964 true, // `Unable to approve token for ${label}`,965 );966967 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');968 }969970 /**971 * Get the amount of token pieces approved to transfer or burn. Normally 0.972 *973 * @param collectionId ID of collection974 * @param tokenId ID of token975 * @param toAccountObj address which is approved to use token pieces976 * @param fromAccountObj address which may have allowed the use of its owned tokens977 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})978 * @returns number of approved to transfer pieces979 */980 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {981 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();982 }983984 /**985 * Get the last created token ID in a collection986 *987 * @param collectionId ID of collection988 * @example getLastTokenId(10);989 * @returns id of the last created token990 */991 async getLastTokenId(collectionId: number): Promise<number> {992 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();993 }994995 /**996 * Check if token exists997 *998 * @param collectionId ID of collection999 * @param tokenId ID of token1000 * @example isTokenExists(10, 20);1001 * @returns true if the token exists, otherwise false1002 */1003 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1004 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1005 }1006}10071008class NFTnRFT extends CollectionGroup {1009 /**1010 * Get tokens owned by account1011 *1012 * @param collectionId ID of collection1013 * @param addressObj tokens owner1014 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1015 * @returns array of token ids owned by account1016 */1017 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1018 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1019 }10201021 /**1022 * Get token data1023 *1024 * @param collectionId ID of collection1025 * @param tokenId ID of token1026 * @param propertyKeys optionally filter the token properties to only these keys1027 * @param blockHashAt optionally query the data at some block with this hash1028 * @example getToken(10, 5);1029 * @returns human readable token data1030 */1031 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1032 properties: IProperty[];1033 owner: ICrossAccountId;1034 normalizedOwner: ICrossAccountId;1035 }| null> {1036 let tokenData;1037 if(typeof blockHashAt === 'undefined') {1038 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1039 }1040 else {1041 if(propertyKeys.length == 0) {1042 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1043 if(!collection) return null;1044 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1045 }1046 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1047 }1048 tokenData = tokenData.toHuman();1049 if (tokenData === null || tokenData.owner === null) return null;1050 const owner = {} as any;1051 for (const key of Object.keys(tokenData.owner)) {1052 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1053 }1054 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1055 return tokenData;1056 }10571058 /**1059 * Set permissions to change token properties1060 *1061 * @param signer keyring of signer1062 * @param collectionId ID of collection1063 * @param permissions permissions to change a property by the collection owner or admin1064 * @example setTokenPropertyPermissions(1065 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1066 * )1067 * @returns true if extrinsic success otherwise false1068 */1069 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1070 const result = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1073 true,1074 );10751076 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1077 }10781079 /**1080 * Set token properties1081 *1082 * @param signer keyring of signer1083 * @param collectionId ID of collection1084 * @param tokenId ID of token1085 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1086 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1087 * @returns ```true``` if extrinsic success, otherwise ```false```1088 */1089 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1090 const result = await this.helper.executeExtrinsic(1091 signer,1092 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1093 true,1094 );10951096 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1097 }10981099 /**1100 * Delete the provided properties of a token1101 * @param signer keyring of signer1102 * @param collectionId ID of collection1103 * @param tokenId ID of token1104 * @param propertyKeys property keys to be deleted1105 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1106 * @returns ```true``` if extrinsic success, otherwise ```false```1107 */1108 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1109 const result = await this.helper.executeExtrinsic(1110 signer,1111 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1112 true,1113 );11141115 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1116 }11171118 /**1119 * Mint new collection1120 *1121 * @param signer keyring of signer1122 * @param collectionOptions basic collection options and properties1123 * @param mode NFT or RFT type of a collection1124 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1125 * @returns object of the created collection1126 */1127 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1128 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1129 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1130 for (const key of ['name', 'description', 'tokenPrefix']) {1131 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);1132 }1133 const creationResult = await this.helper.executeExtrinsic(1134 signer,1135 'api.tx.unique.createCollectionEx', [collectionOptions],1136 true, // errorLabel,1137 );1138 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1139 }11401141 getCollectionObject(_collectionId: number): any {1142 return null;1143 }11441145 getTokenObject(_collectionId: number, _tokenId: number): any {1146 return null;1147 }1148}114911501151class NFTGroup extends NFTnRFT {1152 /**1153 * Get collection object1154 * @param collectionId ID of collection1155 * @example getCollectionObject(2);1156 * @returns instance of UniqueNFTCollection1157 */1158 getCollectionObject(collectionId: number): UniqueNFTCollection {1159 return new UniqueNFTCollection(collectionId, this.helper);1160 }11611162 /**1163 * Get token object1164 * @param collectionId ID of collection1165 * @param tokenId ID of token1166 * @example getTokenObject(10, 5);1167 * @returns instance of UniqueNFTToken1168 */1169 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1170 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1171 }11721173 /**1174 * Get token's owner1175 * @param collectionId ID of collection1176 * @param tokenId ID of token1177 * @param blockHashAt optionally query the data at the block with this hash1178 * @example getTokenOwner(10, 5);1179 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1180 */1181 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1182 let owner;1183 if (typeof blockHashAt === 'undefined') {1184 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1185 } else {1186 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1187 }1188 return crossAccountIdFromLower(owner.toJSON());1189 }11901191 /**1192 * Is token approved to transfer1193 * @param collectionId ID of collection1194 * @param tokenId ID of token1195 * @param toAccountObj address to be approved1196 * @returns ```true``` if extrinsic success, otherwise ```false```1197 */1198 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1199 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1200 }12011202 /**1203 * Changes the owner of the token.1204 *1205 * @param signer keyring of signer1206 * @param collectionId ID of collection1207 * @param tokenId ID of token1208 * @param addressObj address of a new owner1209 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1210 * @returns ```true``` if extrinsic success, otherwise ```false```1211 */1212 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1213 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1214 }12151216 /**1217 *1218 * Change ownership of a NFT on behalf of the owner.1219 *1220 * @param signer keyring of signer1221 * @param collectionId ID of collection1222 * @param tokenId ID of token1223 * @param fromAddressObj address on behalf of which the token will be sent1224 * @param toAddressObj new token owner1225 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1226 * @returns ```true``` if extrinsic success, otherwise ```false```1227 */1228 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1229 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1230 }12311232 /**1233 * Recursively find the address that owns the token1234 * @param collectionId ID of collection1235 * @param tokenId ID of token1236 * @param blockHashAt1237 * @example getTokenTopmostOwner(10, 5);1238 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1239 */1240 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1241 let owner;1242 if (typeof blockHashAt === 'undefined') {1243 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1244 } else {1245 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1246 }12471248 if (owner === null) return null;12491250 owner = owner.toHuman();12511252 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1253 }12541255 /**1256 * Get tokens nested in the provided token1257 * @param collectionId ID of collection1258 * @param tokenId ID of token1259 * @param blockHashAt optionally query the data at the block with this hash1260 * @example getTokenChildren(10, 5);1261 * @returns tokens whose depth of nesting is <= 51262 */1263 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1264 let children;1265 if(typeof blockHashAt === 'undefined') {1266 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1267 } else {1268 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1269 }12701271 return children.toJSON().map((x: any) => {1272 return {collectionId: x.collection, tokenId: x.token};1273 });1274 }12751276 /**1277 * Nest one token into another1278 * @param signer keyring of signer1279 * @param tokenObj token to be nested1280 * @param rootTokenObj token to be parent1281 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1282 * @returns ```true``` if extrinsic success, otherwise ```false```1283 */1284 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1285 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1286 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1287 if(!result) {1288 throw Error('Unable to nest token!');1289 }1290 return result;1291 }12921293 /**1294 * Remove token from nested state1295 * @param signer keyring of signer1296 * @param tokenObj token to unnest1297 * @param rootTokenObj parent of a token1298 * @param toAddressObj address of a new token owner1299 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1300 * @returns ```true``` if extrinsic success, otherwise ```false```1301 */1302 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1303 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1304 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1305 if(!result) {1306 throw Error('Unable to unnest token!');1307 }1308 return result;1309 }13101311 /**1312 * Mint new collection1313 * @param signer keyring of signer1314 * @param collectionOptions Collection options1315 * @example1316 * mintCollection(aliceKeyring, {1317 * name: 'New',1318 * description: 'New collection',1319 * tokenPrefix: 'NEW',1320 * })1321 * @returns object of the created collection1322 */1323 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1324 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1325 }13261327 /**1328 * Mint new token1329 * @param signer keyring of signer1330 * @param data token data1331 * @returns created token object1332 */1333 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1334 const creationResult = await this.helper.executeExtrinsic(1335 signer,1336 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1337 nft: {1338 properties: data.properties,1339 },1340 }],1341 true,1342 );1343 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1344 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1345 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1346 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1347 }13481349 /**1350 * Mint multiple NFT tokens1351 * @param signer keyring of signer1352 * @param collectionId ID of collection1353 * @param tokens array of tokens with owner and properties1354 * @example1355 * mintMultipleTokens(aliceKeyring, 10, [{1356 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1357 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1358 * },{1359 * owner: {Ethereum: "0x9F0583DbB855d..."},1360 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1361 * }]);1362 * @returns ```true``` if extrinsic success, otherwise ```false```1363 */1364 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1365 const creationResult = await this.helper.executeExtrinsic(1366 signer,1367 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1368 true,1369 );1370 const collection = this.getCollectionObject(collectionId);1371 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1372 }13731374 /**1375 * Mint multiple NFT tokens with one owner1376 * @param signer keyring of signer1377 * @param collectionId ID of collection1378 * @param owner tokens owner1379 * @param tokens array of tokens with owner and properties1380 * @example1381 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1382 * properties: [{1383 * key: "gender",1384 * value: "female",1385 * },{1386 * key: "age",1387 * value: "33",1388 * }],1389 * }]);1390 * @returns array of newly created tokens1391 */1392 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1393 const rawTokens = [];1394 for (const token of tokens) {1395 const raw = {NFT: {properties: token.properties}};1396 rawTokens.push(raw);1397 }1398 const creationResult = await this.helper.executeExtrinsic(1399 signer,1400 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1401 true,1402 );1403 const collection = this.getCollectionObject(collectionId);1404 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1405 }14061407 /**1408 * Set, change, or remove approved address to transfer the ownership of the NFT.1409 *1410 * @param signer keyring of signer1411 * @param collectionId ID of collection1412 * @param tokenId ID of token1413 * @param toAddressObj address to approve1414 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1415 * @returns ```true``` if extrinsic success, otherwise ```false```1416 */1417 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1418 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1419 }1420}142114221423class RFTGroup extends NFTnRFT {1424 /**1425 * Get collection object1426 * @param collectionId ID of collection1427 * @example getCollectionObject(2);1428 * @returns instance of UniqueRFTCollection1429 */1430 getCollectionObject(collectionId: number): UniqueRFTCollection {1431 return new UniqueRFTCollection(collectionId, this.helper);1432 }14331434 /**1435 * Get token object1436 * @param collectionId ID of collection1437 * @param tokenId ID of token1438 * @example getTokenObject(10, 5);1439 * @returns instance of UniqueNFTToken1440 */1441 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1442 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1443 }14441445 /**1446 * Get top 10 token owners with the largest number of pieces1447 * @param collectionId ID of collection1448 * @param tokenId ID of token1449 * @example getTokenTop10Owners(10, 5);1450 * @returns array of top 10 owners1451 */1452 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1453 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1454 }14551456 /**1457 * Get number of pieces owned by address1458 * @param collectionId ID of collection1459 * @param tokenId ID of token1460 * @param addressObj address token owner1461 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1462 * @returns number of pieces ownerd by address1463 */1464 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1465 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1466 }14671468 /**1469 * Transfer pieces of token to another address1470 * @param signer keyring of signer1471 * @param collectionId ID of collection1472 * @param tokenId ID of token1473 * @param addressObj address of a new owner1474 * @param amount number of pieces to be transfered1475 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1476 * @returns ```true``` if extrinsic success, otherwise ```false```1477 */1478 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1479 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1480 }14811482 /**1483 * Change ownership of some pieces of RFT on behalf of the owner.1484 * @param signer keyring of signer1485 * @param collectionId ID of collection1486 * @param tokenId ID of token1487 * @param fromAddressObj address on behalf of which the token will be sent1488 * @param toAddressObj new token owner1489 * @param amount number of pieces to be transfered1490 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1491 * @returns ```true``` if extrinsic success, otherwise ```false```1492 */1493 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1494 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1495 }14961497 /**1498 * Mint new collection1499 * @param signer keyring of signer1500 * @param collectionOptions Collection options1501 * @example1502 * mintCollection(aliceKeyring, {1503 * name: 'New',1504 * description: 'New collection',1505 * tokenPrefix: 'NEW',1506 * })1507 * @returns object of the created collection1508 */1509 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1510 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1511 }15121513 /**1514 * Mint new token1515 * @param signer keyring of signer1516 * @param data token data1517 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1518 * @returns created token object1519 */1520 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1521 const creationResult = await this.helper.executeExtrinsic(1522 signer,1523 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1524 refungible: {1525 pieces: data.pieces,1526 properties: data.properties,1527 },1528 }],1529 true,1530 );1531 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1532 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1533 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1534 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1535 }15361537 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1538 throw Error('Not implemented');1539 const creationResult = await this.helper.executeExtrinsic(1540 signer,1541 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1542 true, // `Unable to mint RFT tokens for ${label}`,1543 );1544 const collection = this.getCollectionObject(collectionId);1545 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1546 }15471548 /**1549 * Mint multiple RFT tokens with one owner1550 * @param signer keyring of signer1551 * @param collectionId ID of collection1552 * @param owner tokens owner1553 * @param tokens array of tokens with properties and pieces1554 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1555 * @returns array of newly created RFT tokens1556 */1557 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1558 const rawTokens = [];1559 for (const token of tokens) {1560 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1561 rawTokens.push(raw);1562 }1563 const creationResult = await this.helper.executeExtrinsic(1564 signer,1565 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1566 true,1567 );1568 const collection = this.getCollectionObject(collectionId);1569 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1570 }15711572 /**1573 * Destroys a concrete instance of RFT.1574 * @param signer keyring of signer1575 * @param collectionId ID of collection1576 * @param tokenId ID of token1577 * @param amount number of pieces to be burnt1578 * @example burnToken(aliceKeyring, 10, 5);1579 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1580 */1581 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1582 return await super.burnToken(signer, collectionId, tokenId, amount);1583 }15841585 /**1586 * Set, change, or remove approved address to transfer the ownership of the RFT.1587 *1588 * @param signer keyring of signer1589 * @param collectionId ID of collection1590 * @param tokenId ID of token1591 * @param toAddressObj address to approve1592 * @param amount number of pieces to be approved1593 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1594 * @returns true if the token success, otherwise false1595 */1596 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1597 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1598 }15991600 /**1601 * Get total number of pieces1602 * @param collectionId ID of collection1603 * @param tokenId ID of token1604 * @example getTokenTotalPieces(10, 5);1605 * @returns number of pieces1606 */1607 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1608 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1609 }16101611 /**1612 * Change number of token pieces. Signer must be the owner of all token pieces.1613 * @param signer keyring of signer1614 * @param collectionId ID of collection1615 * @param tokenId ID of token1616 * @param amount new number of pieces1617 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1618 * @returns true if the repartion was success, otherwise false1619 */1620 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1621 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1622 const repartitionResult = await this.helper.executeExtrinsic(1623 signer,1624 'api.tx.unique.repartition', [collectionId, tokenId, amount],1625 true,1626 );1627 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1628 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1629 }1630}163116321633class FTGroup extends CollectionGroup {1634 /**1635 * Get collection object1636 * @param collectionId ID of collection1637 * @example getCollectionObject(2);1638 * @returns instance of UniqueFTCollection1639 */1640 getCollectionObject(collectionId: number): UniqueFTCollection {1641 return new UniqueFTCollection(collectionId, this.helper);1642 }16431644 /**1645 * Mint new fungible collection1646 * @param signer keyring of signer1647 * @param collectionOptions Collection options1648 * @param decimalPoints number of token decimals1649 * @example1650 * mintCollection(aliceKeyring, {1651 * name: 'New',1652 * description: 'New collection',1653 * tokenPrefix: 'NEW',1654 * }, 18)1655 * @returns newly created fungible collection1656 */1657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1658 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1659 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1660 collectionOptions.mode = {fungible: decimalPoints};1661 for (const key of ['name', 'description', 'tokenPrefix']) {1662 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);1663 }1664 const creationResult = await this.helper.executeExtrinsic(1665 signer,1666 'api.tx.unique.createCollectionEx', [collectionOptions],1667 true,1668 );1669 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1670 }16711672 /**1673 * Mint tokens1674 * @param signer keyring of signer1675 * @param collectionId ID of collection1676 * @param owner address owner of new tokens1677 * @param amount amount of tokens to be meanted1678 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1679 * @returns ```true``` if extrinsic success, otherwise ```false```1680 */1681 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1682 const creationResult = await this.helper.executeExtrinsic(1683 signer,1684 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1685 fungible: {1686 value: amount,1687 },1688 }],1689 true, // `Unable to mint fungible tokens for ${label}`,1690 );1691 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1692 }16931694 /**1695 * Mint multiple Fungible tokens with one owner1696 * @param signer keyring of signer1697 * @param collectionId ID of collection1698 * @param owner tokens owner1699 * @param tokens array of tokens with properties and pieces1700 * @returns ```true``` if extrinsic success, otherwise ```false```1701 */1702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1703 const rawTokens = [];1704 for (const token of tokens) {1705 const raw = {Fungible: {Value: token.value}};1706 rawTokens.push(raw);1707 }1708 const creationResult = await this.helper.executeExtrinsic(1709 signer,1710 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1711 true,1712 );1713 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1714 }17151716 /**1717 * Get the top 10 owners with the largest balance for the Fungible collection1718 * @param collectionId ID of collection1719 * @example getTop10Owners(10);1720 * @returns array of ```ICrossAccountId```1721 */1722 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724 }17251726 /**1727 * Get account balance1728 * @param collectionId ID of collection1729 * @param addressObj address of owner1730 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1731 * @returns amount of fungible tokens owned by address1732 */1733 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735 }17361737 /**1738 * Transfer tokens to address1739 * @param signer keyring of signer1740 * @param collectionId ID of collection1741 * @param toAddressObj address recipient1742 * @param amount amount of tokens to be sent1743 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1744 * @returns ```true``` if extrinsic success, otherwise ```false```1745 */1746 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1747 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748 }17491750 /**1751 * Transfer some tokens on behalf of the owner.1752 * @param signer keyring of signer1753 * @param collectionId ID of collection1754 * @param fromAddressObj address on behalf of which tokens will be sent1755 * @param toAddressObj address where token to be sent1756 * @param amount number of tokens to be sent1757 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1758 * @returns ```true``` if extrinsic success, otherwise ```false```1759 */1760 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1761 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1762 }17631764 /**1765 * Destroy some amount of tokens1766 * @param signer keyring of signer1767 * @param collectionId ID of collection1768 * @param amount amount of tokens to be destroyed1769 * @example burnTokens(aliceKeyring, 10, 1000n);1770 * @returns ```true``` if extrinsic success, otherwise ```false```1771 */1772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, amount)).success;1774 }17751776 /**1777 * Burn some tokens on behalf of the owner.1778 * @param signer keyring of signer1779 * @param collectionId ID of collection1780 * @param fromAddressObj address on behalf of which tokens will be burnt1781 * @param amount amount of tokens to be burnt1782 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1783 * @returns ```true``` if extrinsic success, otherwise ```false```1784 */1785 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1786 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1787 }17881789 /**1790 * Get total collection supply1791 * @param collectionId1792 * @returns1793 */1794 async getTotalPieces(collectionId: number): Promise<bigint> {1795 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1796 }17971798 /**1799 * Set, change, or remove approved address to transfer tokens.1800 *1801 * @param signer keyring of signer1802 * @param collectionId ID of collection1803 * @param toAddressObj address to be approved1804 * @param amount amount of tokens to be approved1805 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1806 * @returns ```true``` if extrinsic success, otherwise ```false```1807 */1808 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1809 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1810 }18111812 /**1813 * Get amount of fungible tokens approved to transfer1814 * @param collectionId ID of collection1815 * @param fromAddressObj owner of tokens1816 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1817 * @returns number of tokens approved for the transfer1818 */1819 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1820 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1821 }1822}182318241825class ChainGroup extends HelperGroup {1826 /**1827 * Get system properties of a chain1828 * @example getChainProperties();1829 * @returns ss58Format, token decimals, and token symbol1830 */1831 getChainProperties(): IChainProperties {1832 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1833 return {1834 ss58Format: properties.ss58Format.toJSON(),1835 tokenDecimals: properties.tokenDecimals.toJSON(),1836 tokenSymbol: properties.tokenSymbol.toJSON(),1837 };1838 }18391840 /**1841 * Get chain header1842 * @example getLatestBlockNumber();1843 * @returns the number of the last block1844 */1845 async getLatestBlockNumber(): Promise<number> {1846 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1847 }18481849 /**1850 * Get block hash by block number1851 * @param blockNumber number of block1852 * @example getBlockHashByNumber(12345);1853 * @returns hash of a block1854 */1855 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1856 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1857 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1858 return blockHash;1859 }18601861 // TODO add docs1862 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1863 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1864 if (!blockHash) return null;1865 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1866 }18671868 /**1869 * Get account nonce1870 * @param address substrate address1871 * @example getNonce("5GrwvaEF5zXb26Fz...");1872 * @returns number, account's nonce1873 */1874 async getNonce(address: TSubstrateAccount): Promise<number> {1875 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1876 }1877}187818791880class BalanceGroup extends HelperGroup {1881 /**1882 * Representation of the native token in the smallest unit1883 * @example getOneTokenNominal()1884 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1885 */1886 getOneTokenNominal(): bigint {1887 const chainProperties = this.helper.chain.getChainProperties();1888 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1889 }18901891 /**1892 * Get substrate address balance1893 * @param address substrate address1894 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1895 * @returns amount of tokens on address1896 */1897 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1898 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1899 }19001901 /**1902 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1903 * @param address substrate address1904 * @returns1905 */1906 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1907 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1908 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1909 }19101911 /**1912 * Get ethereum address balance1913 * @param address ethereum address1914 * @example getEthereum("0x9F0583DbB855d...")1915 * @returns amount of tokens on address1916 */1917 async getEthereum(address: TEthereumAccount): Promise<bigint> {1918 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1919 }19201921 /**1922 * Transfer tokens to substrate address1923 * @param signer keyring of signer1924 * @param address substrate address of a recipient1925 * @param amount amount of tokens to be transfered1926 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1927 * @returns ```true``` if extrinsic success, otherwise ```false```1928 */1929 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1930 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}`*/);19311932 let transfer = {from: null, to: null, amount: 0n} as any;1933 result.result.events.forEach(({event: {data, method, section}}) => {1934 if ((section === 'balances') && (method === 'Transfer')) {1935 transfer = {1936 from: this.helper.address.normalizeSubstrate(data[0]),1937 to: this.helper.address.normalizeSubstrate(data[1]),1938 amount: BigInt(data[2]),1939 };1940 }1941 });1942 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1943 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1944 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1945 return isSuccess;1946 }1947}194819491950class AddressGroup extends HelperGroup {1951 /**1952 * Normalizes the address to the specified ss58 format, by default ```42```.1953 * @param address substrate address1954 * @param ss58Format format for address conversion, by default ```42```1955 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY1956 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation1957 */1958 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1959 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1960 }19611962 /**1963 * Get address in the connected chain format1964 * @param address substrate address1965 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network1966 * @returns address in chain format1967 */1968 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1969 const info = this.helper.chain.getChainProperties();1970 return encodeAddress(decodeAddress(address), info.ss58Format);1971 }19721973 /**1974 * Get substrate mirror of an ethereum address1975 * @param ethAddress ethereum address1976 * @param toChainFormat false for normalized account1977 * @example ethToSubstrate('0x9F0583DbB855d...')1978 * @returns substrate mirror of a provided ethereum address1979 */1980 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1981 if(!toChainFormat) return evmToAddress(ethAddress);1982 const info = this.helper.chain.getChainProperties();1983 return evmToAddress(ethAddress, info.ss58Format);1984 }19851986 /**1987 * Get ethereum mirror of a substrate address1988 * @param subAddress substrate account1989 * @example substrateToEth("5DnSF6RRjwteE3BrC...")1990 * @returns ethereum mirror of a provided substrate address1991 */1992 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1993 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1994 }1995}19961997class StakingGroup extends HelperGroup {1998 /**1999 * Stake tokens for App Promotion2000 * @param signer keyring of signer2001 * @param amountToStake amount of tokens to stake2002 * @param label extra label for log2003 * @returns2004 */2005 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2006 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2007 const stakeResult = await this.helper.executeExtrinsic(2008 signer, 'api.tx.appPromotion.stake',2009 [amountToStake], true,2010 );2011 // TODO extract info from stakeResult2012 return true;2013 }20142015 /**2016 * Unstake tokens for App Promotion2017 * @param signer keyring of signer2018 * @param amountToUnstake amount of tokens to unstake2019 * @param label extra label for log2020 * @returns block number where balances will be unlocked2021 */2022 async unstake(signer: TSigner, label?: string): Promise<number> {2023 if(typeof label === 'undefined') label = `${signer.address}`;2024 const unstakeResult = await this.helper.executeExtrinsic(2025 signer, 'api.tx.appPromotion.unstake',2026 [], true,2027 );2028 // TODO extract block number fron events2029 return 1;2030 }20312032 /**2033 * Get total staked amount for address2034 * @param address substrate or ethereum address2035 * @returns total staked amount2036 */2037 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2038 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2039 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2040 }20412042 /**2043 * Get total staked per block2044 * @param address substrate or ethereum address2045 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2046 */2047 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2048 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2049 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2050 return { 2051 block: block.toBigInt(),2052 amount: amount.toBigInt(),2053 };2054 });2055 }20562057 /**2058 * Get total pending unstake amount for address2059 * @param address substrate or ethereum address2060 * @returns total pending unstake amount2061 */2062 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2063 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2064 }20652066 /**2067 * Get pending unstake amount per block for address2068 * @param address substrate or ethereum address2069 * @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 block2070 */2071 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2072 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2073 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2074 return {2075 block: block.toBigInt(),2076 amount: amount.toBigInt(),2077 };2078 });2079 return result;2080 }2081}20822083export class UniqueHelper extends ChainHelperBase {2084 chain: ChainGroup;2085 balance: BalanceGroup;2086 address: AddressGroup;2087 collection: CollectionGroup;2088 nft: NFTGroup;2089 rft: RFTGroup;2090 ft: FTGroup;2091 staking: StakingGroup;20922093 constructor(logger?: ILogger) {2094 super(logger);2095 this.chain = new ChainGroup(this);2096 this.balance = new BalanceGroup(this);2097 this.address = new AddressGroup(this);2098 this.collection = new CollectionGroup(this);2099 this.nft = new NFTGroup(this);2100 this.rft = new RFTGroup(this);2101 this.ft = new FTGroup(this);2102 this.staking = new StakingGroup(this);2103 }2104}210521062107class UniqueCollectionBase {2108 helper: UniqueHelper;2109 collectionId: number;21102111 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2112 this.collectionId = collectionId;2113 this.helper = uniqueHelper;2114 }21152116 async getData() {2117 return await this.helper.collection.getData(this.collectionId);2118 }21192120 async getLastTokenId() {2121 return await this.helper.collection.getLastTokenId(this.collectionId);2122 }21232124 async isTokenExists(tokenId: number) {2125 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2126 }21272128 async getAdmins() {2129 return await this.helper.collection.getAdmins(this.collectionId);2130 }21312132 async getAllowList() {2133 return await this.helper.collection.getAllowList(this.collectionId);2134 }21352136 async getEffectiveLimits() {2137 return await this.helper.collection.getEffectiveLimits(this.collectionId);2138 }21392140 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2141 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2142 }21432144 async confirmSponsorship(signer: TSigner) {2145 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2146 }21472148 async removeSponsor(signer: TSigner) {2149 return await this.helper.collection.removeSponsor(signer, this.collectionId);2150 }21512152 async setLimits(signer: TSigner, limits: ICollectionLimits) {2153 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2154 }21552156 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2157 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2158 }21592160 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2161 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2162 }21632164 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2165 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2166 }21672168 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2169 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2170 }21712172 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2173 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2174 }21752176 async setProperties(signer: TSigner, properties: IProperty[]) {2177 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2178 }21792180 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2181 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2182 }21832184 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2185 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2186 }21872188 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2189 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2190 }21912192 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2193 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2194 }21952196 async disableNesting(signer: TSigner) {2197 return await this.helper.collection.disableNesting(signer, this.collectionId);2198 }21992200 async burn(signer: TSigner) {2201 return await this.helper.collection.burn(signer, this.collectionId);2202 }2203}220422052206class UniqueNFTCollection extends UniqueCollectionBase {2207 getTokenObject(tokenId: number) {2208 return new UniqueNFTToken(tokenId, this);2209 }22102211 async getTokensByAddress(addressObj: ICrossAccountId) {2212 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2213 }22142215 async getToken(tokenId: number, blockHashAt?: string) {2216 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2217 }22182219 async getTokenOwner(tokenId: number, blockHashAt?: string) {2220 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2221 }22222223 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2224 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2225 }22262227 async getTokenChildren(tokenId: number, blockHashAt?: string) {2228 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2229 }22302231 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2232 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2233 }22342235 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2236 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2237 }22382239 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2240 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2241 }22422243 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2244 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2245 }22462247 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2248 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2249 }22502251 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2252 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2253 }22542255 async burnToken(signer: TSigner, tokenId: number) {2256 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2257 }22582259 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2260 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2261 }22622263 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2264 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2265 }22662267 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2268 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2269 }22702271 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2272 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2273 }22742275 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2276 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2277 }2278}227922802281class UniqueRFTCollection extends UniqueCollectionBase {2282 getTokenObject(tokenId: number) {2283 return new UniqueRFTToken(tokenId, this);2284 }22852286 async getTokensByAddress(addressObj: ICrossAccountId) {2287 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2288 }22892290 async getTop10TokenOwners(tokenId: number) {2291 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2292 }22932294 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2295 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2296 }22972298 async getTokenTotalPieces(tokenId: number) {2299 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2300 }23012302 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2303 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2304 }23052306 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2307 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2308 }23092310 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2311 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2312 }23132314 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2315 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2316 }23172318 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2319 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2320 }23212322 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2323 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2324 }23252326 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2327 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2328 }23292330 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2331 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2332 }23332334 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2335 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2336 }23372338 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2339 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2340 }23412342 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2343 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2344 }2345}234623472348class UniqueFTCollection extends UniqueCollectionBase {2349 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2350 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2351 }23522353 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2354 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2355 }23562357 async getBalance(addressObj: ICrossAccountId) {2358 return await this.helper.ft.getBalance(this.collectionId, addressObj);2359 }23602361 async getTop10Owners() {2362 return await this.helper.ft.getTop10Owners(this.collectionId);2363 }23642365 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2366 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2367 }23682369 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2370 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2371 }23722373 async burnTokens(signer: TSigner, amount=1n) {2374 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2375 }23762377 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2378 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2379 }23802381 async getTotalPieces() {2382 return await this.helper.ft.getTotalPieces(this.collectionId);2383 }23842385 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2386 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2387 }23882389 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2390 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2391 }2392}239323942395class UniqueTokenBase implements IToken {2396 collection: UniqueNFTCollection | UniqueRFTCollection;2397 collectionId: number;2398 tokenId: number;23992400 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2401 this.collection = collection;2402 this.collectionId = collection.collectionId;2403 this.tokenId = tokenId;2404 }24052406 async getNextSponsored(addressObj: ICrossAccountId) {2407 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2408 }24092410 async setProperties(signer: TSigner, properties: IProperty[]) {2411 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2412 }24132414 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2415 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2416 }2417}241824192420class UniqueNFTToken extends UniqueTokenBase {2421 collection: UniqueNFTCollection;24222423 constructor(tokenId: number, collection: UniqueNFTCollection) {2424 super(tokenId, collection);2425 this.collection = collection;2426 }24272428 async getData(blockHashAt?: string) {2429 return await this.collection.getToken(this.tokenId, blockHashAt);2430 }24312432 async getOwner(blockHashAt?: string) {2433 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2434 }24352436 async getTopmostOwner(blockHashAt?: string) {2437 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2438 }24392440 async getChildren(blockHashAt?: string) {2441 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2442 }24432444 async nest(signer: TSigner, toTokenObj: IToken) {2445 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2446 }24472448 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2449 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2450 }24512452 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2453 return await this.collection.transferToken(signer, this.tokenId, addressObj);2454 }24552456 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2457 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2458 }24592460 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2461 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2462 }24632464 async isApproved(toAddressObj: ICrossAccountId) {2465 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2466 }24672468 async burn(signer: TSigner) {2469 return await this.collection.burnToken(signer, this.tokenId);2470 }2471}24722473class UniqueRFTToken extends UniqueTokenBase {2474 collection: UniqueRFTCollection;24752476 constructor(tokenId: number, collection: UniqueRFTCollection) {2477 super(tokenId, collection);2478 this.collection = collection;2479 }24802481 async getTop10Owners() {2482 return await this.collection.getTop10TokenOwners(this.tokenId);2483 }24842485 async getBalance(addressObj: ICrossAccountId) {2486 return await this.collection.getTokenBalance(this.tokenId, addressObj);2487 }24882489 async getTotalPieces() {2490 return await this.collection.getTokenTotalPieces(this.tokenId);2491 }24922493 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2494 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2495 }24962497 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2498 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2499 }25002501 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2502 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2503 }25042505 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2506 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2507 }25082509 async repartition(signer: TSigner, amount: bigint) {2510 return await this.collection.repartitionToken(signer, this.tokenId, amount);2511 }25122513 async burn(signer: TSigner, amount=1n) {2514 return await this.collection.burnToken(signer, this.tokenId, amount);2515 }2516}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// SPDX-License-Identifier: Apache-2.034/* eslint-disable @typescript-eslint/no-var-requires */5/* eslint-disable function-call-argument-newline */6/* eslint-disable no-prototype-builtins */78import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 // If ith character is 8 to f then make it uppercase33 if (parseInt(addressHash[i], 16) > 7) {34 checksumAddress.push(address[i].toUpperCase());35 } else {36 checksumAddress.push(address[i]);37 }38 }39 return checksumAddress.join('');40 },41 tokenIdToAddress(collectionId: number, tokenId: number) {42 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8,'0')}${tokenId.toString(16).padStart(8,'0')}`);43 },44};4546class UniqueUtil {47 static transactionStatus = {48 NOT_READY: 'NotReady',49 FAIL: 'Fail',50 SUCCESS: 'Success',51 };5253 static chainLogType = {54 EXTRINSIC: 'extrinsic',55 RPC: 'rpc',56 };5758 static getNestingTokenAddress(collectionId: number, tokenId: number) {59 return nesting.tokenIdToAddress(collectionId, tokenId);60 }6162 static getDefaultLogger(): ILogger {63 return {64 log(msg: any, level = 'INFO') {65 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));66 },67 level: {68 ERROR: 'ERROR',69 WARNING: 'WARNING',70 INFO: 'INFO',71 },72 };73 }7475 static vec2str(arr: string[] | number[]) {76 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');77 }7879 static str2vec(string: string) {80 if (typeof string !== 'string') return string;81 return Array.from(string).map(x => x.charCodeAt(0));82 }8384 static fromSeed(seed: string, ss58Format = 42) {85 const keyring = new Keyring({type: 'sr25519', ss58Format});86 return keyring.addFromUri(seed);87 }8889 static normalizeSubstrateAddress(address: string, ss58Format = 42) {90 return encodeAddress(decodeAddress(address), ss58Format);91 }9293 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {94 if (creationResult.status !== this.transactionStatus.SUCCESS) {95 throw Error('Unable to create collection!');96 }9798 let collectionId = null;99 creationResult.result.events.forEach(({event: {data, method, section}}) => {100 if ((section === 'common') && (method === 'CollectionCreated')) {101 collectionId = parseInt(data[0].toString(), 10);102 }103 });104105 if (collectionId === null) {106 throw Error('No CollectionCreated event was found!');107 }108109 return collectionId;110 }111112 static extractTokensFromCreationResult(creationResult: ITransactionResult) {113 if (creationResult.status !== this.transactionStatus.SUCCESS) {114 throw Error('Unable to create tokens!');115 }116 let success = false;117 const tokens = [] as any;118 creationResult.result.events.forEach(({event: {data, method, section}}) => {119 if (method === 'ExtrinsicSuccess') {120 success = true;121 } else if ((section === 'common') && (method === 'ItemCreated')) {122 tokens.push({123 collectionId: parseInt(data[0].toString(), 10),124 tokenId: parseInt(data[1].toString(), 10),125 owner: data[2].toJSON(),126 });127 }128 });129 return {success, tokens};130 }131132 static extractTokensFromBurnResult(burnResult: ITransactionResult) {133 if (burnResult.status !== this.transactionStatus.SUCCESS) {134 throw Error('Unable to burn tokens!');135 }136 let success = false;137 const tokens = [] as any;138 burnResult.result.events.forEach(({event: {data, method, section}}) => {139 if (method === 'ExtrinsicSuccess') {140 success = true;141 } else if ((section === 'common') && (method === 'ItemDestroyed')) {142 tokens.push({143 collectionId: parseInt(data[0].toString(), 10),144 tokenId: parseInt(data[1].toString(), 10),145 owner: data[2].toJSON(),146 });147 }148 });149 return {success, tokens};150 }151152 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {153 let eventId = null;154 events.forEach(({event: {data, method, section}}) => {155 if ((section === expectedSection) && (method === expectedMethod)) {156 eventId = parseInt(data[0].toString(), 10);157 }158 });159160 if (eventId === null) {161 throw Error(`No ${expectedMethod} event was found!`);162 }163 return eventId === collectionId;164 }165166 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {167 const normalizeAddress = (address: string | ICrossAccountId) => {168 if(typeof address === 'string') return address;169 const obj = {} as any;170 Object.keys(address).forEach(k => {171 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];172 });173 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};174 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};175 return address;176 };177 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;178 events.forEach(({event: {data, method, section}}) => {179 if ((section === 'common') && (method === 'Transfer')) {180 const hData = (data as any).toJSON();181 transfer = {182 collectionId: hData[0],183 tokenId: hData[1],184 from: normalizeAddress(hData[2]),185 to: normalizeAddress(hData[3]),186 amount: BigInt(hData[4]),187 };188 }189 });190 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;191 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);193 isSuccess = isSuccess && amount === transfer.amount;194 return isSuccess;195 }196}197198class UniqueEventHelper {199 private static extractIndex(index: any): [number, number] | string {200 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];201 return index.toJSON();202 }203204 private static extractSub(data: any, subTypes: any): {[key: string]: any} {205 let obj: any = {};206 let index = 0;207208 if (data.entries)209 for(const [key, value] of data.entries()) {210 obj[key] = this.extractData(value, subTypes[index]);211 index++;212 }213 else obj = data.toJSON();214215 return obj;216 }217 218 private static extractData(data: any, type: any): any {219 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();220 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();221 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);222 return data.toHuman();223 }224225 public static extractEvents(records: ITransactionResult): IEvent[] {226 const parsedEvents: IEvent[] = [];227228 records.result.events.forEach((record) => {229 const {event, phase} = record;230 const types = (event as any).typeDef;231232 const eventData: IEvent = {233 section: event.section.toString(),234 method: event.method.toString(),235 index: this.extractIndex(event.index),236 data: [],237 phase: phase.toJSON(),238 };239240 event.data.forEach((val: any, index: number) => {241 eventData.data.push(this.extractData(val, types[index]));242 });243244 parsedEvents.push(eventData);245 });246247 return parsedEvents;248 }249}250251class ChainHelperBase {252 transactionStatus = UniqueUtil.transactionStatus;253 chainLogType = UniqueUtil.chainLogType;254 util: typeof UniqueUtil;255 eventHelper: typeof UniqueEventHelper;256 logger: ILogger;257 api: ApiPromise | null;258 forcedNetwork: TUniqueNetworks | null;259 network: TUniqueNetworks | null;260 chainLog: IUniqueHelperLog[];261262 constructor(logger?: ILogger) {263 this.util = UniqueUtil;264 this.eventHelper = UniqueEventHelper;265 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();266 this.logger = logger;267 this.api = null;268 this.forcedNetwork = null;269 this.network = null;270 this.chainLog = [];271 }272273 clearChainLog(): void {274 this.chainLog = [];275 }276277 forceNetwork(value: TUniqueNetworks): void {278 this.forcedNetwork = value;279 }280281 async connect(wsEndpoint: string, listeners?: IApiListeners) {282 if (this.api !== null) throw Error('Already connected');283 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);284 this.api = api;285 this.network = network;286 }287288 async disconnect() {289 if (this.api === null) return;290 await this.api.disconnect();291 this.api = null;292 this.network = null;293 }294295 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {296 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;297 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;298 return 'opal';299 }300301 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {302 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});303 await api.isReady;304305 const network = await this.detectNetwork(api);306307 await api.disconnect();308309 return network;310 }311312 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{313 api: ApiPromise;314 network: TUniqueNetworks;315 }> {316 if(typeof network === 'undefined' || network === null) network = 'opal';317 const supportedRPC = {318 opal: {319 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,320 },321 quartz: {322 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,323 },324 unique: {325 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,326 },327 };328 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);329 const rpc = supportedRPC[network];330331 // TODO: investigate how to replace rpc in runtime332 // api._rpcCore.addUserInterfaces(rpc);333334 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});335336 await api.isReadyOrError;337338 if (typeof listeners === 'undefined') listeners = {};339 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {340 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;341 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);342 }343344 return {api, network};345 }346347 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {348 const {events, status} = data;349 if (status.isReady) {350 return this.transactionStatus.NOT_READY;351 }352 if (status.isBroadcast) {353 return this.transactionStatus.NOT_READY;354 }355 if (status.isInBlock || status.isFinalized) {356 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');357 if (errors.length > 0) {358 return this.transactionStatus.FAIL;359 }360 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {361 return this.transactionStatus.SUCCESS;362 }363 }364365 return this.transactionStatus.FAIL;366 }367368 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {369 const sign = (callback: any) => {370 if(options !== null) return transaction.signAndSend(sender, options, callback);371 return transaction.signAndSend(sender, callback);372 };373 // eslint-disable-next-line no-async-promise-executor374 return new Promise(async (resolve, reject) => {375 try {376 const unsub = await sign((result: any) => {377 const status = this.getTransactionStatus(result);378379 if (status === this.transactionStatus.SUCCESS) {380 this.logger.log(`${label} successful`);381 unsub();382 resolve({result, status});383 } else if (status === this.transactionStatus.FAIL) {384 let moduleError = null;385386 if (result.hasOwnProperty('dispatchError')) {387 const dispatchError = result['dispatchError'];388389 if (dispatchError) {390 if (dispatchError.isModule) {391 const modErr = dispatchError.asModule;392 const errorMeta = dispatchError.registry.findMetaError(modErr);393394 moduleError = `${errorMeta.section}.${errorMeta.name}`;395 } else {396 moduleError = dispatchError.toHuman();397 }398 } else {399 this.logger.log(result, this.logger.level.ERROR);400 }401 }402403 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);404 unsub();405 reject({status, moduleError, result});406 }407 });408 } catch (e) {409 this.logger.log(e, this.logger.level.ERROR);410 reject(e);411 }412 });413 }414415 constructApiCall(apiCall: string, params: any[]) {416 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);417 let call = this.api as any;418 for(const part of apiCall.slice(4).split('.')) {419 call = call[part];420 }421 return call(...params);422 }423424 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true/*, failureMessage='expected success'*/) {425 if(this.api === null) throw Error('API not initialized');426 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);427428 const startTime = (new Date()).getTime();429 let result: ITransactionResult;430 let events: IEvent[] = [];431 try {432 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;433 events = this.eventHelper.extractEvents(result);434 }435 catch(e) {436 if(!(e as object).hasOwnProperty('status')) throw e;437 result = e as ITransactionResult;438 }439440 const endTime = (new Date()).getTime();441442 const log = {443 executedAt: endTime,444 executionTime: endTime - startTime,445 type: this.chainLogType.EXTRINSIC,446 status: result.status,447 call: extrinsic,448 signer: this.getSignerAddress(sender),449 params,450 } as IUniqueHelperLog;451452 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;453 if(events.length > 0) log.events = events;454455 this.chainLog.push(log);456457 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);458 return result;459 }460461 async callRpc(rpc: string, params?: any[]) {462 if(typeof params === 'undefined') params = [];463 if(this.api === null) throw Error('API not initialized');464 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);465466 const startTime = (new Date()).getTime();467 let result;468 let error = null;469 const log = {470 type: this.chainLogType.RPC,471 call: rpc,472 params,473 } as IUniqueHelperLog;474475 try {476 result = await this.constructApiCall(rpc, params);477 }478 catch(e) {479 error = e;480 }481482 const endTime = (new Date()).getTime();483484 log.executedAt = endTime;485 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';486 log.executionTime = endTime - startTime;487488 this.chainLog.push(log);489490 if(error !== null) throw error;491492 return result;493 }494495 getSignerAddress(signer: IKeyringPair | string): string {496 if(typeof signer === 'string') return signer;497 return signer.address;498 }499500 fetchAllPalletNames(): string[] {501 if(this.api === null) throw Error('API not initialized');502 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());503 }504505 fetchMissingPalletNames(requiredPallets: string[]): string[] {506 const palletNames = this.fetchAllPalletNames();507 return requiredPallets.filter(p => !palletNames.includes(p));508 }509}510511512class HelperGroup {513 helper: UniqueHelper;514515 constructor(uniqueHelper: UniqueHelper) {516 this.helper = uniqueHelper;517 }518}519520521class CollectionGroup extends HelperGroup {522 /**523 * Get number of blocks when sponsored transaction is available.524 *525 * @param collectionId ID of collection526 * @param tokenId ID of token527 * @param addressObj address for which the sponsorship is checked528 * @example await getTokenNextSponsored(1, 2, {Substrate: '5DfhbVfww7ThF8q6f3...'});529 * @returns number of blocks or null if sponsorship hasn't been set530 */531 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {532 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();533 }534535 /**536 * Get the number of created collections.537 *538 * @returns number of created collections539 */540 async getTotalCount(): Promise<number> {541 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();542 }543544 /**545 * Get information about the collection with additional data,546 * including the number of tokens it contains, its administrators,547 * the normalized address of the collection's owner, and decoded name and description.548 *549 * @param collectionId ID of collection550 * @example await getData(2)551 * @returns collection information object552 */553 async getData(collectionId: number): Promise<{554 id: number;555 name: string;556 description: string;557 tokensCount: number;558 admins: ICrossAccountId[];559 normalizedOwner: TSubstrateAccount;560 raw: any561 } | null> {562 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);563 const humanCollection = collection.toHuman(), collectionData = {564 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],565 raw: humanCollection,566 } as any, jsonCollection = collection.toJSON();567 if (humanCollection === null) return null;568 collectionData.raw.limits = jsonCollection.limits;569 collectionData.raw.permissions = jsonCollection.permissions;570 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);571 for (const key of ['name', 'description']) {572 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);573 }574575 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))576 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)577 : 0;578 collectionData.admins = await this.getAdmins(collectionId);579580 return collectionData;581 }582583 /**584 * Get the addresses of the collection's administrators, optionally normalized.585 *586 * @param collectionId ID of collection587 * @param normalize whether to normalize the addresses to the default ss58 format588 * @example await getAdmins(1)589 * @returns array of administrators590 */591 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {592 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();593594 return normalize595 ? admins.map((address: any) => {596 return address.Substrate597 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}598 : address;599 })600 : admins;601 }602603 /**604 * Get the addresses added to the collection allow-list, optionally normalized.605 * @param collectionId ID of collection606 * @param normalize whether to normalize the addresses to the default ss58 format607 * @example await getAllowList(1)608 * @returns array of allow-listed addresses609 */610 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {611 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();612 return normalize613 ? allowListed.map((address: any) => {614 return address.Substrate615 ? {Substrate: this.helper.address.normalizeSubstrate(address.Substrate)}616 : address;617 })618 : allowListed;619 }620621 /**622 * Get the effective limits of the collection instead of null for default values623 *624 * @param collectionId ID of collection625 * @example await getEffectiveLimits(2)626 * @returns object of collection limits627 */628 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {629 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();630 }631632 /**633 * Burns the collection if the signer has sufficient permissions and collection is empty.634 *635 * @param signer keyring of signer636 * @param collectionId ID of collection637 * @example await helper.collection.burn(aliceKeyring, 3);638 * @returns ```true``` if extrinsic success, otherwise ```false```639 */640 async burn(signer: TSigner, collectionId: number): Promise<boolean> {641 const result = await this.helper.executeExtrinsic(642 signer,643 'api.tx.unique.destroyCollection', [collectionId],644 true,645 );646647 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');648 }649650 /**651 * Sets the sponsor for the collection (Requires the Substrate address). Needs confirmation by the sponsor.652 *653 * @param signer keyring of signer654 * @param collectionId ID of collection655 * @param sponsorAddress Sponsor substrate address656 * @example setSponsor(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")657 * @returns ```true``` if extrinsic success, otherwise ```false```658 */659 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {660 const result = await this.helper.executeExtrinsic(661 signer,662 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],663 true,664 );665666 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');667 }668669 /**670 * Confirms consent to sponsor the collection on behalf of the signer.671 *672 * @param signer keyring of signer673 * @param collectionId ID of collection674 * @example confirmSponsorship(aliceKeyring, 10)675 * @returns ```true``` if extrinsic success, otherwise ```false```676 */677 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {678 const result = await this.helper.executeExtrinsic(679 signer,680 'api.tx.unique.confirmSponsorship', [collectionId],681 true,682 );683684 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');685 }686687 /**688 * Removes the sponsor of a collection, regardless if it consented or not.689 *690 * @param signer keyring of signer691 * @param collectionId ID of collection692 * @example removeSponsor(aliceKeyring, 10)693 * @returns ```true``` if extrinsic success, otherwise ```false```694 */695 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {696 const result = await this.helper.executeExtrinsic(697 signer,698 'api.tx.unique.removeCollectionSponsor', [collectionId],699 true,700 );701702 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');703 }704705 /**706 * Sets the limits of the collection. At least one limit must be specified for a correct call.707 *708 * @param signer keyring of signer709 * @param collectionId ID of collection710 * @param limits collection limits object711 * @example712 * await setLimits(713 * aliceKeyring,714 * 10,715 * {716 * sponsorTransferTimeout: 0,717 * ownerCanDestroy: false718 * }719 * )720 * @returns ```true``` if extrinsic success, otherwise ```false```721 */722 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.setCollectionLimits', [collectionId, limits],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');730 }731732 /**733 * Changes the owner of the collection to the new Substrate address.734 *735 * @param signer keyring of signer736 * @param collectionId ID of collection737 * @param ownerAddress substrate address of new owner738 * @example changeOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...")739 * @returns ```true``` if extrinsic success, otherwise ```false```740 */741 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {742 const result = await this.helper.executeExtrinsic(743 signer,744 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],745 true,746 );747748 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');749 }750751 /**752 * Adds a collection administrator.753 *754 * @param signer keyring of signer755 * @param collectionId ID of collection756 * @param adminAddressObj Administrator address (substrate or ethereum)757 * @example addAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})758 * @returns ```true``` if extrinsic success, otherwise ```false```759 */760 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {761 const result = await this.helper.executeExtrinsic(762 signer,763 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],764 true,765 );766767 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');768 }769770 /**771 * Removes a collection administrator.772 *773 * @param signer keyring of signer774 * @param collectionId ID of collection775 * @param adminAddressObj Administrator address (substrate or ethereum)776 * @example removeAdmin(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."})777 * @returns ```true``` if extrinsic success, otherwise ```false```778 */779 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {780 const result = await this.helper.executeExtrinsic(781 signer,782 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],783 true,784 );785786 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');787 }788789 /**790 * Check if user is in allow list.791 * 792 * @param collectionId ID of collection793 * @param user Account to check794 * @example await getAdmins(1)795 * @returns is user in allow list796 */797 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {798 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();799 }800801 /**802 * Adds an address to allow list803 * @param signer keyring of signer804 * @param collectionId ID of collection805 * @param addressObj address to add to the allow list806 * @returns ```true``` if extrinsic success, otherwise ```false```807 */808 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {809 const result = await this.helper.executeExtrinsic(810 signer,811 'api.tx.unique.addToAllowList', [collectionId, addressObj],812 true,813 );814815 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');816 }817818 /**819 * Removes an address from allow list820 *821 * @param signer keyring of signer822 * @param collectionId ID of collection823 * @param addressObj address to remove from the allow list824 * @returns ```true``` if extrinsic success, otherwise ```false```825 */826 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {827 const result = await this.helper.executeExtrinsic(828 signer,829 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],830 true,831 );832833 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');834 }835836 /**837 * Sets onchain permissions for selected collection.838 *839 * @param signer keyring of signer840 * @param collectionId ID of collection841 * @param permissions collection permissions object842 * @example setPermissions(aliceKeyring, 10, {access:'AllowList', mintMode: true, nesting: {collectionAdmin: true, tokenOwner: true}});843 * @returns ```true``` if extrinsic success, otherwise ```false```844 */845 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {846 const result = await this.helper.executeExtrinsic(847 signer,848 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],849 true,850 );851852 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');853 }854855 /**856 * Enables nesting for selected collection. If `restricted` set, you can nest only tokens from specified collections.857 *858 * @param signer keyring of signer859 * @param collectionId ID of collection860 * @param permissions nesting permissions object861 * @example enableNesting(aliceKeyring, 10, {collectionAdmin: true, tokenOwner: true});862 * @returns ```true``` if extrinsic success, otherwise ```false```863 */864 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {865 return await this.setPermissions(signer, collectionId, {nesting: permissions});866 }867868 /**869 * Disables nesting for selected collection.870 *871 * @param signer keyring of signer872 * @param collectionId ID of collection873 * @example disableNesting(aliceKeyring, 10);874 * @returns ```true``` if extrinsic success, otherwise ```false```875 */876 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {877 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});878 }879880 /**881 * Sets onchain properties to the collection.882 *883 * @param signer keyring of signer884 * @param collectionId ID of collection885 * @param properties array of property objects886 * @example setProperties(aliceKeyring, 10, [{key: "gender", value: "male"}]);887 * @returns ```true``` if extrinsic success, otherwise ```false```888 */889 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {890 const result = await this.helper.executeExtrinsic(891 signer,892 'api.tx.unique.setCollectionProperties', [collectionId, properties],893 true,894 );895896 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');897 }898899 /**900 * Deletes onchain properties from the collection.901 *902 * @param signer keyring of signer903 * @param collectionId ID of collection904 * @param propertyKeys array of property keys to delete905 * @example deleteProperties(aliceKeyring, 10, ["gender", "age"]);906 * @returns ```true``` if extrinsic success, otherwise ```false```907 */908 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {909 const result = await this.helper.executeExtrinsic(910 signer,911 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],912 true,913 );914915 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');916 }917918 /**919 * Changes the owner of the token.920 *921 * @param signer keyring of signer922 * @param collectionId ID of collection923 * @param tokenId ID of token924 * @param addressObj address of a new owner925 * @param amount amount of tokens to be transfered. For NFT must be set to 1n926 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})927 * @returns true if the token success, otherwise false928 */929 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {930 const result = await this.helper.executeExtrinsic(931 signer,932 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],933 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,934 );935936 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);937 }938939 /**940 *941 * Change ownership of a token(s) on behalf of the owner.942 *943 * @param signer keyring of signer944 * @param collectionId ID of collection945 * @param tokenId ID of token946 * @param fromAddressObj address on behalf of which the token will be sent947 * @param toAddressObj new token owner948 * @param amount amount of tokens to be transfered. For NFT must be set to 1n949 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg"}, {Ethereum: "0x9F0583DbB85..."})950 * @returns true if the token success, otherwise false951 */952 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],956 true, // `Unable to transfer token #${tokenId} from collection #${collectionId}`,957 );958 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);959 }960961 /**962 *963 * Destroys a concrete instance of NFT/RFT or burns a specified amount of fungible tokens.964 *965 * @param signer keyring of signer966 * @param collectionId ID of collection967 * @param tokenId ID of token968 * @param amount amount of tokens to be burned. For NFT must be set to 1n969 * @example burnToken(aliceKeyring, 10, 5);970 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```971 */972 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{973 success: boolean,974 token: number | null975 }> {976 const burnResult = await this.helper.executeExtrinsic(977 signer,978 'api.tx.unique.burnItem', [collectionId, tokenId, amount],979 true, // `Unable to burn token for ${label}`,980 );981 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);982 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');983 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};984 }985986 /**987 * Destroys a concrete instance of NFT on behalf of the owner988 *989 * @param signer keyring of signer990 * @param collectionId ID of collection991 * @param fromAddressObj address on behalf of which the token will be burnt992 * @param tokenId ID of token993 * @param amount amount of tokens to be burned. For NFT must be set to 1n994 * @example burnTokenFrom(aliceKeyring, 10, {Substrate: "5DyN4Y92vZCjv38fg..."}, 5, {Ethereum: "0x9F0583DbB85..."})995 * @returns ```true``` if extrinsic success, otherwise ```false```996 */997 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {998 const burnResult = await this.helper.executeExtrinsic(999 signer,1000 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1001 true, // `Unable to burn token from for ${label}`,1002 );1003 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1004 return burnedTokens.success && burnedTokens.tokens.length > 0;1005 }10061007 /**1008 * Set, change, or remove approved address to transfer the ownership of the NFT.1009 *1010 * @param signer keyring of signer1011 * @param collectionId ID of collection1012 * @param tokenId ID of token1013 * @param toAddressObj Substrate or Ethereum address which gets approved use of the signer's tokens1014 * @param amount amount of token to be approved. For NFT must be set to 1n1015 * @returns ```true``` if extrinsic success, otherwise ```false```1016 */1017 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1018 const approveResult = await this.helper.executeExtrinsic(1019 signer,1020 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1021 true, // `Unable to approve token for ${label}`,1022 );10231024 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1025 }10261027 /**1028 * Get the amount of token pieces approved to transfer or burn. Normally 0.1029 *1030 * @param collectionId ID of collection1031 * @param tokenId ID of token1032 * @param toAccountObj address which is approved to use token pieces1033 * @param fromAccountObj address which may have allowed the use of its owned tokens1034 * @example getTokenApprovedPieces(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5ERZNF88Mm7UGfPP3mdG..."})1035 * @returns number of approved to transfer pieces1036 */1037 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1038 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1039 }10401041 /**1042 * Get the last created token ID in a collection1043 *1044 * @param collectionId ID of collection1045 * @example getLastTokenId(10);1046 * @returns id of the last created token1047 */1048 async getLastTokenId(collectionId: number): Promise<number> {1049 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1050 }10511052 /**1053 * Check if token exists1054 *1055 * @param collectionId ID of collection1056 * @param tokenId ID of token1057 * @example isTokenExists(10, 20);1058 * @returns true if the token exists, otherwise false1059 */1060 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1061 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1062 }1063}10641065class NFTnRFT extends CollectionGroup {1066 /**1067 * Get tokens owned by account1068 *1069 * @param collectionId ID of collection1070 * @param addressObj tokens owner1071 * @example getTokensByAddress(10, {Substrate: "5DyN4Y92vZCjv38fg..."})1072 * @returns array of token ids owned by account1073 */1074 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1075 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1076 }10771078 /**1079 * Get token data1080 *1081 * @param collectionId ID of collection1082 * @param tokenId ID of token1083 * @param propertyKeys optionally filter the token properties to only these keys1084 * @param blockHashAt optionally query the data at some block with this hash1085 * @example getToken(10, 5);1086 * @returns human readable token data1087 */1088 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1089 properties: IProperty[];1090 owner: ICrossAccountId;1091 normalizedOwner: ICrossAccountId;1092 }| null> {1093 let tokenData;1094 if(typeof blockHashAt === 'undefined') {1095 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1096 }1097 else {1098 if(propertyKeys.length == 0) {1099 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1100 if(!collection) return null;1101 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1102 }1103 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1104 }1105 tokenData = tokenData.toHuman();1106 if (tokenData === null || tokenData.owner === null) return null;1107 const owner = {} as any;1108 for (const key of Object.keys(tokenData.owner)) {1109 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1110 }1111 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1112 return tokenData;1113 }11141115 /**1116 * Set permissions to change token properties1117 *1118 * @param signer keyring of signer1119 * @param collectionId ID of collection1120 * @param permissions permissions to change a property by the collection owner or admin1121 * @example setTokenPropertyPermissions(1122 * aliceKeyring, 10, [{key: "gender", permission: {tokenOwner: true, mutable: true, collectionAdmin: true}}]1123 * )1124 * @returns true if extrinsic success otherwise false1125 */1126 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1127 const result = await this.helper.executeExtrinsic(1128 signer,1129 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1130 true,1131 );11321133 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1134 }11351136 /**1137 * Set token properties1138 *1139 * @param signer keyring of signer1140 * @param collectionId ID of collection1141 * @param tokenId ID of token1142 * @param properties key-value pairs of metadata which to add to a token. Keys must be permitted in the collection1143 * @example setTokenProperties(aliceKeyring, 10, 5, [{key: "gender", value: "female"}, {key: "age", value: "23"}])1144 * @returns ```true``` if extrinsic success, otherwise ```false```1145 */1146 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1147 const result = await this.helper.executeExtrinsic(1148 signer,1149 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1150 true,1151 );11521153 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1154 }11551156 /**1157 * Delete the provided properties of a token1158 * @param signer keyring of signer1159 * @param collectionId ID of collection1160 * @param tokenId ID of token1161 * @param propertyKeys property keys to be deleted1162 * @example deleteTokenProperties(aliceKeyring, 10, 5, ["gender", "age"])1163 * @returns ```true``` if extrinsic success, otherwise ```false```1164 */1165 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1166 const result = await this.helper.executeExtrinsic(1167 signer,1168 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1169 true,1170 );11711172 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1173 }11741175 /**1176 * Mint new collection1177 *1178 * @param signer keyring of signer1179 * @param collectionOptions basic collection options and properties1180 * @param mode NFT or RFT type of a collection1181 * @example mintCollection(aliceKeyring, {name: 'New', description: "New collection", tokenPrefix: "NEW"}, "NFT")1182 * @returns object of the created collection1183 */1184 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1185 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1186 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1187 for (const key of ['name', 'description', 'tokenPrefix']) {1188 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);1189 }1190 const creationResult = await this.helper.executeExtrinsic(1191 signer,1192 'api.tx.unique.createCollectionEx', [collectionOptions],1193 true, // errorLabel,1194 );1195 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1196 }11971198 getCollectionObject(_collectionId: number): any {1199 return null;1200 }12011202 getTokenObject(_collectionId: number, _tokenId: number): any {1203 return null;1204 }1205}120612071208class NFTGroup extends NFTnRFT {1209 /**1210 * Get collection object1211 * @param collectionId ID of collection1212 * @example getCollectionObject(2);1213 * @returns instance of UniqueNFTCollection1214 */1215 getCollectionObject(collectionId: number): UniqueNFTCollection {1216 return new UniqueNFTCollection(collectionId, this.helper);1217 }12181219 /**1220 * Get token object1221 * @param collectionId ID of collection1222 * @param tokenId ID of token1223 * @example getTokenObject(10, 5);1224 * @returns instance of UniqueNFTToken1225 */1226 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1227 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1228 }12291230 /**1231 * Get token's owner1232 * @param collectionId ID of collection1233 * @param tokenId ID of token1234 * @param blockHashAt optionally query the data at the block with this hash1235 * @example getTokenOwner(10, 5);1236 * @returns Address in CrossAccountId format, e.g. {Substrate: "5DnSF6RRjwteE3BrCj..."}1237 */1238 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1239 let owner;1240 if (typeof blockHashAt === 'undefined') {1241 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1242 } else {1243 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1244 }1245 return crossAccountIdFromLower(owner.toJSON());1246 }12471248 /**1249 * Is token approved to transfer1250 * @param collectionId ID of collection1251 * @param tokenId ID of token1252 * @param toAccountObj address to be approved1253 * @returns ```true``` if extrinsic success, otherwise ```false```1254 */1255 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1256 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1257 }12581259 /**1260 * Changes the owner of the token.1261 *1262 * @param signer keyring of signer1263 * @param collectionId ID of collection1264 * @param tokenId ID of token1265 * @param addressObj address of a new owner1266 * @example transferToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1267 * @returns ```true``` if extrinsic success, otherwise ```false```1268 */1269 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1270 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1271 }12721273 /**1274 *1275 * Change ownership of a NFT on behalf of the owner.1276 *1277 * @param signer keyring of signer1278 * @param collectionId ID of collection1279 * @param tokenId ID of token1280 * @param fromAddressObj address on behalf of which the token will be sent1281 * @param toAddressObj new token owner1282 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Ethereum: "0x9F0583DbB85..."})1283 * @returns ```true``` if extrinsic success, otherwise ```false```1284 */1285 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1286 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1287 }12881289 /**1290 * Recursively find the address that owns the token1291 * @param collectionId ID of collection1292 * @param tokenId ID of token1293 * @param blockHashAt1294 * @example getTokenTopmostOwner(10, 5);1295 * @returns address in CrossAccountId format, e.g. {Substrate: "5DyN4Y92vZCjv38fg..."}1296 */1297 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1298 let owner;1299 if (typeof blockHashAt === 'undefined') {1300 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1301 } else {1302 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1303 }13041305 if (owner === null) return null;13061307 owner = owner.toHuman();13081309 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1310 }13111312 /**1313 * Get tokens nested in the provided token1314 * @param collectionId ID of collection1315 * @param tokenId ID of token1316 * @param blockHashAt optionally query the data at the block with this hash1317 * @example getTokenChildren(10, 5);1318 * @returns tokens whose depth of nesting is <= 51319 */1320 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1321 let children;1322 if(typeof blockHashAt === 'undefined') {1323 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1324 } else {1325 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1326 }13271328 return children.toJSON().map((x: any) => {1329 return {collectionId: x.collection, tokenId: x.token};1330 });1331 }13321333 /**1334 * Nest one token into another1335 * @param signer keyring of signer1336 * @param tokenObj token to be nested1337 * @param rootTokenObj token to be parent1338 * @example nestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4});1339 * @returns ```true``` if extrinsic success, otherwise ```false```1340 */1341 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1342 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1343 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1344 if(!result) {1345 throw Error('Unable to nest token!');1346 }1347 return result;1348 }13491350 /**1351 * Remove token from nested state1352 * @param signer keyring of signer1353 * @param tokenObj token to unnest1354 * @param rootTokenObj parent of a token1355 * @param toAddressObj address of a new token owner1356 * @example unnestToken(aliceKeyring, {collectionId: 10, tokenId: 5}, {collectionId: 10, tokenId: 4}, {Substrate: "5DyN4Y92vZCjv38fg..."});1357 * @returns ```true``` if extrinsic success, otherwise ```false```1358 */1359 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1360 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1361 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1362 if(!result) {1363 throw Error('Unable to unnest token!');1364 }1365 return result;1366 }13671368 /**1369 * Mint new collection1370 * @param signer keyring of signer1371 * @param collectionOptions Collection options1372 * @example1373 * mintCollection(aliceKeyring, {1374 * name: 'New',1375 * description: 'New collection',1376 * tokenPrefix: 'NEW',1377 * })1378 * @returns object of the created collection1379 */1380 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1381 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1382 }13831384 /**1385 * Mint new token1386 * @param signer keyring of signer1387 * @param data token data1388 * @returns created token object1389 */1390 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1391 const creationResult = await this.helper.executeExtrinsic(1392 signer,1393 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1394 nft: {1395 properties: data.properties,1396 },1397 }],1398 true,1399 );1400 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1401 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1402 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1403 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1404 }14051406 /**1407 * Mint multiple NFT tokens1408 * @param signer keyring of signer1409 * @param collectionId ID of collection1410 * @param tokens array of tokens with owner and properties1411 * @example1412 * mintMultipleTokens(aliceKeyring, 10, [{1413 * owner: {Substrate: "5DyN4Y92vZCjv38fg..."},1414 * properties: [{key: "gender", value: "male"},{key: "age", value: "45"}],1415 * },{1416 * owner: {Ethereum: "0x9F0583DbB855d..."},1417 * properties: [{key: "gender", value: "female"},{key: "age", value: "22"}],1418 * }]);1419 * @returns ```true``` if extrinsic success, otherwise ```false```1420 */1421 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1422 const creationResult = await this.helper.executeExtrinsic(1423 signer,1424 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1425 true,1426 );1427 const collection = this.getCollectionObject(collectionId);1428 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1429 }14301431 /**1432 * Mint multiple NFT tokens with one owner1433 * @param signer keyring of signer1434 * @param collectionId ID of collection1435 * @param owner tokens owner1436 * @param tokens array of tokens with owner and properties1437 * @example1438 * mintMultipleTokensWithOneOwner(aliceKeyring, 10, "5DyN4Y92vZCjv38fg...", [{1439 * properties: [{1440 * key: "gender",1441 * value: "female",1442 * },{1443 * key: "age",1444 * value: "33",1445 * }],1446 * }]);1447 * @returns array of newly created tokens1448 */1449 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1450 const rawTokens = [];1451 for (const token of tokens) {1452 const raw = {NFT: {properties: token.properties}};1453 rawTokens.push(raw);1454 }1455 const creationResult = await this.helper.executeExtrinsic(1456 signer,1457 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1458 true,1459 );1460 const collection = this.getCollectionObject(collectionId);1461 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1462 }14631464 /**1465 * Set, change, or remove approved address to transfer the ownership of the NFT.1466 *1467 * @param signer keyring of signer1468 * @param collectionId ID of collection1469 * @param tokenId ID of token1470 * @param toAddressObj address to approve1471 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."})1472 * @returns ```true``` if extrinsic success, otherwise ```false```1473 */1474 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1475 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1476 }1477}147814791480class RFTGroup extends NFTnRFT {1481 /**1482 * Get collection object1483 * @param collectionId ID of collection1484 * @example getCollectionObject(2);1485 * @returns instance of UniqueRFTCollection1486 */1487 getCollectionObject(collectionId: number): UniqueRFTCollection {1488 return new UniqueRFTCollection(collectionId, this.helper);1489 }14901491 /**1492 * Get token object1493 * @param collectionId ID of collection1494 * @param tokenId ID of token1495 * @example getTokenObject(10, 5);1496 * @returns instance of UniqueNFTToken1497 */1498 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1499 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1500 }15011502 /**1503 * Get top 10 token owners with the largest number of pieces1504 * @param collectionId ID of collection1505 * @param tokenId ID of token1506 * @example getTokenTop10Owners(10, 5);1507 * @returns array of top 10 owners1508 */1509 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1510 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1511 }15121513 /**1514 * Get number of pieces owned by address1515 * @param collectionId ID of collection1516 * @param tokenId ID of token1517 * @param addressObj address token owner1518 * @example getTokenBalance(10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."});1519 * @returns number of pieces ownerd by address1520 */1521 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1522 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1523 }15241525 /**1526 * Transfer pieces of token to another address1527 * @param signer keyring of signer1528 * @param collectionId ID of collection1529 * @param tokenId ID of token1530 * @param addressObj address of a new owner1531 * @param amount number of pieces to be transfered1532 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, 2000n)1533 * @returns ```true``` if extrinsic success, otherwise ```false```1534 */1535 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1536 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1537 }15381539 /**1540 * Change ownership of some pieces of RFT on behalf of the owner.1541 * @param signer keyring of signer1542 * @param collectionId ID of collection1543 * @param tokenId ID of token1544 * @param fromAddressObj address on behalf of which the token will be sent1545 * @param toAddressObj new token owner1546 * @param amount number of pieces to be transfered1547 * @example transferTokenFrom(aliceKeyring, 10, 5, {Substrate: "5DyN4Y92vZCjv38fg..."}, {Substrate: "5DfhbVfww7ThF8q6f3i..."}, 2000n)1548 * @returns ```true``` if extrinsic success, otherwise ```false```1549 */1550 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1551 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1552 }15531554 /**1555 * Mint new collection1556 * @param signer keyring of signer1557 * @param collectionOptions Collection options1558 * @example1559 * mintCollection(aliceKeyring, {1560 * name: 'New',1561 * description: 'New collection',1562 * tokenPrefix: 'NEW',1563 * })1564 * @returns object of the created collection1565 */1566 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1567 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1568 }15691570 /**1571 * Mint new token1572 * @param signer keyring of signer1573 * @param data token data1574 * @example mintToken(aliceKeyring, {collectionId: 10, owner: {Substrate: '5GHoZe9c73RYbVzq...'}, pieces: 10000n});1575 * @returns created token object1576 */1577 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1578 const creationResult = await this.helper.executeExtrinsic(1579 signer,1580 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1581 refungible: {1582 pieces: data.pieces,1583 properties: data.properties,1584 },1585 }],1586 true,1587 );1588 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1589 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1590 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1591 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1592 }15931594 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1595 throw Error('Not implemented');1596 const creationResult = await this.helper.executeExtrinsic(1597 signer,1598 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1599 true, // `Unable to mint RFT tokens for ${label}`,1600 );1601 const collection = this.getCollectionObject(collectionId);1602 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1603 }16041605 /**1606 * Mint multiple RFT tokens with one owner1607 * @param signer keyring of signer1608 * @param collectionId ID of collection1609 * @param owner tokens owner1610 * @param tokens array of tokens with properties and pieces1611 * @example mintMultipleTokensWithOneOwner(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, [{pieces: 100000n, properties: [{key: "gender", value: "male"}]}]);1612 * @returns array of newly created RFT tokens1613 */1614 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1615 const rawTokens = [];1616 for (const token of tokens) {1617 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1618 rawTokens.push(raw);1619 }1620 const creationResult = await this.helper.executeExtrinsic(1621 signer,1622 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1623 true,1624 );1625 const collection = this.getCollectionObject(collectionId);1626 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1627 }16281629 /**1630 * Destroys a concrete instance of RFT.1631 * @param signer keyring of signer1632 * @param collectionId ID of collection1633 * @param tokenId ID of token1634 * @param amount number of pieces to be burnt1635 * @example burnToken(aliceKeyring, 10, 5);1636 * @returns ```true``` and burnt token number is extrinsic success. Otherwise ```false``` and ```null```1637 */1638 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1639 return await super.burnToken(signer, collectionId, tokenId, amount);1640 }16411642 /**1643 * Set, change, or remove approved address to transfer the ownership of the RFT.1644 *1645 * @param signer keyring of signer1646 * @param collectionId ID of collection1647 * @param tokenId ID of token1648 * @param toAddressObj address to approve1649 * @param amount number of pieces to be approved1650 * @example approveToken(aliceKeyring, 10, 5, {Substrate: "5GHoZe9c73RYbVzq..."}, "", 10000n);1651 * @returns true if the token success, otherwise false1652 */1653 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1654 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1655 }16561657 /**1658 * Get total number of pieces1659 * @param collectionId ID of collection1660 * @param tokenId ID of token1661 * @example getTokenTotalPieces(10, 5);1662 * @returns number of pieces1663 */1664 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1665 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1666 }16671668 /**1669 * Change number of token pieces. Signer must be the owner of all token pieces.1670 * @param signer keyring of signer1671 * @param collectionId ID of collection1672 * @param tokenId ID of token1673 * @param amount new number of pieces1674 * @example repartitionToken(aliceKeyring, 10, 5, 12345n);1675 * @returns true if the repartion was success, otherwise false1676 */1677 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1678 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1679 const repartitionResult = await this.helper.executeExtrinsic(1680 signer,1681 'api.tx.unique.repartition', [collectionId, tokenId, amount],1682 true,1683 );1684 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1685 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1686 }1687}168816891690class FTGroup extends CollectionGroup {1691 /**1692 * Get collection object1693 * @param collectionId ID of collection1694 * @example getCollectionObject(2);1695 * @returns instance of UniqueFTCollection1696 */1697 getCollectionObject(collectionId: number): UniqueFTCollection {1698 return new UniqueFTCollection(collectionId, this.helper);1699 }17001701 /**1702 * Mint new fungible collection1703 * @param signer keyring of signer1704 * @param collectionOptions Collection options1705 * @param decimalPoints number of token decimals1706 * @example1707 * mintCollection(aliceKeyring, {1708 * name: 'New',1709 * description: 'New collection',1710 * tokenPrefix: 'NEW',1711 * }, 18)1712 * @returns newly created fungible collection1713 */1714 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1715 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; // Clone object1716 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1717 collectionOptions.mode = {fungible: decimalPoints};1718 for (const key of ['name', 'description', 'tokenPrefix']) {1719 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);1720 }1721 const creationResult = await this.helper.executeExtrinsic(1722 signer,1723 'api.tx.unique.createCollectionEx', [collectionOptions],1724 true,1725 );1726 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1727 }17281729 /**1730 * Mint tokens1731 * @param signer keyring of signer1732 * @param collectionId ID of collection1733 * @param owner address owner of new tokens1734 * @param amount amount of tokens to be meanted1735 * @example mintTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq"}, 1000n);1736 * @returns ```true``` if extrinsic success, otherwise ```false```1737 */1738 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1739 const creationResult = await this.helper.executeExtrinsic(1740 signer,1741 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1742 fungible: {1743 value: amount,1744 },1745 }],1746 true, // `Unable to mint fungible tokens for ${label}`,1747 );1748 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1749 }17501751 /**1752 * Mint multiple Fungible tokens with one owner1753 * @param signer keyring of signer1754 * @param collectionId ID of collection1755 * @param owner tokens owner1756 * @param tokens array of tokens with properties and pieces1757 * @returns ```true``` if extrinsic success, otherwise ```false```1758 */1759 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1760 const rawTokens = [];1761 for (const token of tokens) {1762 const raw = {Fungible: {Value: token.value}};1763 rawTokens.push(raw);1764 }1765 const creationResult = await this.helper.executeExtrinsic(1766 signer,1767 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1768 true,1769 );1770 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1771 }17721773 /**1774 * Get the top 10 owners with the largest balance for the Fungible collection1775 * @param collectionId ID of collection1776 * @example getTop10Owners(10);1777 * @returns array of ```ICrossAccountId```1778 */1779 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1780 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1781 }17821783 /**1784 * Get account balance1785 * @param collectionId ID of collection1786 * @param addressObj address of owner1787 * @example getBalance(10, {Substrate: "5GHoZe9c73RYbVzq..."})1788 * @returns amount of fungible tokens owned by address1789 */1790 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1791 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1792 }17931794 /**1795 * Transfer tokens to address1796 * @param signer keyring of signer1797 * @param collectionId ID of collection1798 * @param toAddressObj address recipient1799 * @param amount amount of tokens to be sent1800 * @example transfer(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1801 * @returns ```true``` if extrinsic success, otherwise ```false```1802 */1803 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1804 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1805 }18061807 /**1808 * Transfer some tokens on behalf of the owner.1809 * @param signer keyring of signer1810 * @param collectionId ID of collection1811 * @param fromAddressObj address on behalf of which tokens will be sent1812 * @param toAddressObj address where token to be sent1813 * @param amount number of tokens to be sent1814 * @example transferFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, {Substrate: "5DfhbVfww7ThF8q6f3ij..."}, 10000n);1815 * @returns ```true``` if extrinsic success, otherwise ```false```1816 */1817 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1818 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1819 }18201821 /**1822 * Destroy some amount of tokens1823 * @param signer keyring of signer1824 * @param collectionId ID of collection1825 * @param amount amount of tokens to be destroyed1826 * @example burnTokens(aliceKeyring, 10, 1000n);1827 * @returns ```true``` if extrinsic success, otherwise ```false```1828 */1829 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1830 return (await super.burnToken(signer, collectionId, 0, amount)).success;1831 }18321833 /**1834 * Burn some tokens on behalf of the owner.1835 * @param signer keyring of signer1836 * @param collectionId ID of collection1837 * @param fromAddressObj address on behalf of which tokens will be burnt1838 * @param amount amount of tokens to be burnt1839 * @example burnTokensFrom(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n);1840 * @returns ```true``` if extrinsic success, otherwise ```false```1841 */1842 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1843 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1844 }18451846 /**1847 * Get total collection supply1848 * @param collectionId1849 * @returns1850 */1851 async getTotalPieces(collectionId: number): Promise<bigint> {1852 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1853 }18541855 /**1856 * Set, change, or remove approved address to transfer tokens.1857 *1858 * @param signer keyring of signer1859 * @param collectionId ID of collection1860 * @param toAddressObj address to be approved1861 * @param amount amount of tokens to be approved1862 * @example approveTokens(aliceKeyring, 10, {Substrate: "5GHoZe9c73RYbVzq..."}, 1000n)1863 * @returns ```true``` if extrinsic success, otherwise ```false```1864 */1865 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1866 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1867 }18681869 /**1870 * Get amount of fungible tokens approved to transfer1871 * @param collectionId ID of collection1872 * @param fromAddressObj owner of tokens1873 * @param toAddressObj the address approved for the transfer of tokens on behalf of the owner1874 * @returns number of tokens approved for the transfer1875 */1876 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1877 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1878 }1879}188018811882class ChainGroup extends HelperGroup {1883 /**1884 * Get system properties of a chain1885 * @example getChainProperties();1886 * @returns ss58Format, token decimals, and token symbol1887 */1888 getChainProperties(): IChainProperties {1889 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1890 return {1891 ss58Format: properties.ss58Format.toJSON(),1892 tokenDecimals: properties.tokenDecimals.toJSON(),1893 tokenSymbol: properties.tokenSymbol.toJSON(),1894 };1895 }18961897 /**1898 * Get chain header1899 * @example getLatestBlockNumber();1900 * @returns the number of the last block1901 */1902 async getLatestBlockNumber(): Promise<number> {1903 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1904 }19051906 /**1907 * Get block hash by block number1908 * @param blockNumber number of block1909 * @example getBlockHashByNumber(12345);1910 * @returns hash of a block1911 */1912 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1913 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1914 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1915 return blockHash;1916 }19171918 // TODO add docs1919 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1920 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1921 if (!blockHash) return null;1922 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1923 }19241925 /**1926 * Get account nonce1927 * @param address substrate address1928 * @example getNonce("5GrwvaEF5zXb26Fz...");1929 * @returns number, account's nonce1930 */1931 async getNonce(address: TSubstrateAccount): Promise<number> {1932 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1933 }1934}193519361937class BalanceGroup extends HelperGroup {1938 /**1939 * Representation of the native token in the smallest unit1940 * @example getOneTokenNominal()1941 * @returns ```BigInt``` representation of the native token in the smallest unit, e.g. ```1_000_000_000_000_000_000n``` for QTZ.1942 */1943 getOneTokenNominal(): bigint {1944 const chainProperties = this.helper.chain.getChainProperties();1945 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1946 }19471948 /**1949 * Get substrate address balance1950 * @param address substrate address1951 * @example getSubstrate("5GrwvaEF5zXb26Fz...")1952 * @returns amount of tokens on address1953 */1954 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1955 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1956 }19571958 /**1959 * Get full substrate balance including free, miscFrozen, feeFrozen, and reserved1960 * @param address substrate address1961 * @returns1962 */1963 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {1964 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;1965 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};1966 }19671968 /**1969 * Get ethereum address balance1970 * @param address ethereum address1971 * @example getEthereum("0x9F0583DbB855d...")1972 * @returns amount of tokens on address1973 */1974 async getEthereum(address: TEthereumAccount): Promise<bigint> {1975 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1976 }19771978 /**1979 * Transfer tokens to substrate address1980 * @param signer keyring of signer1981 * @param address substrate address of a recipient1982 * @param amount amount of tokens to be transfered1983 * @example transferToSubstrate(aliceKeyring, "5GrwvaEF5zXb26Fz...", 100_000_000_000n);1984 * @returns ```true``` if extrinsic success, otherwise ```false```1985 */1986 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1987 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}`*/);19881989 let transfer = {from: null, to: null, amount: 0n} as any;1990 result.result.events.forEach(({event: {data, method, section}}) => {1991 if ((section === 'balances') && (method === 'Transfer')) {1992 transfer = {1993 from: this.helper.address.normalizeSubstrate(data[0]),1994 to: this.helper.address.normalizeSubstrate(data[1]),1995 amount: BigInt(data[2]),1996 };1997 }1998 });1999 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2000 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2001 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2002 return isSuccess;2003 }2004}200520062007class AddressGroup extends HelperGroup {2008 /**2009 * Normalizes the address to the specified ss58 format, by default ```42```.2010 * @param address substrate address2011 * @param ss58Format format for address conversion, by default ```42```2012 * @example normalizeSubstrate("unjKJQJrRd238pkUZZvzDQrfKuM39zBSnQ5zjAGAGcdRhaJTx") // returns 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY2013 * @returns substrate address converted to normalized (i.e., starting with 5) or specified explicitly representation2014 */2015 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2016 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2017 }20182019 /**2020 * Get address in the connected chain format2021 * @param address substrate address2022 * @example normalizeSubstrateToChainFormat("5GrwvaEF5zXb26Fz...") // returns unjKJQJrRd238pkUZZ... for Unique Network2023 * @returns address in chain format2024 */2025 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2026 const info = this.helper.chain.getChainProperties();2027 return encodeAddress(decodeAddress(address), info.ss58Format);2028 }20292030 /**2031 * Get substrate mirror of an ethereum address2032 * @param ethAddress ethereum address2033 * @param toChainFormat false for normalized account2034 * @example ethToSubstrate('0x9F0583DbB855d...')2035 * @returns substrate mirror of a provided ethereum address2036 */2037 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2038 if(!toChainFormat) return evmToAddress(ethAddress);2039 const info = this.helper.chain.getChainProperties();2040 return evmToAddress(ethAddress, info.ss58Format);2041 }20422043 /**2044 * Get ethereum mirror of a substrate address2045 * @param subAddress substrate account2046 * @example substrateToEth("5DnSF6RRjwteE3BrC...")2047 * @returns ethereum mirror of a provided substrate address2048 */2049 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2050 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2051 }2052}20532054class StakingGroup extends HelperGroup {2055 /**2056 * Stake tokens for App Promotion2057 * @param signer keyring of signer2058 * @param amountToStake amount of tokens to stake2059 * @param label extra label for log2060 * @returns2061 */2062 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2063 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2064 const stakeResult = await this.helper.executeExtrinsic(2065 signer, 'api.tx.appPromotion.stake',2066 [amountToStake], true,2067 );2068 // TODO extract info from stakeResult2069 return true;2070 }20712072 /**2073 * Unstake tokens for App Promotion2074 * @param signer keyring of signer2075 * @param amountToUnstake amount of tokens to unstake2076 * @param label extra label for log2077 * @returns block number where balances will be unlocked2078 */2079 async unstake(signer: TSigner, label?: string): Promise<number> {2080 if(typeof label === 'undefined') label = `${signer.address}`;2081 const unstakeResult = await this.helper.executeExtrinsic(2082 signer, 'api.tx.appPromotion.unstake',2083 [], true,2084 );2085 // TODO extract block number fron events2086 return 1;2087 }20882089 /**2090 * Get total staked amount for address2091 * @param address substrate or ethereum address2092 * @returns total staked amount2093 */2094 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2095 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2096 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2097 }20982099 /**2100 * Get total staked per block2101 * @param address substrate or ethereum address2102 * @returns array of stakes. `block` – the number of the block in which the stake was made. `amount` - the number of tokens staked in the block2103 */2104 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2105 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2106 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2107 return { 2108 block: block.toBigInt(),2109 amount: amount.toBigInt(),2110 };2111 });2112 }21132114 /**2115 * Get total pending unstake amount for address2116 * @param address substrate or ethereum address2117 * @returns total pending unstake amount2118 */2119 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2120 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2121 }21222123 /**2124 * Get pending unstake amount per block for address2125 * @param address substrate or ethereum address2126 * @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 block2127 */2128 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2129 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2130 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2131 return {2132 block: block.toBigInt(),2133 amount: amount.toBigInt(),2134 };2135 });2136 return result;2137 }2138}21392140export class UniqueHelper extends ChainHelperBase {2141 chain: ChainGroup;2142 balance: BalanceGroup;2143 address: AddressGroup;2144 collection: CollectionGroup;2145 nft: NFTGroup;2146 rft: RFTGroup;2147 ft: FTGroup;2148 staking: StakingGroup;21492150 constructor(logger?: ILogger) {2151 super(logger);2152 this.chain = new ChainGroup(this);2153 this.balance = new BalanceGroup(this);2154 this.address = new AddressGroup(this);2155 this.collection = new CollectionGroup(this);2156 this.nft = new NFTGroup(this);2157 this.rft = new RFTGroup(this);2158 this.ft = new FTGroup(this);2159 this.staking = new StakingGroup(this);2160 }2161}216221632164class UniqueCollectionBase {2165 helper: UniqueHelper;2166 collectionId: number;21672168 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2169 this.collectionId = collectionId;2170 this.helper = uniqueHelper;2171 }21722173 async getData() {2174 return await this.helper.collection.getData(this.collectionId);2175 }21762177 async getLastTokenId() {2178 return await this.helper.collection.getLastTokenId(this.collectionId);2179 }21802181 async isTokenExists(tokenId: number) {2182 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2183 }21842185 async getAdmins() {2186 return await this.helper.collection.getAdmins(this.collectionId);2187 }21882189 async getAllowList() {2190 return await this.helper.collection.getAllowList(this.collectionId);2191 }21922193 async getEffectiveLimits() {2194 return await this.helper.collection.getEffectiveLimits(this.collectionId);2195 }21962197 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2198 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2199 }22002201 async confirmSponsorship(signer: TSigner) {2202 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2203 }22042205 async removeSponsor(signer: TSigner) {2206 return await this.helper.collection.removeSponsor(signer, this.collectionId);2207 }22082209 async setLimits(signer: TSigner, limits: ICollectionLimits) {2210 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2211 }22122213 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2214 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2215 }22162217 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2218 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2219 }22202221 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2222 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2223 }22242225 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2226 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2227 }22282229 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2230 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2231 }22322233 async setProperties(signer: TSigner, properties: IProperty[]) {2234 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2235 }22362237 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2238 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2239 }22402241 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2242 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2243 }22442245 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2246 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2247 }22482249 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2250 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2251 }22522253 async disableNesting(signer: TSigner) {2254 return await this.helper.collection.disableNesting(signer, this.collectionId);2255 }22562257 async burn(signer: TSigner) {2258 return await this.helper.collection.burn(signer, this.collectionId);2259 }2260}226122622263class UniqueNFTCollection extends UniqueCollectionBase {2264 getTokenObject(tokenId: number) {2265 return new UniqueNFTToken(tokenId, this);2266 }22672268 async getTokensByAddress(addressObj: ICrossAccountId) {2269 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2270 }22712272 async getToken(tokenId: number, blockHashAt?: string) {2273 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2274 }22752276 async getTokenOwner(tokenId: number, blockHashAt?: string) {2277 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2278 }22792280 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2281 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2282 }22832284 async getTokenChildren(tokenId: number, blockHashAt?: string) {2285 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2286 }22872288 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2289 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2290 }22912292 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2293 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2294 }22952296 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2297 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2298 }22992300 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2301 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2302 }23032304 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2305 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2306 }23072308 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2309 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2310 }23112312 async burnToken(signer: TSigner, tokenId: number) {2313 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2314 }23152316 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2317 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2318 }23192320 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2321 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2322 }23232324 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2325 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2326 }23272328 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2329 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2330 }23312332 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2333 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2334 }2335}233623372338class UniqueRFTCollection extends UniqueCollectionBase {2339 getTokenObject(tokenId: number) {2340 return new UniqueRFTToken(tokenId, this);2341 }23422343 async getTokensByAddress(addressObj: ICrossAccountId) {2344 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2345 }23462347 async getTop10TokenOwners(tokenId: number) {2348 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2349 }23502351 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2352 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2353 }23542355 async getTokenTotalPieces(tokenId: number) {2356 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2357 }23582359 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2360 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2361 }23622363 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2364 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2365 }23662367 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2368 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2369 }23702371 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2372 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2373 }23742375 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2376 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2377 }23782379 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2380 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2381 }23822383 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2384 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2385 }23862387 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2388 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2389 }23902391 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2392 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2393 }23942395 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2396 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2397 }23982399 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2400 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2401 }2402}240324042405class UniqueFTCollection extends UniqueCollectionBase {2406 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2407 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2408 }24092410 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2411 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2412 }24132414 async getBalance(addressObj: ICrossAccountId) {2415 return await this.helper.ft.getBalance(this.collectionId, addressObj);2416 }24172418 async getTop10Owners() {2419 return await this.helper.ft.getTop10Owners(this.collectionId);2420 }24212422 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2423 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2424 }24252426 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2427 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2428 }24292430 async burnTokens(signer: TSigner, amount=1n) {2431 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2432 }24332434 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2435 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2436 }24372438 async getTotalPieces() {2439 return await this.helper.ft.getTotalPieces(this.collectionId);2440 }24412442 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2443 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2444 }24452446 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2447 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2448 }2449}245024512452class UniqueTokenBase implements IToken {2453 collection: UniqueNFTCollection | UniqueRFTCollection;2454 collectionId: number;2455 tokenId: number;24562457 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2458 this.collection = collection;2459 this.collectionId = collection.collectionId;2460 this.tokenId = tokenId;2461 }24622463 async getNextSponsored(addressObj: ICrossAccountId) {2464 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2465 }24662467 async setProperties(signer: TSigner, properties: IProperty[]) {2468 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2469 }24702471 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2472 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2473 }2474}247524762477class UniqueNFTToken extends UniqueTokenBase {2478 collection: UniqueNFTCollection;24792480 constructor(tokenId: number, collection: UniqueNFTCollection) {2481 super(tokenId, collection);2482 this.collection = collection;2483 }24842485 async getData(blockHashAt?: string) {2486 return await this.collection.getToken(this.tokenId, blockHashAt);2487 }24882489 async getOwner(blockHashAt?: string) {2490 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2491 }24922493 async getTopmostOwner(blockHashAt?: string) {2494 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2495 }24962497 async getChildren(blockHashAt?: string) {2498 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2499 }25002501 async nest(signer: TSigner, toTokenObj: IToken) {2502 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2503 }25042505 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2506 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2507 }25082509 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2510 return await this.collection.transferToken(signer, this.tokenId, addressObj);2511 }25122513 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2514 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2515 }25162517 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2518 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2519 }25202521 async isApproved(toAddressObj: ICrossAccountId) {2522 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2523 }25242525 async burn(signer: TSigner) {2526 return await this.collection.burnToken(signer, this.tokenId);2527 }2528}25292530class UniqueRFTToken extends UniqueTokenBase {2531 collection: UniqueRFTCollection;25322533 constructor(tokenId: number, collection: UniqueRFTCollection) {2534 super(tokenId, collection);2535 this.collection = collection;2536 }25372538 async getTop10Owners() {2539 return await this.collection.getTop10TokenOwners(this.tokenId);2540 }25412542 async getBalance(addressObj: ICrossAccountId) {2543 return await this.collection.getTokenBalance(this.tokenId, addressObj);2544 }25452546 async getTotalPieces() {2547 return await this.collection.getTokenTotalPieces(this.tokenId);2548 }25492550 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2551 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2552 }25532554 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2555 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2556 }25572558 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2559 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2560 }25612562 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2563 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2564 }25652566 async repartition(signer: TSigner, amount: bigint) {2567 return await this.collection.repartitionToken(signer, this.tokenId, amount);2568 }25692570 async burn(signer: TSigner, amount=1n) {2571 return await this.collection.burnToken(signer, this.tokenId, amount);2572 }2573}