12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, ITokenAddress, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks, ICollectionBase, ICollectionNFT, ICollectionRFT, ITokenBase, ITokenNonfungible, ITokenRefungible, ICollectionFT} from './types';1314export const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};2021const nesting = {22 toChecksumAddress(address: string): string {23 if (typeof address === 'undefined') return '';2425 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2627 address = address.toLowerCase().replace(/^0x/i,'');28 const addressHash = keccakAsHex(address).replace(/^0x/i,'');29 const checksumAddress = ['0x'];3031 for (let i = 0; i < address.length; i++) {32 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 getTokenAccount(token: ITokenAddress): ICrossAccountId {59 return {Ethereum: this.getTokenAddress(token)};60 }6162 static getTokenAccountInLowerCase(token: ITokenAddress): ICrossAccountId {63 return {Ethereum: this.getTokenAddress(token).toLowerCase()};64 }6566 static getTokenAddress(token: ITokenAddress): string {67 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);68 }6970 static getDefaultLogger(): ILogger {71 return {72 log(msg: any, level = 'INFO') {73 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));74 },75 level: {76 ERROR: 'ERROR',77 WARNING: 'WARNING',78 INFO: 'INFO',79 },80 };81 }8283 static vec2str(arr: string[] | number[]) {84 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');85 }8687 static str2vec(string: string) {88 if (typeof string !== 'string') return string;89 return Array.from(string).map(x => x.charCodeAt(0));90 }9192 static fromSeed(seed: string, ss58Format = 42) {93 const keyring = new Keyring({type: 'sr25519', ss58Format});94 return keyring.addFromUri(seed);95 }9697 static normalizeSubstrateAddress(address: string, ss58Format = 42) {98 return encodeAddress(decodeAddress(address), ss58Format);99 }100101 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {102 if (creationResult.status !== this.transactionStatus.SUCCESS) {103 throw Error('Unable to create collection!');104 }105106 let collectionId = null;107 creationResult.result.events.forEach(({event: {data, method, section}}) => {108 if ((section === 'common') && (method === 'CollectionCreated')) {109 collectionId = parseInt(data[0].toString(), 10);110 }111 });112113 if (collectionId === null) {114 throw Error('No CollectionCreated event was found!');115 }116117 return collectionId;118 }119120 static extractTokensFromCreationResult(creationResult: ITransactionResult) {121 if (creationResult.status !== this.transactionStatus.SUCCESS) {122 throw Error('Unable to create tokens!');123 }124 let success = false;125 const tokens = [] as any;126 creationResult.result.events.forEach(({event: {data, method, section}}) => {127 if (method === 'ExtrinsicSuccess') {128 success = true;129 } else if ((section === 'common') && (method === 'ItemCreated')) {130 tokens.push({131 collectionId: parseInt(data[0].toString(), 10),132 tokenId: parseInt(data[1].toString(), 10),133 owner: data[2].toJSON(),134 });135 }136 });137 return {success, tokens};138 }139140 static extractTokensFromBurnResult(burnResult: ITransactionResult) {141 if (burnResult.status !== this.transactionStatus.SUCCESS) {142 throw Error('Unable to burn tokens!');143 }144 let success = false;145 const tokens = [] as any;146 burnResult.result.events.forEach(({event: {data, method, section}}) => {147 if (method === 'ExtrinsicSuccess') {148 success = true;149 } else if ((section === 'common') && (method === 'ItemDestroyed')) {150 tokens.push({151 collectionId: parseInt(data[0].toString(), 10),152 tokenId: parseInt(data[1].toString(), 10),153 owner: data[2].toJSON(),154 });155 }156 });157 return {success, tokens};158 }159160 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {161 let eventId = null;162 events.forEach(({event: {data, method, section}}) => {163 if ((section === expectedSection) && (method === expectedMethod)) {164 eventId = parseInt(data[0].toString(), 10);165 }166 });167168 if (eventId === null) {169 throw Error(`No ${expectedMethod} event was found!`);170 }171 return eventId === collectionId;172 }173174 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {175 const normalizeAddress = (address: string | ICrossAccountId) => {176 if(typeof address === 'string') return address;177 const obj = {} as any;178 Object.keys(address).forEach(k => {179 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];180 });181 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};182 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};183 return address;184 };185 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;186 events.forEach(({event: {data, method, section}}) => {187 if ((section === 'common') && (method === 'Transfer')) {188 const hData = (data as any).toJSON();189 transfer = {190 collectionId: hData[0],191 tokenId: hData[1],192 from: normalizeAddress(hData[2]),193 to: normalizeAddress(hData[3]),194 amount: BigInt(hData[4]),195 };196 }197 });198 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;199 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);200 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);201 isSuccess = isSuccess && amount === transfer.amount;202 return isSuccess;203 }204}205206class UniqueEventHelper {207 private static extractIndex(index: any): [number, number] | string {208 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];209 return index.toJSON();210 }211212 private static extractSub(data: any, subTypes: any): {[key: string]: any} {213 let obj: any = {};214 let index = 0;215216 if (data.entries) {217 for(const [key, value] of data.entries()) {218 obj[key] = this.extractData(value, subTypes[index]);219 index++;220 }221 } else obj = data.toJSON();222223 return obj;224 }225 226 private static extractData(data: any, type: any): any {227 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();228 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();229 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);230 return data.toHuman();231 }232233 public static extractEvents(records: ITransactionResult): IEvent[] {234 const parsedEvents: IEvent[] = [];235236 records.result.events.forEach((record) => {237 const {event, phase} = record;238 const types = (event as any).typeDef;239240 const eventData: IEvent = {241 section: event.section.toString(),242 method: event.method.toString(),243 index: this.extractIndex(event.index),244 data: [],245 phase: phase.toJSON(),246 };247248 event.data.forEach((val: any, index: number) => {249 eventData.data.push(this.extractData(val, types[index]));250 });251252 parsedEvents.push(eventData);253 });254255 return parsedEvents;256 }257}258259class ChainHelperBase {260 transactionStatus = UniqueUtil.transactionStatus;261 chainLogType = UniqueUtil.chainLogType;262 util: typeof UniqueUtil;263 eventHelper: typeof UniqueEventHelper;264 logger: ILogger;265 api: ApiPromise | null;266 forcedNetwork: TUniqueNetworks | null;267 network: TUniqueNetworks | null;268 chainLog: IUniqueHelperLog[];269270 constructor(logger?: ILogger) {271 this.util = UniqueUtil;272 this.eventHelper = UniqueEventHelper;273 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();274 this.logger = logger;275 this.api = null;276 this.forcedNetwork = null;277 this.network = null;278 this.chainLog = [];279 }280281 clearChainLog(): void {282 this.chainLog = [];283 }284285 forceNetwork(value: TUniqueNetworks): void {286 this.forcedNetwork = value;287 }288289 async connect(wsEndpoint: string, listeners?: IApiListeners) {290 if (this.api !== null) throw Error('Already connected');291 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);292 this.api = api;293 this.network = network;294 }295296 async disconnect() {297 if (this.api === null) return;298 await this.api.disconnect();299 this.api = null;300 this.network = null;301 }302303 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {304 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;305 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;306 return 'opal';307 }308309 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {310 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});311 await api.isReady;312313 const network = await this.detectNetwork(api);314315 await api.disconnect();316317 return network;318 }319320 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{321 api: ApiPromise;322 network: TUniqueNetworks;323 }> {324 if(typeof network === 'undefined' || network === null) network = 'opal';325 const supportedRPC = {326 opal: {327 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,328 },329 quartz: {330 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,331 },332 unique: {333 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,334 },335 };336 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);337 const rpc = supportedRPC[network];338339 340 341342 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});343344 await api.isReadyOrError;345346 if (typeof listeners === 'undefined') listeners = {};347 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {348 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;349 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);350 }351352 return {api, network};353 }354355 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {356 const {events, status} = data;357 if (status.isReady) {358 return this.transactionStatus.NOT_READY;359 }360 if (status.isBroadcast) {361 return this.transactionStatus.NOT_READY;362 }363 if (status.isInBlock || status.isFinalized) {364 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');365 if (errors.length > 0) {366 return this.transactionStatus.FAIL;367 }368 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {369 return this.transactionStatus.SUCCESS;370 }371 }372373 return this.transactionStatus.FAIL;374 }375376 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {377 const sign = (callback: any) => {378 if(options !== null) return transaction.signAndSend(sender, options, callback);379 return transaction.signAndSend(sender, callback);380 };381 382 return new Promise(async (resolve, reject) => {383 try {384 const unsub = await sign((result: any) => {385 const status = this.getTransactionStatus(result);386387 if (status === this.transactionStatus.SUCCESS) {388 this.logger.log(`${label} successful`);389 unsub();390 resolve({result, status});391 } else if (status === this.transactionStatus.FAIL) {392 let moduleError = null;393394 if (result.hasOwnProperty('dispatchError')) {395 const dispatchError = result['dispatchError'];396397 if (dispatchError) {398 if (dispatchError.isModule) {399 const modErr = dispatchError.asModule;400 const errorMeta = dispatchError.registry.findMetaError(modErr);401402 moduleError = `${errorMeta.section}.${errorMeta.name}`;403 } else {404 moduleError = dispatchError.toHuman();405 }406 } else {407 this.logger.log(result, this.logger.level.ERROR);408 }409 }410411 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);412 unsub();413 reject({status, moduleError, result});414 }415 });416 } catch (e) {417 this.logger.log(e, this.logger.level.ERROR);418 reject(e);419 }420 });421 }422423 constructApiCall(apiCall: string, params: any[]) {424 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);425 let call = this.api as any;426 for(const part of apiCall.slice(4).split('.')) {427 call = call[part];428 }429 return call(...params);430 }431432 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {433 if(this.api === null) throw Error('API not initialized');434 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);435436 const startTime = (new Date()).getTime();437 let result: ITransactionResult;438 let events: IEvent[] = [];439 try {440 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;441 events = this.eventHelper.extractEvents(result);442 }443 catch(e) {444 if(!(e as object).hasOwnProperty('status')) throw e;445 result = e as ITransactionResult;446 }447448 const endTime = (new Date()).getTime();449450 const log = {451 executedAt: endTime,452 executionTime: endTime - startTime,453 type: this.chainLogType.EXTRINSIC,454 status: result.status,455 call: extrinsic,456 signer: this.getSignerAddress(sender),457 params,458 } as IUniqueHelperLog;459460 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;461 if(events.length > 0) log.events = events;462463 this.chainLog.push(log);464465 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);466 return result;467 }468469 async callRpc(rpc: string, params?: any[]) {470 if(typeof params === 'undefined') params = [];471 if(this.api === null) throw Error('API not initialized');472 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);473474 const startTime = (new Date()).getTime();475 let result;476 let error = null;477 const log = {478 type: this.chainLogType.RPC,479 call: rpc,480 params,481 } as IUniqueHelperLog;482483 try {484 result = await this.constructApiCall(rpc, params);485 }486 catch(e) {487 error = e;488 }489490 const endTime = (new Date()).getTime();491492 log.executedAt = endTime;493 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';494 log.executionTime = endTime - startTime;495496 this.chainLog.push(log);497498 if(error !== null) throw error;499500 return result;501 }502503 getSignerAddress(signer: IKeyringPair | string): string {504 if(typeof signer === 'string') return signer;505 return signer.address;506 }507508 fetchAllPalletNames(): string[] {509 if(this.api === null) throw Error('API not initialized');510 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());511 }512513 fetchMissingPalletNames(requiredPallets: string[]): string[] {514 const palletNames = this.fetchAllPalletNames();515 return requiredPallets.filter(p => !palletNames.includes(p));516 }517}518519520class HelperGroup {521 helper: UniqueHelper;522523 constructor(uniqueHelper: UniqueHelper) {524 this.helper = uniqueHelper;525 }526}527528529class CollectionGroup extends HelperGroup {530 531532533534535536537538539 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {540 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();541 }542543 544545546547548 async getTotalCount(): Promise<number> {549 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();550 }551552 553554555556557558559560561 async getData(collectionId: number): Promise<{562 id: number;563 name: string;564 description: string;565 tokensCount: number;566 admins: ICrossAccountId[];567 normalizedOwner: TSubstrateAccount;568 raw: any569 } | null> {570 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);571 const humanCollection = collection.toHuman(), collectionData = {572 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],573 raw: humanCollection,574 } as any, jsonCollection = collection.toJSON();575 if (humanCollection === null) return null;576 collectionData.raw.limits = jsonCollection.limits;577 collectionData.raw.permissions = jsonCollection.permissions;578 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);579 for (const key of ['name', 'description']) {580 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);581 }582583 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))584 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)585 : 0;586 collectionData.admins = await this.getAdmins(collectionId);587588 return collectionData;589 }590591 592593594595596597598599 async getAdmins(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {600 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();601602 return normalize603 ? admins.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))604 : admins;605 }606607 608609610611612613614 async getAllowList(collectionId: number, normalize = false): Promise<ICrossAccountId[]> {615 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();616 return normalize617 ? allowListed.map((address: any) => this.helper.address.normalizeCrossAccountIfSubstrate(address))618 : allowListed;619 }620621 622623624625626627628 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {629 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();630 }631632 633634635636637638639640 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 651652653654655656657658659 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 670671672673674675676677 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 688689690691692693694695 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 706707708709710711712713714715716717718719720721722 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 733734735736737738739740741 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 752753754755756757758759760 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 771772773774775776777778779 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 790791792793794795796797 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {798 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();799 }800801 802803804805806807808 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 819820821822823824825826 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 837838839840841842843844845 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 856857858859860861862863864 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {865 return await this.setPermissions(signer, collectionId, {nesting: permissions});866 }867868 869870871872873874875876 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {877 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});878 }879880 881882883884885886887888889 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 900901902903904905906907 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {908 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();909 }910911 912913914915916917918919920 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {921 const result = await this.helper.executeExtrinsic(922 signer,923 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],924 true,925 );926927 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');928 }929930 931932933934935936937938939940941 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {942 const result = await this.helper.executeExtrinsic(943 signer,944 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],945 true, 946 );947948 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);949 }950951 952953954955956957958959960961962963964 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {965 const result = await this.helper.executeExtrinsic(966 signer,967 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],968 true, 969 );970 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);971 }972973 974975976977978979980981982983984 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{985 success: boolean,986 token: number | null987 }> {988 const burnResult = await this.helper.executeExtrinsic(989 signer,990 'api.tx.unique.burnItem', [collectionId, tokenId, amount],991 true, 992 );993 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);994 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');995 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};996 }997998 9991000100110021003100410051006100710081009 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1010 const burnResult = await this.helper.executeExtrinsic(1011 signer,1012 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1013 true, 1014 );1015 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1016 return burnedTokens.success && burnedTokens.tokens.length > 0;1017 }10181019 1020102110221023102410251026102710281029 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1030 const approveResult = await this.helper.executeExtrinsic(1031 signer,1032 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1033 true, 1034 );10351036 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1037 }10381039 1040104110421043104410451046104710481049 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1050 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1051 }10521053 1054105510561057105810591060 async getLastTokenId(collectionId: number): Promise<number> {1061 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1062 }10631064 10651066106710681069107010711072 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1073 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1074 }1075}10761077class NFTnRFT extends CollectionGroup {1078 10791080108110821083108410851086 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1087 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1088 }10891090 1091109210931094109510961097109810991100 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1101 properties: IProperty[];1102 owner: ICrossAccountId;1103 normalizedOwner: ICrossAccountId;1104 }| null> {1105 let tokenData;1106 if(typeof blockHashAt === 'undefined') {1107 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1108 }1109 else {1110 if(propertyKeys.length == 0) {1111 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1112 if(!collection) return null;1113 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1114 }1115 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1116 }1117 tokenData = tokenData.toHuman();1118 if (tokenData === null || tokenData.owner === null) return null;1119 const owner = {} as any;1120 for (const key of Object.keys(tokenData.owner)) {1121 owner[key.toLocaleLowerCase()] = this.helper.address.normalizeCrossAccountIfSubstrate(tokenData.owner[key]);1122 }1123 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1124 return tokenData;1125 }11261127 11281129113011311132113311341135113611371138 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1139 const result = await this.helper.executeExtrinsic(1140 signer,1141 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1142 true,1143 );11441145 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1146 }11471148 11491150115111521153115411551156 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1157 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1158 }11591160 1161116211631164116511661167116811691170 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1171 const result = await this.helper.executeExtrinsic(1172 signer,1173 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1174 true,1175 );11761177 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1178 }11791180 118111821183118411851186118711881189 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1190 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1191 }11921193 119411951196119711981199120012011202 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1203 const result = await this.helper.executeExtrinsic(1204 signer,1205 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1206 true,1207 );12081209 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1210 }12111212 121312141215121612171218121912201221 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1222 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1223 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1224 for (const key of ['name', 'description', 'tokenPrefix']) {1225 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1226 }1227 const creationResult = await this.helper.executeExtrinsic(1228 signer,1229 'api.tx.unique.createCollectionEx', [collectionOptions],1230 true, 1231 );1232 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1233 }12341235 getCollectionObject(_collectionId: number): any {1236 return null;1237 }12381239 getTokenObject(_collectionId: number, _tokenId: number): any {1240 return null;1241 }1242}124312441245class NFTGroup extends NFTnRFT {1246 124712481249125012511252 getCollectionObject(collectionId: number): UniqueNFTCollection {1253 return new UniqueNFTCollection(collectionId, this.helper);1254 }12551256 1257125812591260126112621263 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1264 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1265 }12661267 12681269127012711272127312741275 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1276 let owner;1277 if (typeof blockHashAt === 'undefined') {1278 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1279 } else {1280 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1281 }1282 return crossAccountIdFromLower(owner.toJSON());1283 }12841285 1286128712881289129012911292 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1293 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1294 }12951296 1297129812991300130113021303130413051306 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1307 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1308 }13091310 131113121313131413151316131713181319132013211322 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1323 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1324 }13251326 13271328132913301331133213331334 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1335 let owner;1336 if (typeof blockHashAt === 'undefined') {1337 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1338 } else {1339 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1340 }13411342 if (owner === null) return null;13431344 return owner.toHuman();1345 }13461347 13481349135013511352135313541355 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ITokenAddress[]> {1356 let children;1357 if(typeof blockHashAt === 'undefined') {1358 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1359 } else {1360 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1361 }13621363 return children.toJSON().map((x: any) => {1364 return {collectionId: x.collection, tokenId: x.token};1365 });1366 }13671368 13691370137113721373137413751376 async nestToken(signer: TSigner, tokenObj: ITokenAddress, rootTokenObj: ITokenAddress): Promise<boolean> {1377 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1378 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1379 if(!result) {1380 throw Error('Unable to nest token!');1381 }1382 return result;1383 }13841385 138613871388138913901391139213931394 async unnestToken(signer: TSigner, tokenObj: ITokenAddress, rootTokenObj: ITokenAddress, toAddressObj: ICrossAccountId): Promise<boolean> {1395 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1396 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1397 if(!result) {1398 throw Error('Unable to unnest token!');1399 }1400 return result;1401 }14021403 140414051406140714081409141014111412141314141415 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1416 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1417 }14181419 142014211422142314241425 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1426 const creationResult = await this.helper.executeExtrinsic(1427 signer,1428 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1429 nft: {1430 properties: data.properties,1431 },1432 }],1433 true,1434 );1435 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1436 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1437 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1438 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1439 }14401441 144214431444144514461447144814491450145114521453145414551456 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1457 const creationResult = await this.helper.executeExtrinsic(1458 signer,1459 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1460 true,1461 );1462 const collection = this.getCollectionObject(collectionId);1463 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1464 }14651466 146714681469147014711472147314741475147614771478147914801481148214831484 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1485 const rawTokens = [];1486 for (const token of tokens) {1487 const raw = {NFT: {properties: token.properties}};1488 rawTokens.push(raw);1489 }1490 const creationResult = await this.helper.executeExtrinsic(1491 signer,1492 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1493 true,1494 );1495 const collection = this.getCollectionObject(collectionId);1496 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1497 }14981499 1500150115021503150415051506150715081509 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1510 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1511 }1512}151315141515class RFTGroup extends NFTnRFT {1516 151715181519152015211522 getCollectionObject(collectionId: number): UniqueRFTCollection {1523 return new UniqueRFTCollection(collectionId, this.helper);1524 }15251526 1527152815291530153115321533 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1534 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1535 }15361537 1538153915401541154215431544 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1545 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1546 }15471548 15491550155115521553155415551556 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1557 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1558 }15591560 1561156215631564156515661567156815691570 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1571 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1572 }15731574 15751576157715781579158015811582158315841585 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1586 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1587 }15881589 159015911592159315941595159615971598159916001601 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1602 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1603 }16041605 1606160716081609161016111612 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1613 const creationResult = await this.helper.executeExtrinsic(1614 signer,1615 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1616 refungible: {1617 pieces: data.pieces,1618 properties: data.properties,1619 },1620 }],1621 true,1622 );1623 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1624 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1625 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1626 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1627 }16281629 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1630 throw Error('Not implemented');1631 const creationResult = await this.helper.executeExtrinsic(1632 signer,1633 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1634 true, 1635 );1636 const collection = this.getCollectionObject(collectionId);1637 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1638 }16391640 164116421643164416451646164716481649 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1650 const rawTokens = [];1651 for (const token of tokens) {1652 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1653 rawTokens.push(raw);1654 }1655 const creationResult = await this.helper.executeExtrinsic(1656 signer,1657 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1658 true,1659 );1660 const collection = this.getCollectionObject(collectionId);1661 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: ITokenAddress) => collection.getTokenObject(x.tokenId));1662 }16631664 166516661667166816691670167116721673 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1674 return await super.burnToken(signer, collectionId, tokenId, amount);1675 }16761677 1678167916801681168216831684168516861687 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1688 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1689 }16901691 16921693169416951696169716981699170017011702 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1703 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1704 }17051706 1707170817091710171117121713 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1714 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1715 }17161717 171817191720172117221723172417251726 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1727 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1728 const repartitionResult = await this.helper.executeExtrinsic(1729 signer,1730 'api.tx.unique.repartition', [collectionId, tokenId, amount],1731 true,1732 );1733 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1734 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1735 }1736}173717381739class FTGroup extends CollectionGroup {1740 174117421743174417451746 getCollectionObject(collectionId: number): UniqueFTCollection {1747 return new UniqueFTCollection(collectionId, this.helper);1748 }17491750 1751175217531754175517561757175817591760176117621763 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1764 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1765 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1766 collectionOptions.mode = {fungible: decimalPoints};1767 for (const key of ['name', 'description', 'tokenPrefix']) {1768 if (typeof collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] === 'string') collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] = this.helper.util.str2vec(collectionOptions[key as 'name' | 'description' | 'tokenPrefix'] as string);1769 }1770 const creationResult = await this.helper.executeExtrinsic(1771 signer,1772 'api.tx.unique.createCollectionEx', [collectionOptions],1773 true,1774 );1775 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1776 }17771778 177917801781178217831784178517861787 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1788 const creationResult = await this.helper.executeExtrinsic(1789 signer,1790 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1791 fungible: {1792 value: amount,1793 },1794 }],1795 true, 1796 );1797 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1798 }17991800 18011802180318041805180618071808 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1809 const rawTokens = [];1810 for (const token of tokens) {1811 const raw = {Fungible: {Value: token.value}};1812 rawTokens.push(raw);1813 }1814 const creationResult = await this.helper.executeExtrinsic(1815 signer,1816 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1817 true,1818 );1819 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1820 }18211822 182318241825182618271828 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1829 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1830 }18311832 1833183418351836183718381839 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1840 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1841 }18421843 184418451846184718481849185018511852 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1853 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1854 }18551856 1857185818591860186118621863186418651866 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1867 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1868 }18691870 18711872187318741875187618771878 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1879 return (await super.burnToken(signer, collectionId, 0, amount)).success;1880 }18811882 188318841885188618871888188918901891 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1892 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1893 }18941895 18961897189818991900 async getTotalPieces(collectionId: number): Promise<bigint> {1901 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1902 }19031904 1905190619071908190919101911191219131914 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1915 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1916 }19171918 1919192019211922192319241925 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1926 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1927 }1928}192919301931class ChainGroup extends HelperGroup {1932 19331934193519361937 getChainProperties(): IChainProperties {1938 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1939 return {1940 ss58Format: properties.ss58Format.toJSON(),1941 tokenDecimals: properties.tokenDecimals.toJSON(),1942 tokenSymbol: properties.tokenSymbol.toJSON(),1943 };1944 }19451946 19471948194919501951 async getLatestBlockNumber(): Promise<number> {1952 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1953 }19541955 195619571958195919601961 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1962 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1963 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1964 return blockHash;1965 }19661967 1968 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1969 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1970 if (!blockHash) return null;1971 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1972 }19731974 197519761977197819791980 async getNonce(address: TSubstrateAccount): Promise<number> {1981 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1982 }1983}198419851986class BalanceGroup extends HelperGroup {1987 19881989199019911992 getOneTokenNominal(): bigint {1993 const chainProperties = this.helper.chain.getChainProperties();1994 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1995 }19961997 199819992000200120022003 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2004 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2005 }20062007 20082009201020112012 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2013 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2014 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2015 }20162017 201820192020202120222023 async getEthereum(address: TEthereumAccount): Promise<bigint> {2024 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2025 }20262027 20282029203020312032203320342035 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2036 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20372038 let transfer = {from: null, to: null, amount: 0n} as any;2039 result.result.events.forEach(({event: {data, method, section}}) => {2040 if ((section === 'balances') && (method === 'Transfer')) {2041 transfer = {2042 from: this.helper.address.normalizeSubstrate(data[0]),2043 to: this.helper.address.normalizeSubstrate(data[1]),2044 amount: BigInt(data[2]),2045 };2046 }2047 });2048 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;2049 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;2050 isSuccess = isSuccess && BigInt(amount) === transfer.amount;2051 return isSuccess;2052 }2053}205420552056class AddressGroup extends HelperGroup {2057 2058205920602061206220632064 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2065 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);2066 }20672068 2069207020712072207320742075 normalizeCrossAccountIfSubstrate(account: ICrossAccountId, ss58Format = 42): ICrossAccountId {2076 return account.Substrate2077 ? {Substrate: this.normalizeSubstrate(account.Substrate, ss58Format)}2078 : account;2079 }20802081 208220832084208520862087 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2088 const info = this.helper.chain.getChainProperties();2089 return encodeAddress(decodeAddress(address), info.ss58Format);2090 }20912092 2093209420952096209720982099 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2100 if(!toChainFormat) return evmToAddress(ethAddress);2101 const info = this.helper.chain.getChainProperties();2102 return evmToAddress(ethAddress, info.ss58Format);2103 }21042105 210621072108210921102111 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2112 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2113 }2114}21152116class StakingGroup extends HelperGroup {2117 2118211921202121212221232124 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2125 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2126 const stakeResult = await this.helper.executeExtrinsic(2127 signer, 'api.tx.appPromotion.stake',2128 [amountToStake], true,2129 );2130 2131 return true;2132 }21332134 2135213621372138213921402141 async unstake(signer: TSigner, label?: string): Promise<number> {2142 if(typeof label === 'undefined') label = `${signer.address}`;2143 const unstakeResult = await this.helper.executeExtrinsic(2144 signer, 'api.tx.appPromotion.unstake',2145 [], true,2146 );2147 2148 return 1;2149 }21502151 21522153215421552156 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2157 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2158 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2159 }21602161 21622163216421652166 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2167 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2168 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2169 return { 2170 block: block.toBigInt(),2171 amount: amount.toBigInt(),2172 };2173 });2174 }21752176 21772178217921802181 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2182 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2183 }21842185 21862187218821892190 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2191 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2192 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2193 return {2194 block: block.toBigInt(),2195 amount: amount.toBigInt(),2196 };2197 });2198 return result;2199 }2200}22012202export class UniqueHelper extends ChainHelperBase {2203 chain: ChainGroup;2204 balance: BalanceGroup;2205 address: AddressGroup;2206 collection: CollectionGroup;2207 nft: NFTGroup;2208 rft: RFTGroup;2209 ft: FTGroup;2210 staking: StakingGroup;22112212 constructor(logger?: ILogger) {2213 super(logger);2214 this.chain = new ChainGroup(this);2215 this.balance = new BalanceGroup(this);2216 this.address = new AddressGroup(this);2217 this.collection = new CollectionGroup(this);2218 this.nft = new NFTGroup(this);2219 this.rft = new RFTGroup(this);2220 this.ft = new FTGroup(this);2221 this.staking = new StakingGroup(this);2222 }2223}222422252226class UniqueCollectionBase implements ICollectionBase {2227 helper: UniqueHelper;2228 collectionId: number;22292230 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2231 this.collectionId = collectionId;2232 this.helper = uniqueHelper;2233 }22342235 async getData() {2236 return await this.helper.collection.getData(this.collectionId);2237 }22382239 async getLastTokenId() {2240 return await this.helper.collection.getLastTokenId(this.collectionId);2241 }22422243 async isTokenExists(tokenId: number) {2244 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2245 }22462247 async getAdmins() {2248 return await this.helper.collection.getAdmins(this.collectionId);2249 }22502251 async getAllowList() {2252 return await this.helper.collection.getAllowList(this.collectionId);2253 }22542255 async getEffectiveLimits() {2256 return await this.helper.collection.getEffectiveLimits(this.collectionId);2257 }22582259 async getProperties(propertyKeys: string[] | null = null) {2260 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2261 }22622263 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2264 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2265 }22662267 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2268 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2269 }22702271 async confirmSponsorship(signer: TSigner) {2272 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2273 }22742275 async removeSponsor(signer: TSigner) {2276 return await this.helper.collection.removeSponsor(signer, this.collectionId);2277 }22782279 async setLimits(signer: TSigner, limits: ICollectionLimits) {2280 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2281 }22822283 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2284 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2285 }22862287 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2288 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2289 }22902291 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2292 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2293 }22942295 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2296 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2297 }22982299 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2300 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2301 }23022303 async setProperties(signer: TSigner, properties: IProperty[]) {2304 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2305 }23062307 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2308 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2309 }23102311 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2312 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2313 }23142315 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2316 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2317 }23182319 async disableNesting(signer: TSigner) {2320 return await this.helper.collection.disableNesting(signer, this.collectionId);2321 }23222323 async burn(signer: TSigner) {2324 return await this.helper.collection.burn(signer, this.collectionId);2325 }2326}232723282329class UniqueNFTCollection extends UniqueCollectionBase implements ICollectionNFT {2330 getTokenObject(tokenId: number) {2331 return new UniqueNFTToken(tokenId, this);2332 }23332334 async getTokensByAddress(addressObj: ICrossAccountId) {2335 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2336 }23372338 async getToken(tokenId: number, blockHashAt?: string) {2339 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2340 }23412342 async getTokenOwner(tokenId: number, blockHashAt?: string) {2343 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2344 }23452346 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2347 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2348 }23492350 async getTokenChildren(tokenId: number, blockHashAt?: string) {2351 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2352 }23532354 async getPropertyPermissions(propertyKeys: string[] | null = null) {2355 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2356 }23572358 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2359 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2360 }23612362 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2363 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2364 }23652366 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2367 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2368 }23692370 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2371 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2372 }23732374 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2375 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2376 }23772378 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2379 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2380 }23812382 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2383 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2384 }23852386 async burnToken(signer: TSigner, tokenId: number) {2387 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2388 }23892390 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2391 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2392 }23932394 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2395 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2396 }23972398 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2399 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2400 }24012402 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2403 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2404 }24052406 async nestToken(signer: TSigner, tokenId: number, toTokenObj: ITokenAddress) {2407 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2408 }24092410 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) {2411 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2412 }2413}241424152416class UniqueRFTCollection extends UniqueCollectionBase implements ICollectionRFT {2417 getTokenObject(tokenId: number) {2418 return new UniqueRFTToken(tokenId, this);2419 }24202421 async getToken(tokenId: number, blockHashAt?: string) {2422 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2423 }24242425 async getTokensByAddress(addressObj: ICrossAccountId) {2426 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2427 }24282429 async getTop10TokenOwners(tokenId: number) {2430 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2431 }24322433 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2434 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2435 }24362437 async getTokenTotalPieces(tokenId: number) {2438 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2439 }24402441 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2442 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2443 }24442445 async getPropertyPermissions(propertyKeys: string[] | null = null) {2446 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2447 }24482449 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2450 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2451 }24522453 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2454 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2455 }24562457 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2458 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2459 }24602461 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2462 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2463 }24642465 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2466 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2467 }24682469 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2470 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2471 }24722473 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2474 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2475 }24762477 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2478 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2479 }24802481 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2482 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2483 }24842485 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2486 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2487 }24882489 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2490 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2491 }24922493 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2494 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2495 }2496}249724982499class UniqueFTCollection extends UniqueCollectionBase implements ICollectionFT {2500 async getBalance(addressObj: ICrossAccountId) {2501 return await this.helper.ft.getBalance(this.collectionId, addressObj);2502 }25032504 async getTotalPieces() {2505 return await this.helper.ft.getTotalPieces(this.collectionId);2506 }25072508 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2509 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2510 }25112512 async getTop10Owners() {2513 return await this.helper.ft.getTop10Owners(this.collectionId);2514 }25152516 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2517 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2518 }25192520 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2521 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2522 }25232524 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2525 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2526 }25272528 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2529 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2530 }25312532 async burnTokens(signer: TSigner, amount=1n) {2533 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2534 }25352536 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2537 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2538 }25392540 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2541 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2542 }2543}254425452546class UniqueTokenBase implements ITokenBase {2547 collection: UniqueNFTCollection | UniqueRFTCollection;2548 collectionId: number;2549 tokenId: number;25502551 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2552 this.collection = collection;2553 this.collectionId = collection.collectionId;2554 this.tokenId = tokenId;2555 }25562557 async getNextSponsored(addressObj: ICrossAccountId) {2558 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2559 }25602561 async getProperties(propertyKeys: string[] | null = null) {2562 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2563 }25642565 async setProperties(signer: TSigner, properties: IProperty[]) {2566 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2567 }25682569 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2570 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2571 }25722573 nestingAccount() {2574 return this.collection.helper.util.getTokenAccount(this);2575 }25762577 nestingAccountInLowerCase() {2578 return this.collection.helper.util.getTokenAccountInLowerCase(this);2579 }2580}258125822583class UniqueNFTToken extends UniqueTokenBase implements ITokenNonfungible {2584 collection: UniqueNFTCollection;25852586 constructor(tokenId: number, collection: UniqueNFTCollection) {2587 super(tokenId, collection);2588 this.collection = collection;2589 }25902591 async getData(blockHashAt?: string) {2592 return await this.collection.getToken(this.tokenId, blockHashAt);2593 }25942595 async getOwner(blockHashAt?: string) {2596 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2597 }25982599 async getTopmostOwner(blockHashAt?: string) {2600 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2601 }26022603 async getChildren(blockHashAt?: string) {2604 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2605 }26062607 async nest(signer: TSigner, toTokenObj: ITokenAddress) {2608 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2609 }26102611 async unnest(signer: TSigner, fromTokenObj: ITokenAddress, toAddressObj: ICrossAccountId) {2612 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2613 }26142615 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2616 return await this.collection.transferToken(signer, this.tokenId, addressObj);2617 }26182619 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2620 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2621 }26222623 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2624 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2625 }26262627 async isApproved(toAddressObj: ICrossAccountId) {2628 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2629 }26302631 async burn(signer: TSigner) {2632 return await this.collection.burnToken(signer, this.tokenId);2633 }26342635 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2636 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2637 }2638}26392640class UniqueRFTToken extends UniqueTokenBase implements ITokenRefungible {2641 collection: UniqueRFTCollection;26422643 constructor(tokenId: number, collection: UniqueRFTCollection) {2644 super(tokenId, collection);2645 this.collection = collection;2646 }26472648 async getData(blockHashAt?: string) {2649 return await this.collection.getToken(this.tokenId, blockHashAt);2650 }26512652 async getTop10Owners() {2653 return await this.collection.getTop10TokenOwners(this.tokenId);2654 }26552656 async getBalance(addressObj: ICrossAccountId) {2657 return await this.collection.getTokenBalance(this.tokenId, addressObj);2658 }26592660 async getTotalPieces() {2661 return await this.collection.getTokenTotalPieces(this.tokenId);2662 }26632664 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2665 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2666 }26672668 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2669 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2670 }26712672 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2673 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2674 }26752676 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2677 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2678 }26792680 async repartition(signer: TSigner, amount: bigint) {2681 return await this.collection.repartitionToken(signer, this.tokenId, amount);2682 }26832684 async burn(signer: TSigner, amount=1n) {2685 return await this.collection.burnToken(signer, this.tokenId, amount);2686 }26872688 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2689 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2690 }2691}