12345678import {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, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, 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 33 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 278 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 320 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) {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 }447 448 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 466467468469470471472473474 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 479480481482483 async getTotalCount(): Promise<number> {484 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();485 }486487 488489490491492493494495496 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 527528529530531532533534 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 547548549550551552553 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 565566567568569570571 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {572 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();573 }574575 576577578579580581582583 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 594595596597598599600601602 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 613614615616617618619620 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 631632633634635636637638 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 649650651652653654655656657658659660661662663664665 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 676677678679680681682683684 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 695696697698699700701702703 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 714715716717718719720721722 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 733734735736737738739 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {740 const result = await this.helper.executeExtrinsic(741 signer,742 'api.tx.unique.addToAllowList', [collectionId, addressObj],743 true,744 );745746 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');747 }748749 750751752753754755756757 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {758 const result = await this.helper.executeExtrinsic(759 signer,760 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],761 true,762 );763764 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');765 }766767 768769770771772773774775776 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {777 const result = await this.helper.executeExtrinsic(778 signer,779 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],780 true,781 );782783 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');784 }785786 787788789790791792793794795 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {796 return await this.setPermissions(signer, collectionId, {nesting: permissions});797 }798799 800801802803804805806807 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {808 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});809 }810811 812813814815816817818819820 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {821 const result = await this.helper.executeExtrinsic(822 signer,823 'api.tx.unique.setCollectionProperties', [collectionId, properties],824 true,825 );826827 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');828 }829830 831832833834835836837838839 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {840 const result = await this.helper.executeExtrinsic(841 signer,842 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],843 true,844 );845846 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');847 }848849 850851852853854855856857858859860 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {861 const result = await this.helper.executeExtrinsic(862 signer,863 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],864 true, 865 );866867 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);868 }869870 871872873874875876877878879880881882883 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {884 const result = await this.helper.executeExtrinsic(885 signer,886 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],887 true, 888 );889 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);890 }891892 893894895896897898899900901902903 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{904 success: boolean,905 token: number | null906 }> {907 const burnResult = await this.helper.executeExtrinsic(908 signer,909 'api.tx.unique.burnItem', [collectionId, tokenId, amount],910 true, 911 );912 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);913 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');914 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};915 }916917 918919920921922923924925926927928 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {929 const burnResult = await this.helper.executeExtrinsic(930 signer,931 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],932 true, 933 );934 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);935 return burnedTokens.success && burnedTokens.tokens.length > 0;936 }937938 939940941942943944945946947948 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {949 const approveResult = await this.helper.executeExtrinsic(950 signer, 951 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],952 true, 953 );954955 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');956 }957958 959960961962963964965966967968 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {969 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();970 }971972 973974975976977978979 async getLastTokenId(collectionId: number): Promise<number> {980 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();981 }982983 984985986987988989990991 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {992 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();993 }994}995996class NFTnRFT extends CollectionGroup {997 998999100010011002100310041005 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1006 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1007 }10081009 1010101110121013101410151016101710181019 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1020 properties: IProperty[];1021 owner: ICrossAccountId;1022 normalizedOwner: ICrossAccountId;1023 }| null> {1024 let tokenData;1025 if(typeof blockHashAt === 'undefined') {1026 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1027 }1028 else {1029 if(propertyKeys.length == 0) {1030 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1031 if(!collection) return null;1032 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1033 }1034 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1035 }1036 tokenData = tokenData.toHuman();1037 if (tokenData === null || tokenData.owner === null) return null;1038 const owner = {} as any;1039 for (const key of Object.keys(tokenData.owner)) {1040 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1041 }1042 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1043 return tokenData;1044 }10451046 10471048104910501051105210531054105510561057 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1058 const result = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1061 true,1062 );10631064 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1065 }10661067 1068106910701071107210731074107510761077 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1078 const result = await this.helper.executeExtrinsic(1079 signer,1080 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1081 true,1082 );10831084 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1085 }10861087 108810891090109110921093109410951096 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1097 const result = await this.helper.executeExtrinsic(1098 signer,1099 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1100 true,1101 );11021103 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1104 }11051106 110711081109111011111112111311141115 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1116 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1117 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1118 for (const key of ['name', 'description', 'tokenPrefix']) {1119 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);1120 }1121 const creationResult = await this.helper.executeExtrinsic(1122 signer,1123 'api.tx.unique.createCollectionEx', [collectionOptions],1124 true, 1125 );1126 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1127 }11281129 getCollectionObject(_collectionId: number): any {1130 return null;1131 }11321133 getTokenObject(_collectionId: number, _tokenId: number): any {1134 return null;1135 }1136}113711381139class NFTGroup extends NFTnRFT {1140 114111421143114411451146 getCollectionObject(collectionId: number): UniqueNFTCollection {1147 return new UniqueNFTCollection(collectionId, this.helper);1148 }11491150 1151115211531154115511561157 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1158 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1159 }11601161 11621163116411651166116711681169 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1170 let owner;1171 if (typeof blockHashAt === 'undefined') {1172 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1173 } else {1174 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1175 }1176 return crossAccountIdFromLower(owner.toJSON());1177 }11781179 1180118111821183118411851186 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1187 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1188 }11891190 1191119211931194119511961197119811991200 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1201 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1202 }12031204 120512061207120812091210121112121213121412151216 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1217 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1218 }12191220 12211222122312241225122612271228 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1229 let owner;1230 if (typeof blockHashAt === 'undefined') {1231 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1232 } else {1233 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1234 }12351236 if (owner === null) return null;12371238 owner = owner.toHuman();12391240 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1241 }12421243 12441245124612471248124912501251 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1252 let children;1253 if(typeof blockHashAt === 'undefined') {1254 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1255 } else {1256 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1257 }12581259 return children.toJSON().map((x: any) => {1260 return {collectionId: x.collection, tokenId: x.token};1261 });1262 }12631264 12651266126712681269127012711272 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1273 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1274 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1275 if(!result) {1276 throw Error('Unable to nest token!');1277 }1278 return result;1279 }12801281 128212831284128512861287128812891290 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1291 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1292 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1293 if(!result) {1294 throw Error('Unable to unnest token!');1295 }1296 return result;1297 }12981299 130013011302130313041305130613071308130913101311 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1312 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1313 }13141315 131613171318131913201321 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1322 const creationResult = await this.helper.executeExtrinsic(1323 signer,1324 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1325 nft: {1326 properties: data.properties,1327 },1328 }],1329 true,1330 );1331 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1332 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1333 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1334 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1335 }13361337 133813391340134113421343134413451346134713481349135013511352 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1353 const creationResult = await this.helper.executeExtrinsic(1354 signer,1355 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1356 true,1357 );1358 const collection = this.getCollectionObject(collectionId);1359 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1360 }13611362 136313641365136613671368136913701371137213731374137513761377137813791380 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1381 const rawTokens = [];1382 for (const token of tokens) {1383 const raw = {NFT: {properties: token.properties}};1384 rawTokens.push(raw);1385 }1386 const creationResult = await this.helper.executeExtrinsic(1387 signer,1388 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1389 true,1390 );1391 const collection = this.getCollectionObject(collectionId);1392 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1393 }13941395 13961397139813991400140114021403 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1404 return await super.burnToken(signer, collectionId, tokenId, 1n);1405 }14061407 1408140914101411141214131414141514161417 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 142514261427142814291430 getCollectionObject(collectionId: number): UniqueRFTCollection {1431 return new UniqueRFTCollection(collectionId, this.helper);1432 }14331434 1435143614371438143914401441 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1442 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1443 }14441445 1446144714481449145014511452 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 14571458145914601461146214631464 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 1469147014711472147314741475147614771478 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 14831484148514861487148814891490149114921493 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 149814991500150115021503150415051506150715081509 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1510 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1511 }15121513 1514151515161517151815191520 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, 1543 );1544 const collection = this.getCollectionObject(collectionId);1545 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1546 }15471548 154915501551155215531554155515561557 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 157315741575157615771578157915801581 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 15861587158815891590159115921593159415951596 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1597 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1598 }15991600 1601160216031604160516061607 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1608 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1609 }16101611 161216131614161516161617161816191620 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 163516361637163816391640 getCollectionObject(collectionId: number): UniqueFTCollection {1641 return new UniqueFTCollection(collectionId, this.helper);1642 }16431644 1645164616471648164916501651165216531654165516561657 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1658 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1659 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 167316741675167616771678167916801681 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): 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, 1690 );1691 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1692 }16931694 16951696169716981699170017011702 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): 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 171717181719172017211722 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1723 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1724 }17251726 1727172817291730173117321733 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1734 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1735 }17361737 173817391740174117421743174417451746 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1747 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1748 }17491750 1751175217531754175517561757175817591760 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 17651766176717681769177017711772 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1773 return (await super.burnToken(signer, collectionId, 0, amount)).success;1774 }17751776 177717781779178017811782178317841785 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1786 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1787 }17881789 17901791179217931794 async getTotalPieces(collectionId: number): Promise<bigint> {1795 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1796 }17971798 1799180018011802180318041805180618071808 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1809 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1810 }18111812 1813181418151816181718181819 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1820 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1821 }1822}182318241825class ChainGroup extends HelperGroup {1826 18271828182918301831 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 18411842184318441845 async getLatestBlockNumber(): Promise<number> {1846 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1847 }18481849 185018511852185318541855 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 186218631864186518661867 async getNonce(address: TSubstrateAccount): Promise<number> {1868 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1869 }1870}187118721873class BalanceGroup extends HelperGroup {1874 18751876187718781879 getOneTokenNominal(): bigint {1880 const chainProperties = this.helper.chain.getChainProperties();1881 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1882 }18831884 188518861887188818891890 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1891 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1892 }18931894 189518961897189818991900 async getEthereum(address: TEthereumAccount): Promise<bigint> {1901 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1902 }19031904 19051906190719081909191019111912 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1913 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);19141915 let transfer = {from: null, to: null, amount: 0n} as any;1916 result.result.events.forEach(({event: {data, method, section}}) => {1917 if ((section === 'balances') && (method === 'Transfer')) {1918 transfer = {1919 from: this.helper.address.normalizeSubstrate(data[0]),1920 to: this.helper.address.normalizeSubstrate(data[1]),1921 amount: BigInt(data[2]),1922 };1923 }1924 });1925 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1926 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1927 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1928 return isSuccess;1929 }1930}193119321933class AddressGroup extends HelperGroup {1934 1935193619371938193919401941 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1942 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1943 }19441945 194619471948194919501951 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1952 const info = this.helper.chain.getChainProperties();1953 return encodeAddress(decodeAddress(address), info.ss58Format);1954 }19551956 1957195819591960196119621963 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1964 if(!toChainFormat) return evmToAddress(ethAddress);1965 const info = this.helper.chain.getChainProperties();1966 return evmToAddress(ethAddress, info.ss58Format);1967 }19681969 197019711972197319741975 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1976 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1977 }1978}197919801981export class UniqueHelper extends ChainHelperBase {1982 chain: ChainGroup;1983 balance: BalanceGroup;1984 address: AddressGroup;1985 collection: CollectionGroup;1986 nft: NFTGroup;1987 rft: RFTGroup;1988 ft: FTGroup;19891990 constructor(logger?: ILogger) {1991 super(logger);1992 this.chain = new ChainGroup(this);1993 this.balance = new BalanceGroup(this);1994 this.address = new AddressGroup(this);1995 this.collection = new CollectionGroup(this);1996 this.nft = new NFTGroup(this);1997 this.rft = new RFTGroup(this);1998 this.ft = new FTGroup(this);1999 } 2000}200120022003class UniqueCollectionBase {2004 helper: UniqueHelper;2005 collectionId: number;20062007 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2008 this.collectionId = collectionId;2009 this.helper = uniqueHelper;2010 }20112012 async getData() {2013 return await this.helper.collection.getData(this.collectionId);2014 }20152016 async getLastTokenId() {2017 return await this.helper.collection.getLastTokenId(this.collectionId);2018 }20192020 async isTokenExists(tokenId: number) {2021 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2022 }20232024 async getAdmins() {2025 return await this.helper.collection.getAdmins(this.collectionId);2026 }20272028 async getAllowList() {2029 return await this.helper.collection.getAllowList(this.collectionId);2030 }20312032 async getEffectiveLimits() {2033 return await this.helper.collection.getEffectiveLimits(this.collectionId);2034 }20352036 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2037 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2038 }20392040 async confirmSponsorship(signer: TSigner) {2041 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2042 }20432044 async removeSponsor(signer: TSigner) {2045 return await this.helper.collection.removeSponsor(signer, this.collectionId);2046 }20472048 async setLimits(signer: TSigner, limits: ICollectionLimits) {2049 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2050 }20512052 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2053 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2054 }20552056 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2057 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2058 }20592060 async enableCertainPermissions(signer: TSigner, accessMode: 'AllowList' | 'Normal' | undefined = 'AllowList', mintMode: boolean | undefined = true) {2061 return await this.setPermissions(signer, {access: accessMode, mintMode: mintMode});2062 }20632064 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2065 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2066 }20672068 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2069 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2070 }20712072 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2073 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2074 }20752076 async setProperties(signer: TSigner, properties: IProperty[]) {2077 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2078 }20792080 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2081 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2082 }20832084 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2085 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2086 }20872088 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2089 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2090 }20912092 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2093 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2094 }20952096 async disableNesting(signer: TSigner) {2097 return await this.helper.collection.disableNesting(signer, this.collectionId);2098 }20992100 async burn(signer: TSigner) {2101 return await this.helper.collection.burn(signer, this.collectionId);2102 }2103}210421052106class UniqueNFTCollection extends UniqueCollectionBase {2107 getTokenObject(tokenId: number) {2108 return new UniqueNFTToken(tokenId, this);2109 }21102111 async getTokensByAddress(addressObj: ICrossAccountId) {2112 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2113 }21142115 async getToken(tokenId: number, blockHashAt?: string) {2116 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2117 }21182119 async getTokenOwner(tokenId: number, blockHashAt?: string) {2120 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2121 }21222123 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2124 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2125 }21262127 async getTokenChildren(tokenId: number, blockHashAt?: string) {2128 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2129 }21302131 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2132 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2133 }21342135 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2136 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2137 }21382139 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2140 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2141 }21422143 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2144 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2145 }21462147 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2148 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2149 }21502151 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2152 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2153 }21542155 async burnToken(signer: TSigner, tokenId: number) {2156 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2157 }21582159 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2160 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2161 }21622163 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2164 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2165 }21662167 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2168 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2169 }21702171 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2172 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2173 }21742175 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2176 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2177 }2178}217921802181class UniqueRFTCollection extends UniqueCollectionBase {2182 getTokenObject(tokenId: number) {2183 return new UniqueRFTToken(tokenId, this);2184 }21852186 async getTokensByAddress(addressObj: ICrossAccountId) {2187 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2188 }21892190 async getTop10TokenOwners(tokenId: number) {2191 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2192 }21932194 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2195 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2196 }21972198 async getTokenTotalPieces(tokenId: number) {2199 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2200 }22012202 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2203 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2204 }22052206 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2207 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2208 }22092210 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2211 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2212 }22132214 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2215 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2216 }22172218 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2219 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2220 }22212222 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2223 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2224 }22252226 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2227 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2228 }22292230 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2231 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2232 }22332234 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2235 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2236 }22372238 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2239 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2240 }22412242 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2243 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2244 }2245}224622472248class UniqueFTCollection extends UniqueCollectionBase {2249 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2250 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2251 }22522253 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2254 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2255 }22562257 async getBalance(addressObj: ICrossAccountId) {2258 return await this.helper.ft.getBalance(this.collectionId, addressObj);2259 }22602261 async getTop10Owners() {2262 return await this.helper.ft.getTop10Owners(this.collectionId);2263 }22642265 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2266 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2267 }22682269 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2270 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2271 }22722273 async burnTokens(signer: TSigner, amount=1n) {2274 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2275 }22762277 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2278 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2279 }22802281 async getTotalPieces() {2282 return await this.helper.ft.getTotalPieces(this.collectionId);2283 }22842285 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2286 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2287 }22882289 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2290 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2291 }2292}229322942295class UniqueTokenBase implements IToken {2296 collection: UniqueNFTCollection | UniqueRFTCollection;2297 collectionId: number;2298 tokenId: number;22992300 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2301 this.collection = collection;2302 this.collectionId = collection.collectionId;2303 this.tokenId = tokenId;2304 }23052306 async getNextSponsored(addressObj: ICrossAccountId) {2307 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2308 }23092310 async setProperties(signer: TSigner, properties: IProperty[]) {2311 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2312 }23132314 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2315 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2316 }2317}231823192320class UniqueNFTToken extends UniqueTokenBase {2321 collection: UniqueNFTCollection;23222323 constructor(tokenId: number, collection: UniqueNFTCollection) {2324 super(tokenId, collection);2325 this.collection = collection;2326 }23272328 async getData(blockHashAt?: string) {2329 return await this.collection.getToken(this.tokenId, blockHashAt);2330 }23312332 async getOwner(blockHashAt?: string) {2333 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2334 }23352336 async getTopmostOwner(blockHashAt?: string) {2337 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2338 }23392340 async getChildren(blockHashAt?: string) {2341 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2342 }23432344 async nest(signer: TSigner, toTokenObj: IToken) {2345 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2346 }23472348 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2349 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2350 }23512352 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2353 return await this.collection.transferToken(signer, this.tokenId, addressObj);2354 }23552356 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2357 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2358 }23592360 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2361 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2362 }23632364 async isApproved(toAddressObj: ICrossAccountId) {2365 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2366 }23672368 async burn(signer: TSigner) {2369 return await this.collection.burnToken(signer, this.tokenId);2370 }2371}23722373class UniqueRFTToken extends UniqueTokenBase {2374 collection: UniqueRFTCollection;23752376 constructor(tokenId: number, collection: UniqueRFTCollection) {2377 super(tokenId, collection);2378 this.collection = collection;2379 }23802381 async getTop10Owners() {2382 return await this.collection.getTop10TokenOwners(this.tokenId);2383 }23842385 async getBalance(addressObj: ICrossAccountId) {2386 return await this.collection.getTokenBalance(this.tokenId, addressObj);2387 }23882389 async getTotalPieces() {2390 return await this.collection.getTokenTotalPieces(this.tokenId);2391 }23922393 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2394 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2395 }23962397 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2398 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2399 }24002401 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2402 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2403 }24042405 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2406 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2407 }24082409 async repartition(signer: TSigner, amount: bigint) {2410 return await this.collection.repartitionToken(signer, this.tokenId, amount);2411 }24122413 async burn(signer: TSigner, amount=1n) {2414 return await this.collection.burnToken(signer, this.tokenId, amount);2415 }2416}