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, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair) {24 return new CrossAccountId({Substrate: account.address});25 }2627 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29 }3031 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32 return encodeAddress(decodeAddress(address), ss58Format);33 }3435 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37 }38 39 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41 return this;42 }43 44 toLowerCase(): CrossAccountId {45 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47 return this;48 }49}5051const nesting = {52 toChecksumAddress(address: string): string {53 if (typeof address === 'undefined') return '';5455 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);5657 address = address.toLowerCase().replace(/^0x/i,'');58 const addressHash = keccakAsHex(address).replace(/^0x/i,'');59 const checksumAddress = ['0x'];6061 for (let i = 0; i < address.length; i++) {62 63 if (parseInt(addressHash[i], 16) > 7) {64 checksumAddress.push(address[i].toUpperCase());65 } else {66 checksumAddress.push(address[i]);67 }68 }69 return checksumAddress.join('');70 },71 tokenIdToAddress(collectionId: number, tokenId: number) {72 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);73 },74};7576class UniqueUtil {77 static transactionStatus = {78 NOT_READY: 'NotReady',79 FAIL: 'Fail',80 SUCCESS: 'Success',81 };8283 static chainLogType = {84 EXTRINSIC: 'extrinsic',85 RPC: 'rpc',86 };8788 static getTokenAccount(token: IToken): CrossAccountId {89 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});90 }9192 static getTokenAddress(token: IToken): string {93 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94 }9596 static getDefaultLogger(): ILogger {97 return {98 log(msg: any, level = 'INFO') {99 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));100 },101 level: {102 ERROR: 'ERROR',103 WARNING: 'WARNING',104 INFO: 'INFO',105 },106 };107 }108109 static vec2str(arr: string[] | number[]) {110 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');111 }112113 static str2vec(string: string) {114 if (typeof string !== 'string') return string;115 return Array.from(string).map(x => x.charCodeAt(0));116 }117118 static fromSeed(seed: string, ss58Format = 42) {119 const keyring = new Keyring({type: 'sr25519', ss58Format});120 return keyring.addFromUri(seed);121 }122123 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {124 if (creationResult.status !== this.transactionStatus.SUCCESS) {125 throw Error('Unable to create collection!');126 }127128 let collectionId = null;129 creationResult.result.events.forEach(({event: {data, method, section}}) => {130 if ((section === 'common') && (method === 'CollectionCreated')) {131 collectionId = parseInt(data[0].toString(), 10);132 }133 });134135 if (collectionId === null) {136 throw Error('No CollectionCreated event was found!');137 }138139 return collectionId;140 }141142 static extractTokensFromCreationResult(creationResult: ITransactionResult): {143 success: boolean, 144 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],145 } {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create tokens!');148 }149 let success = false;150 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if (method === 'ExtrinsicSuccess') {153 success = true;154 } else if ((section === 'common') && (method === 'ItemCreated')) {155 tokens.push({156 collectionId: parseInt(data[0].toString(), 10),157 tokenId: parseInt(data[1].toString(), 10),158 owner: data[2].toHuman(),159 amount: data[3].toBigInt(),160 });161 }162 });163 return {success, tokens};164 }165166 static extractTokensFromBurnResult(burnResult: ITransactionResult): {167 success: boolean, 168 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],169 } {170 if (burnResult.status !== this.transactionStatus.SUCCESS) {171 throw Error('Unable to burn tokens!');172 }173 let success = false;174 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];175 burnResult.result.events.forEach(({event: {data, method, section}}) => {176 if (method === 'ExtrinsicSuccess') {177 success = true;178 } else if ((section === 'common') && (method === 'ItemDestroyed')) {179 tokens.push({180 collectionId: parseInt(data[0].toString(), 10),181 tokenId: parseInt(data[1].toString(), 10),182 owner: data[2].toHuman(),183 amount: data[3].toBigInt(),184 });185 }186 });187 return {success, tokens};188 }189190 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {191 let eventId = null;192 events.forEach(({event: {data, method, section}}) => {193 if ((section === expectedSection) && (method === expectedMethod)) {194 eventId = parseInt(data[0].toString(), 10);195 }196 });197198 if (eventId === null) {199 throw Error(`No ${expectedMethod} event was found!`);200 }201 return eventId === collectionId;202 }203204 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {205 const normalizeAddress = (address: string | ICrossAccountId) => {206 if(typeof address === 'string') return address;207 const obj = {} as any;208 Object.keys(address).forEach(k => {209 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];210 });211 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);212 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();213 return address;214 };215 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;216 events.forEach(({event: {data, method, section}}) => {217 if ((section === 'common') && (method === 'Transfer')) {218 const hData = (data as any).toJSON();219 transfer = {220 collectionId: hData[0],221 tokenId: hData[1],222 from: normalizeAddress(hData[2]),223 to: normalizeAddress(hData[3]),224 amount: BigInt(hData[4]),225 };226 }227 });228 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;229 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);230 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);231 isSuccess = isSuccess && amount === transfer.amount;232 return isSuccess;233 }234}235236class UniqueEventHelper {237 private static extractIndex(index: any): [number, number] | string {238 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];239 return index.toJSON();240 }241242 private static extractSub(data: any, subTypes: any): {[key: string]: any} {243 let obj: any = {};244 let index = 0;245246 if (data.entries) {247 for(const [key, value] of data.entries()) {248 obj[key] = this.extractData(value, subTypes[index]);249 index++;250 }251 } else obj = data.toJSON();252253 return obj;254 }255 256 private static extractData(data: any, type: any): any {257 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();258 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();259 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);260 return data.toHuman();261 }262263 public static extractEvents(records: ITransactionResult): IEvent[] {264 const parsedEvents: IEvent[] = [];265266 records.result.events.forEach((record) => {267 const {event, phase} = record;268 const types = (event as any).typeDef;269270 const eventData: IEvent = {271 section: event.section.toString(),272 method: event.method.toString(),273 index: this.extractIndex(event.index),274 data: [],275 phase: phase.toJSON(),276 };277278 event.data.forEach((val: any, index: number) => {279 eventData.data.push(this.extractData(val, types[index]));280 });281282 parsedEvents.push(eventData);283 });284285 return parsedEvents;286 }287}288289class ChainHelperBase {290 transactionStatus = UniqueUtil.transactionStatus;291 chainLogType = UniqueUtil.chainLogType;292 util: typeof UniqueUtil;293 eventHelper: typeof UniqueEventHelper;294 logger: ILogger;295 api: ApiPromise | null;296 forcedNetwork: TUniqueNetworks | null;297 network: TUniqueNetworks | null;298 chainLog: IUniqueHelperLog[];299300 constructor(logger?: ILogger) {301 this.util = UniqueUtil;302 this.eventHelper = UniqueEventHelper;303 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();304 this.logger = logger;305 this.api = null;306 this.forcedNetwork = null;307 this.network = null;308 this.chainLog = [];309 }310311 clearChainLog(): void {312 this.chainLog = [];313 }314315 forceNetwork(value: TUniqueNetworks): void {316 this.forcedNetwork = value;317 }318319 async connect(wsEndpoint: string, listeners?: IApiListeners) {320 if (this.api !== null) throw Error('Already connected');321 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);322 this.api = api;323 this.network = network;324 }325326 async disconnect() {327 if (this.api === null) return;328 await this.api.disconnect();329 this.api = null;330 this.network = null;331 }332333 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {334 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;335 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;336 return 'opal';337 }338339 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {340 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});341 await api.isReady;342343 const network = await this.detectNetwork(api);344345 await api.disconnect();346347 return network;348 }349350 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{351 api: ApiPromise;352 network: TUniqueNetworks;353 }> {354 if(typeof network === 'undefined' || network === null) network = 'opal';355 const supportedRPC = {356 opal: {357 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,358 },359 quartz: {360 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,361 },362 unique: {363 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,364 },365 };366 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);367 const rpc = supportedRPC[network];368369 370 371372 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});373374 await api.isReadyOrError;375376 if (typeof listeners === 'undefined') listeners = {};377 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {378 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;379 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);380 }381382 return {api, network};383 }384385 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {386 const {events, status} = data;387 if (status.isReady) {388 return this.transactionStatus.NOT_READY;389 }390 if (status.isBroadcast) {391 return this.transactionStatus.NOT_READY;392 }393 if (status.isInBlock || status.isFinalized) {394 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');395 if (errors.length > 0) {396 return this.transactionStatus.FAIL;397 }398 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {399 return this.transactionStatus.SUCCESS;400 }401 }402403 return this.transactionStatus.FAIL;404 }405406 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {407 const sign = (callback: any) => {408 if(options !== null) return transaction.signAndSend(sender, options, callback);409 return transaction.signAndSend(sender, callback);410 };411 412 return new Promise(async (resolve, reject) => {413 try {414 const unsub = await sign((result: any) => {415 const status = this.getTransactionStatus(result);416417 if (status === this.transactionStatus.SUCCESS) {418 this.logger.log(`${label} successful`);419 unsub();420 resolve({result, status});421 } else if (status === this.transactionStatus.FAIL) {422 let moduleError = null;423424 if (result.hasOwnProperty('dispatchError')) {425 const dispatchError = result['dispatchError'];426427 if (dispatchError) {428 if (dispatchError.isModule) {429 const modErr = dispatchError.asModule;430 const errorMeta = dispatchError.registry.findMetaError(modErr);431432 moduleError = `${errorMeta.section}.${errorMeta.name}`;433 } else {434 moduleError = dispatchError.toHuman();435 }436 } else {437 this.logger.log(result, this.logger.level.ERROR);438 }439 }440441 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);442 unsub();443 reject({status, moduleError, result});444 }445 });446 } catch (e) {447 this.logger.log(e, this.logger.level.ERROR);448 reject(e);449 }450 });451 }452453 constructApiCall(apiCall: string, params: any[]) {454 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);455 let call = this.api as any;456 for(const part of apiCall.slice(4).split('.')) {457 call = call[part];458 }459 return call(...params);460 }461462 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {463 if(this.api === null) throw Error('API not initialized');464 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);465466 const startTime = (new Date()).getTime();467 let result: ITransactionResult;468 let events: IEvent[] = [];469 try {470 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;471 events = this.eventHelper.extractEvents(result);472 }473 catch(e) {474 if(!(e as object).hasOwnProperty('status')) throw e;475 result = e as ITransactionResult;476 }477478 const endTime = (new Date()).getTime();479480 const log = {481 executedAt: endTime,482 executionTime: endTime - startTime,483 type: this.chainLogType.EXTRINSIC,484 status: result.status,485 call: extrinsic,486 signer: this.getSignerAddress(sender),487 params,488 } as IUniqueHelperLog;489490 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;491 if(events.length > 0) log.events = events;492493 this.chainLog.push(log);494495 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);496 return result;497 }498499 async callRpc(rpc: string, params?: any[]) {500 if(typeof params === 'undefined') params = [];501 if(this.api === null) throw Error('API not initialized');502 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);503504 const startTime = (new Date()).getTime();505 let result;506 let error = null;507 const log = {508 type: this.chainLogType.RPC,509 call: rpc,510 params,511 } as IUniqueHelperLog;512513 try {514 result = await this.constructApiCall(rpc, params);515 }516 catch(e) {517 error = e;518 }519520 const endTime = (new Date()).getTime();521522 log.executedAt = endTime;523 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';524 log.executionTime = endTime - startTime;525526 this.chainLog.push(log);527528 if(error !== null) throw error;529530 return result;531 }532533 getSignerAddress(signer: IKeyringPair | string): string {534 if(typeof signer === 'string') return signer;535 return signer.address;536 }537538 fetchAllPalletNames(): string[] {539 if(this.api === null) throw Error('API not initialized');540 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());541 }542543 fetchMissingPalletNames(requiredPallets: string[]): string[] {544 const palletNames = this.fetchAllPalletNames();545 return requiredPallets.filter(p => !palletNames.includes(p));546 }547}548549550class HelperGroup {551 helper: UniqueHelper;552553 constructor(uniqueHelper: UniqueHelper) {554 this.helper = uniqueHelper;555 }556}557558559class CollectionGroup extends HelperGroup {560 561562563564565566567568569 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {570 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();571 }572573 574575576577578 async getTotalCount(): Promise<number> {579 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();580 }581582 583584585586587588589590591 async getData(collectionId: number): Promise<{592 id: number;593 name: string;594 description: string;595 tokensCount: number;596 admins: CrossAccountId[];597 normalizedOwner: TSubstrateAccount;598 raw: any599 } | null> {600 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);601 const humanCollection = collection.toHuman(), collectionData = {602 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],603 raw: humanCollection,604 } as any, jsonCollection = collection.toJSON();605 if (humanCollection === null) return null;606 collectionData.raw.limits = jsonCollection.limits;607 collectionData.raw.permissions = jsonCollection.permissions;608 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);609 for (const key of ['name', 'description']) {610 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);611 }612613 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))614 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)615 : 0;616 collectionData.admins = await this.getAdmins(collectionId);617618 return collectionData;619 }620621 622623624625626627628629 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {630 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();631632 return normalize633 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())634 : admins;635 }636637 638639640641642643644 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {645 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();646 return normalize647 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())648 : allowListed;649 }650651 652653654655656657658 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {659 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();660 }661662 663664665666667668669670 async burn(signer: TSigner, collectionId: number): Promise<boolean> {671 const result = await this.helper.executeExtrinsic(672 signer,673 'api.tx.unique.destroyCollection', [collectionId],674 true,675 );676677 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');678 }679680 681682683684685686687688689 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {690 const result = await this.helper.executeExtrinsic(691 signer,692 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],693 true,694 );695696 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');697 }698699 700701702703704705706707 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {708 const result = await this.helper.executeExtrinsic(709 signer,710 'api.tx.unique.confirmSponsorship', [collectionId],711 true,712 );713714 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');715 }716717 718719720721722723724725 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {726 const result = await this.helper.executeExtrinsic(727 signer,728 'api.tx.unique.removeCollectionSponsor', [collectionId],729 true,730 );731732 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');733 }734735 736737738739740741742743744745746747748749750751752 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {753 const result = await this.helper.executeExtrinsic(754 signer,755 'api.tx.unique.setCollectionLimits', [collectionId, limits],756 true,757 );758759 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');760 }761762 763764765766767768769770771 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {772 const result = await this.helper.executeExtrinsic(773 signer,774 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],775 true,776 );777778 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');779 }780781 782783784785786787788789790 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {791 const result = await this.helper.executeExtrinsic(792 signer,793 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],794 true,795 );796797 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');798 }799800 801802803804805806807808809 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {810 const result = await this.helper.executeExtrinsic(811 signer,812 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],813 true,814 );815816 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');817 }818819 820821822823824825826827 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {828 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();829 }830831 832833834835836837838 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {839 const result = await this.helper.executeExtrinsic(840 signer,841 'api.tx.unique.addToAllowList', [collectionId, addressObj],842 true,843 );844845 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');846 }847848 849850851852853854855856 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {857 const result = await this.helper.executeExtrinsic(858 signer,859 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],860 true,861 );862863 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');864 }865866 867868869870871872873874875 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {876 const result = await this.helper.executeExtrinsic(877 signer,878 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],879 true,880 );881882 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');883 }884885 886887888889890891892893894 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {895 return await this.setPermissions(signer, collectionId, {nesting: permissions});896 }897898 899900901902903904905906 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {907 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});908 }909910 911912913914915916917918919 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.setCollectionProperties', [collectionId, properties],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');927 }928929 930931932933934935936937 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {938 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();939 }940941 942943944945946947948949950 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {951 const result = await this.helper.executeExtrinsic(952 signer,953 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],954 true,955 );956957 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');958 }959960 961962963964965966967968969970971 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],975 true, 976 );977978 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);979 }980981 982983984985986987988989990991992993994 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],998 true, 999 );1000 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1001 }10021003 10041005100610071008100910101011101210131014 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1015 const burnResult = await this.helper.executeExtrinsic(1016 signer,1017 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1018 true, 1019 );1020 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1021 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1022 return burnedTokens.success;1023 }10241025 10261027102810291030103110321033103410351036 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1037 const burnResult = await this.helper.executeExtrinsic(1038 signer,1039 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1040 true, 1041 );1042 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1043 return burnedTokens.success && burnedTokens.tokens.length > 0;1044 }10451046 1047104810491050105110521053105410551056 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1057 const approveResult = await this.helper.executeExtrinsic(1058 signer,1059 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1060 true, 1061 );10621063 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1064 }10651066 1067106810691070107110721073107410751076 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1077 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1078 }10791080 1081108210831084108510861087 async getLastTokenId(collectionId: number): Promise<number> {1088 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1089 }10901091 10921093109410951096109710981099 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1100 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1101 }1102}11031104class NFTnRFT extends CollectionGroup {1105 11061107110811091110111111121113 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1114 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1115 }11161117 1118111911201121112211231124112511261127 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1128 properties: IProperty[];1129 owner: CrossAccountId;1130 normalizedOwner: CrossAccountId;1131 }| null> {1132 let tokenData;1133 if(typeof blockHashAt === 'undefined') {1134 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1135 }1136 else {1137 if(propertyKeys.length == 0) {1138 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1139 if(!collection) return null;1140 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1141 }1142 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1143 }1144 tokenData = tokenData.toHuman();1145 if (tokenData === null || tokenData.owner === null) return null;1146 const owner = {} as any;1147 for (const key of Object.keys(tokenData.owner)) {1148 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1149 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1150 : tokenData.owner[key];1151 }1152 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1153 return tokenData;1154 }11551156 11571158115911601161116211631164116511661167 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1168 const result = await this.helper.executeExtrinsic(1169 signer,1170 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1171 true,1172 );11731174 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1175 }11761177 11781179118011811182118311841185 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1186 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1187 }11881189 1190119111921193119411951196119711981199 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1200 const result = await this.helper.executeExtrinsic(1201 signer,1202 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1203 true,1204 );12051206 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1207 }12081209 121012111212121312141215121612171218 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1219 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1220 }12211222 122312241225122612271228122912301231 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1232 const result = await this.helper.executeExtrinsic(1233 signer,1234 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1235 true,1236 );12371238 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1239 }12401241 124212431244124512461247124812491250 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1251 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1252 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1253 for (const key of ['name', 'description', 'tokenPrefix']) {1254 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);1255 }1256 const creationResult = await this.helper.executeExtrinsic(1257 signer,1258 'api.tx.unique.createCollectionEx', [collectionOptions],1259 true, 1260 );1261 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1262 }12631264 getCollectionObject(_collectionId: number): any {1265 return null;1266 }12671268 getTokenObject(_collectionId: number, _tokenId: number): any {1269 return null;1270 }1271}127212731274class NFTGroup extends NFTnRFT {1275 127612771278127912801281 getCollectionObject(collectionId: number): UniqueNFTCollection {1282 return new UniqueNFTCollection(collectionId, this.helper);1283 }12841285 1286128712881289129012911292 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1293 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1294 }12951296 12971298129913001301130213031304 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1305 let owner;1306 if (typeof blockHashAt === 'undefined') {1307 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1308 } else {1309 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1310 }1311 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1312 }13131314 1315131613171318131913201321 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1322 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1323 }13241325 1326132713281329133013311332133313341335 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1336 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1337 }13381339 134013411342134313441345134613471348134913501351 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1352 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1353 }13541355 13561357135813591360136113621363 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1364 let owner;1365 if (typeof blockHashAt === 'undefined') {1366 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1367 } else {1368 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1369 }13701371 if (owner === null) return null;13721373 return owner.toHuman();1374 }13751376 13771378137913801381138213831384 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1385 let children;1386 if(typeof blockHashAt === 'undefined') {1387 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1388 } else {1389 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1390 }13911392 return children.toJSON().map((x: any) => {1393 return {collectionId: x.collection, tokenId: x.token};1394 });1395 }13961397 13981399140014011402140314041405 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1406 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1407 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1408 if(!result) {1409 throw Error('Unable to nest token!');1410 }1411 return result;1412 }14131414 141514161417141814191420142114221423 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1424 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1425 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1426 if(!result) {1427 throw Error('Unable to unnest token!');1428 }1429 return result;1430 }14311432 143314341435143614371438143914401441144214431444 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1445 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1446 }14471448 144914501451145214531454 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1455 const creationResult = await this.helper.executeExtrinsic(1456 signer,1457 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1458 nft: {1459 properties: data.properties,1460 },1461 }],1462 true,1463 );1464 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1465 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1466 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1467 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1468 }14691470 147114721473147414751476147714781479148014811482148314841485 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1486 const creationResult = await this.helper.executeExtrinsic(1487 signer,1488 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1489 true,1490 );1491 const collection = this.getCollectionObject(collectionId);1492 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1493 }14941495 149614971498149915001501150215031504150515061507150815091510151115121513 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1514 const rawTokens = [];1515 for (const token of tokens) {1516 const raw = {NFT: {properties: token.properties}};1517 rawTokens.push(raw);1518 }1519 const creationResult = await this.helper.executeExtrinsic(1520 signer,1521 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1522 true,1523 );1524 const collection = this.getCollectionObject(collectionId);1525 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1526 }15271528 1529153015311532153315341535153615371538 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1539 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1540 }1541}154215431544class RFTGroup extends NFTnRFT {1545 154615471548154915501551 getCollectionObject(collectionId: number): UniqueRFTCollection {1552 return new UniqueRFTCollection(collectionId, this.helper);1553 }15541555 1556155715581559156015611562 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1563 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1564 }15651566 1567156815691570157115721573 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1574 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1575 }15761577 15781579158015811582158315841585 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1586 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1587 }15881589 1590159115921593159415951596159715981599 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1600 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1601 }16021603 16041605160616071608160916101611161216131614 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1615 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1616 }16171618 161916201621162216231624162516261627162816291630 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1631 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1632 }16331634 1635163616371638163916401641 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1642 const creationResult = await this.helper.executeExtrinsic(1643 signer,1644 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1645 refungible: {1646 pieces: data.pieces,1647 properties: data.properties,1648 },1649 }],1650 true,1651 );1652 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1653 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1654 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1655 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1656 }16571658 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1659 throw Error('Not implemented');1660 const creationResult = await this.helper.executeExtrinsic(1661 signer,1662 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1663 true, 1664 );1665 const collection = this.getCollectionObject(collectionId);1666 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1667 }16681669 167016711672167316741675167616771678 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1679 const rawTokens = [];1680 for (const token of tokens) {1681 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1682 rawTokens.push(raw);1683 }1684 const creationResult = await this.helper.executeExtrinsic(1685 signer,1686 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1687 true,1688 );1689 const collection = this.getCollectionObject(collectionId);1690 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1691 }16921693 169416951696169716981699170017011702 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1703 return await super.burnToken(signer, collectionId, tokenId, amount);1704 }17051706 1707170817091710171117121713171417151716 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1717 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1718 }17191720 17211722172317241725172617271728172917301731 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1732 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1733 }17341735 1736173717381739174017411742 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1743 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1744 }17451746 174717481749175017511752175317541755 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1756 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1757 const repartitionResult = await this.helper.executeExtrinsic(1758 signer,1759 'api.tx.unique.repartition', [collectionId, tokenId, amount],1760 true,1761 );1762 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1763 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1764 }1765}176617671768class FTGroup extends CollectionGroup {1769 177017711772177317741775 getCollectionObject(collectionId: number): UniqueFTCollection {1776 return new UniqueFTCollection(collectionId, this.helper);1777 }17781779 1780178117821783178417851786178717881789179017911792 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1793 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1794 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1795 collectionOptions.mode = {fungible: decimalPoints};1796 for (const key of ['name', 'description', 'tokenPrefix']) {1797 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);1798 }1799 const creationResult = await this.helper.executeExtrinsic(1800 signer,1801 'api.tx.unique.createCollectionEx', [collectionOptions],1802 true,1803 );1804 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1805 }18061807 180818091810181118121813181418151816 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1817 const creationResult = await this.helper.executeExtrinsic(1818 signer,1819 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1820 fungible: {1821 value: amount,1822 },1823 }],1824 true, 1825 );1826 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1827 }18281829 18301831183218331834183518361837 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1838 const rawTokens = [];1839 for (const token of tokens) {1840 const raw = {Fungible: {Value: token.value}};1841 rawTokens.push(raw);1842 }1843 const creationResult = await this.helper.executeExtrinsic(1844 signer,1845 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1846 true,1847 );1848 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1849 }18501851 185218531854185518561857 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1858 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1859 }18601861 1862186318641865186618671868 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1869 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1870 }18711872 187318741875187618771878187918801881 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1882 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1883 }18841885 1886188718881889189018911892189318941895 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1896 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1897 }18981899 19001901190219031904190519061907 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1908 return await super.burnToken(signer, collectionId, 0, amount);1909 }19101911 191219131914191519161917191819191920 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1921 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1922 }19231924 19251926192719281929 async getTotalPieces(collectionId: number): Promise<bigint> {1930 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1931 }19321933 1934193519361937193819391940194119421943 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1944 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1945 }19461947 1948194919501951195219531954 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1955 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1956 }1957}195819591960class ChainGroup extends HelperGroup {1961 19621963196419651966 getChainProperties(): IChainProperties {1967 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1968 return {1969 ss58Format: properties.ss58Format.toJSON(),1970 tokenDecimals: properties.tokenDecimals.toJSON(),1971 tokenSymbol: properties.tokenSymbol.toJSON(),1972 };1973 }19741975 19761977197819791980 async getLatestBlockNumber(): Promise<number> {1981 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1982 }19831984 198519861987198819891990 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1991 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1992 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1993 return blockHash;1994 }19951996 1997 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1998 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1999 if (!blockHash) return null;2000 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2001 }20022003 200420052006200720082009 async getNonce(address: TSubstrateAccount): Promise<number> {2010 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2011 }2012}201320142015class BalanceGroup extends HelperGroup {2016 20172018201920202021 getOneTokenNominal(): bigint {2022 const chainProperties = this.helper.chain.getChainProperties();2023 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2024 }20252026 202720282029203020312032 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2033 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2034 }20352036 20372038203920402041 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2042 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2043 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2044 }20452046 204720482049205020512052 async getEthereum(address: TEthereumAccount): Promise<bigint> {2053 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2054 }20552056 20572058205920602061206220632064 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2065 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20662067 let transfer = {from: null, to: null, amount: 0n} as any;2068 result.result.events.forEach(({event: {data, method, section}}) => {2069 if ((section === 'balances') && (method === 'Transfer')) {2070 transfer = {2071 from: this.helper.address.normalizeSubstrate(data[0]),2072 to: this.helper.address.normalizeSubstrate(data[1]),2073 amount: BigInt(data[2]),2074 };2075 }2076 });2077 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2078 && this.helper.address.normalizeSubstrate(address) === transfer.to 2079 && BigInt(amount) === transfer.amount;2080 return isSuccess;2081 }2082}208320842085class AddressGroup extends HelperGroup {2086 2087208820892090209120922093 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2094 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2095 }20962097 209820992100210121022103 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2104 const info = this.helper.chain.getChainProperties();2105 return encodeAddress(decodeAddress(address), info.ss58Format);2106 }21072108 2109211021112112211321142115 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2116 if(!toChainFormat) return evmToAddress(ethAddress);2117 const info = this.helper.chain.getChainProperties();2118 return evmToAddress(ethAddress, info.ss58Format);2119 }21202121 212221232124212521262127 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2128 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2129 }2130}21312132class StakingGroup extends HelperGroup {2133 2134213521362137213821392140 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2141 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2142 const stakeResult = await this.helper.executeExtrinsic(2143 signer, 'api.tx.appPromotion.stake',2144 [amountToStake], true,2145 );2146 2147 return true;2148 }21492150 2151215221532154215521562157 async unstake(signer: TSigner, label?: string): Promise<number> {2158 if(typeof label === 'undefined') label = `${signer.address}`;2159 const unstakeResult = await this.helper.executeExtrinsic(2160 signer, 'api.tx.appPromotion.unstake',2161 [], true,2162 );2163 2164 return 1;2165 }21662167 21682169217021712172 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2173 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2174 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2175 }21762177 21782179218021812182 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2183 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2184 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2185 return { 2186 block: block.toBigInt(),2187 amount: amount.toBigInt(),2188 };2189 });2190 }21912192 21932194219521962197 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2198 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2199 }22002201 22022203220422052206 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2207 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2208 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2209 return {2210 block: block.toBigInt(),2211 amount: amount.toBigInt(),2212 };2213 });2214 return result;2215 }2216}22172218export class UniqueHelper extends ChainHelperBase {2219 chain: ChainGroup;2220 balance: BalanceGroup;2221 address: AddressGroup;2222 collection: CollectionGroup;2223 nft: NFTGroup;2224 rft: RFTGroup;2225 ft: FTGroup;2226 staking: StakingGroup;22272228 constructor(logger?: ILogger) {2229 super(logger);2230 this.chain = new ChainGroup(this);2231 this.balance = new BalanceGroup(this);2232 this.address = new AddressGroup(this);2233 this.collection = new CollectionGroup(this);2234 this.nft = new NFTGroup(this);2235 this.rft = new RFTGroup(this);2236 this.ft = new FTGroup(this);2237 this.staking = new StakingGroup(this);2238 }2239}224022412242export class UniqueBaseCollection {2243 helper: UniqueHelper;2244 collectionId: number;22452246 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2247 this.collectionId = collectionId;2248 this.helper = uniqueHelper;2249 }22502251 async getData() {2252 return await this.helper.collection.getData(this.collectionId);2253 }22542255 async getLastTokenId() {2256 return await this.helper.collection.getLastTokenId(this.collectionId);2257 }22582259 async isTokenExists(tokenId: number) {2260 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2261 }22622263 async getAdmins() {2264 return await this.helper.collection.getAdmins(this.collectionId);2265 }22662267 async getAllowList() {2268 return await this.helper.collection.getAllowList(this.collectionId);2269 }22702271 async getEffectiveLimits() {2272 return await this.helper.collection.getEffectiveLimits(this.collectionId);2273 }22742275 async getProperties(propertyKeys: string[] | null = null) {2276 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2277 }22782279 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2280 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2281 }22822283 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2284 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2285 }22862287 async confirmSponsorship(signer: TSigner) {2288 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2289 }22902291 async removeSponsor(signer: TSigner) {2292 return await this.helper.collection.removeSponsor(signer, this.collectionId);2293 }22942295 async setLimits(signer: TSigner, limits: ICollectionLimits) {2296 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2297 }22982299 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2300 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2301 }23022303 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2304 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2305 }23062307 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2308 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2309 }23102311 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2312 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2313 }23142315 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2316 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2317 }23182319 async setProperties(signer: TSigner, properties: IProperty[]) {2320 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2321 }23222323 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2324 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2325 }23262327 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2328 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2329 }23302331 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2332 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2333 }23342335 async disableNesting(signer: TSigner) {2336 return await this.helper.collection.disableNesting(signer, this.collectionId);2337 }23382339 async burn(signer: TSigner) {2340 return await this.helper.collection.burn(signer, this.collectionId);2341 }2342}234323442345export class UniqueNFTCollection extends UniqueBaseCollection {2346 getTokenObject(tokenId: number) {2347 return new UniqueNFToken(tokenId, this);2348 }23492350 async getTokensByAddress(addressObj: ICrossAccountId) {2351 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2352 }23532354 async getToken(tokenId: number, blockHashAt?: string) {2355 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2356 }23572358 async getTokenOwner(tokenId: number, blockHashAt?: string) {2359 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2360 }23612362 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2363 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2364 }23652366 async getTokenChildren(tokenId: number, blockHashAt?: string) {2367 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2368 }23692370 async getPropertyPermissions(propertyKeys: string[] | null = null) {2371 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2372 }23732374 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2375 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2376 }23772378 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2379 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2380 }23812382 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2383 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2384 }23852386 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2387 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2388 }23892390 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2391 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2392 }23932394 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2395 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2396 }23972398 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2399 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2400 }24012402 async burnToken(signer: TSigner, tokenId: number) {2403 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2404 }24052406 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2407 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2408 }24092410 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2411 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2412 }24132414 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2415 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2416 }24172418 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2419 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2420 }24212422 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2423 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2424 }24252426 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2427 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2428 }2429}243024312432export class UniqueRFTCollection extends UniqueBaseCollection {2433 getTokenObject(tokenId: number) {2434 return new UniqueRFToken(tokenId, this);2435 }24362437 async getToken(tokenId: number, blockHashAt?: string) {2438 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2439 }24402441 async getTokensByAddress(addressObj: ICrossAccountId) {2442 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2443 }24442445 async getTop10TokenOwners(tokenId: number) {2446 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2447 }24482449 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2450 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2451 }24522453 async getTokenTotalPieces(tokenId: number) {2454 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2455 }24562457 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2458 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2459 }24602461 async getPropertyPermissions(propertyKeys: string[] | null = null) {2462 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2463 }24642465 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2466 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2467 }24682469 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2470 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2471 }24722473 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2474 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2475 }24762477 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2478 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2479 }24802481 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2482 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2483 }24842485 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2486 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2487 }24882489 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2490 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2491 }24922493 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2494 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2495 }24962497 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2498 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2499 }25002501 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2502 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2503 }25042505 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2506 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2507 }25082509 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2510 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2511 }2512}251325142515export class UniqueFTCollection extends UniqueBaseCollection {2516 async getBalance(addressObj: ICrossAccountId) {2517 return await this.helper.ft.getBalance(this.collectionId, addressObj);2518 }25192520 async getTotalPieces() {2521 return await this.helper.ft.getTotalPieces(this.collectionId);2522 }25232524 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2525 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2526 }25272528 async getTop10Owners() {2529 return await this.helper.ft.getTop10Owners(this.collectionId);2530 }25312532 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2533 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2534 }25352536 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2537 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2538 }25392540 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2541 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2542 }25432544 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2545 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2546 }25472548 async burnTokens(signer: TSigner, amount=1n) {2549 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2550 }25512552 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2553 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2554 }25552556 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2557 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2558 }2559}256025612562export class UniqueBaseToken {2563 collection: UniqueNFTCollection | UniqueRFTCollection;2564 collectionId: number;2565 tokenId: number;25662567 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2568 this.collection = collection;2569 this.collectionId = collection.collectionId;2570 this.tokenId = tokenId;2571 }25722573 async getNextSponsored(addressObj: ICrossAccountId) {2574 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2575 }25762577 async getProperties(propertyKeys: string[] | null = null) {2578 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2579 }25802581 async setProperties(signer: TSigner, properties: IProperty[]) {2582 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2583 }25842585 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2586 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2587 }25882589 nestingAccount() {2590 return this.collection.helper.util.getTokenAccount(this);2591 }2592}259325942595export class UniqueNFToken extends UniqueBaseToken {2596 collection: UniqueNFTCollection;25972598 constructor(tokenId: number, collection: UniqueNFTCollection) {2599 super(tokenId, collection);2600 this.collection = collection;2601 }26022603 async getData(blockHashAt?: string) {2604 return await this.collection.getToken(this.tokenId, blockHashAt);2605 }26062607 async getOwner(blockHashAt?: string) {2608 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2609 }26102611 async getTopmostOwner(blockHashAt?: string) {2612 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2613 }26142615 async getChildren(blockHashAt?: string) {2616 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2617 }26182619 async nest(signer: TSigner, toTokenObj: IToken) {2620 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2621 }26222623 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2624 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2625 }26262627 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2628 return await this.collection.transferToken(signer, this.tokenId, addressObj);2629 }26302631 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2632 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2633 }26342635 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2636 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2637 }26382639 async isApproved(toAddressObj: ICrossAccountId) {2640 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2641 }26422643 async burn(signer: TSigner) {2644 return await this.collection.burnToken(signer, this.tokenId);2645 }26462647 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2648 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2649 }2650}26512652export class UniqueRFToken extends UniqueBaseToken {2653 collection: UniqueRFTCollection;26542655 constructor(tokenId: number, collection: UniqueRFTCollection) {2656 super(tokenId, collection);2657 this.collection = collection;2658 }26592660 async getData(blockHashAt?: string) {2661 return await this.collection.getToken(this.tokenId, blockHashAt);2662 }26632664 async getTop10Owners() {2665 return await this.collection.getTop10TokenOwners(this.tokenId);2666 }26672668 async getBalance(addressObj: ICrossAccountId) {2669 return await this.collection.getTokenBalance(this.tokenId, addressObj);2670 }26712672 async getTotalPieces() {2673 return await this.collection.getTokenTotalPieces(this.tokenId);2674 }26752676 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2677 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2678 }26792680 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2681 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2682 }26832684 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2685 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2686 }26872688 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2689 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2690 }26912692 async repartition(signer: TSigner, amount: bigint) {2693 return await this.collection.repartitionToken(signer, this.tokenId, amount);2694 }26952696 async burn(signer: TSigner, amount=1n) {2697 return await this.collection.burnToken(signer, this.tokenId, amount);2698 }26992700 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2701 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2702 }2703}