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, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321322 constructor(logger?: ILogger) {323 this.util = UniqueUtil;324 this.eventHelper = UniqueEventHelper;325 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();326 this.logger = logger;327 this.api = null;328 this.forcedNetwork = null;329 this.network = null;330 this.chainLog = [];331 }332333 getApi(): ApiPromise {334 if(this.api === null) throw Error('API not initialized');335 return this.api;336 }337338 clearChainLog(): void {339 this.chainLog = [];340 }341342 forceNetwork(value: TUniqueNetworks): void {343 this.forcedNetwork = value;344 }345346 async connect(wsEndpoint: string, listeners?: IApiListeners) {347 if (this.api !== null) throw Error('Already connected');348 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);349 this.api = api;350 this.network = network;351 }352353 async disconnect() {354 if (this.api === null) return;355 await this.api.disconnect();356 this.api = null;357 this.network = null;358 }359360 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {361 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;362 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;363 return 'opal';364 }365366 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {367 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});368 await api.isReady;369370 const network = await this.detectNetwork(api);371372 await api.disconnect();373374 return network;375 }376377 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{378 api: ApiPromise;379 network: TUniqueNetworks;380 }> {381 if(typeof network === 'undefined' || network === null) network = 'opal';382 const supportedRPC = {383 opal: {384 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,385 },386 quartz: {387 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,388 },389 unique: {390 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,391 },392 };393 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);394 const rpc = supportedRPC[network];395396 397 398399 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});400401 await api.isReadyOrError;402403 if (typeof listeners === 'undefined') listeners = {};404 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {405 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;406 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);407 }408409 return {api, network};410 }411412 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {413 const {events, status} = data;414 if (status.isReady) {415 return this.transactionStatus.NOT_READY;416 }417 if (status.isBroadcast) {418 return this.transactionStatus.NOT_READY;419 }420 if (status.isInBlock || status.isFinalized) {421 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');422 if (errors.length > 0) {423 return this.transactionStatus.FAIL;424 }425 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {426 return this.transactionStatus.SUCCESS;427 }428 }429430 return this.transactionStatus.FAIL;431 }432433 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {434 const sign = (callback: any) => {435 if(options !== null) return transaction.signAndSend(sender, options, callback);436 return transaction.signAndSend(sender, callback);437 };438 439 return new Promise(async (resolve, reject) => {440 try {441 const unsub = await sign((result: any) => {442 const status = this.getTransactionStatus(result);443444 if (status === this.transactionStatus.SUCCESS) {445 this.logger.log(`${label} successful`);446 unsub();447 resolve({result, status});448 } else if (status === this.transactionStatus.FAIL) {449 let moduleError = null;450451 if (result.hasOwnProperty('dispatchError')) {452 const dispatchError = result['dispatchError'];453454 if (dispatchError) {455 if (dispatchError.isModule) {456 const modErr = dispatchError.asModule;457 const errorMeta = dispatchError.registry.findMetaError(modErr);458459 moduleError = `${errorMeta.section}.${errorMeta.name}`;460 } else {461 moduleError = dispatchError.toHuman();462 }463 } else {464 this.logger.log(result, this.logger.level.ERROR);465 }466 }467468 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);469 unsub();470 reject({status, moduleError, result});471 }472 });473 } catch (e) {474 this.logger.log(e, this.logger.level.ERROR);475 reject(e);476 }477 });478 }479480 constructApiCall(apiCall: string, params: any[]) {481 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);482 let call = this.api as any;483 for(const part of apiCall.slice(4).split('.')) {484 call = call[part];485 }486 return call(...params);487 }488489 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {490 if(this.api === null) throw Error('API not initialized');491 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);492493 const startTime = (new Date()).getTime();494 let result: ITransactionResult;495 let events: IEvent[] = [];496 try {497 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;498 events = this.eventHelper.extractEvents(result);499 }500 catch(e) {501 if(!(e as object).hasOwnProperty('status')) throw e;502 result = e as ITransactionResult;503 }504505 const endTime = (new Date()).getTime();506507 const log = {508 executedAt: endTime,509 executionTime: endTime - startTime,510 type: this.chainLogType.EXTRINSIC,511 status: result.status,512 call: extrinsic,513 signer: this.getSignerAddress(sender),514 params,515 } as IUniqueHelperLog;516517 if(result.status !== this.transactionStatus.SUCCESS) {518 if (result.moduleError) log.moduleError = result.moduleError;519 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;520 }521 if(events.length > 0) log.events = events;522523 this.chainLog.push(log);524525 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {526 if (result.moduleError) throw Error(`${result.moduleError}`);527 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));528 }529 return result;530 }531532 async callRpc(rpc: string, params?: any[]) {533 if(typeof params === 'undefined') params = [];534 if(this.api === null) throw Error('API not initialized');535 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);536537 const startTime = (new Date()).getTime();538 let result;539 let error = null;540 const log = {541 type: this.chainLogType.RPC,542 call: rpc,543 params,544 } as IUniqueHelperLog;545546 try {547 result = await this.constructApiCall(rpc, params);548 }549 catch(e) {550 error = e;551 }552553 const endTime = (new Date()).getTime();554555 log.executedAt = endTime;556 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';557 log.executionTime = endTime - startTime;558559 this.chainLog.push(log);560561 if(error !== null) throw error;562563 return result;564 }565566 getSignerAddress(signer: IKeyringPair | string): string {567 if(typeof signer === 'string') return signer;568 return signer.address;569 }570571 fetchAllPalletNames(): string[] {572 if(this.api === null) throw Error('API not initialized');573 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());574 }575576 fetchMissingPalletNames(requiredPallets: string[]): string[] {577 const palletNames = this.fetchAllPalletNames();578 return requiredPallets.filter(p => !palletNames.includes(p));579 }580}581582583class HelperGroup {584 helper: UniqueHelper;585586 constructor(uniqueHelper: UniqueHelper) {587 this.helper = uniqueHelper;588 }589}590591592class CollectionGroup extends HelperGroup {593 594595596597598599600601602 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {603 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();604 }605606 607608609610611 async getTotalCount(): Promise<number> {612 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();613 }614615 616617618619620621622623624 async getData(collectionId: number): Promise<{625 id: number;626 name: string;627 description: string;628 tokensCount: number;629 admins: CrossAccountId[];630 normalizedOwner: TSubstrateAccount;631 raw: any632 } | null> {633 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);634 const humanCollection = collection.toHuman(), collectionData = {635 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],636 raw: humanCollection,637 } as any, jsonCollection = collection.toJSON();638 if (humanCollection === null) return null;639 collectionData.raw.limits = jsonCollection.limits;640 collectionData.raw.permissions = jsonCollection.permissions;641 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);642 for (const key of ['name', 'description']) {643 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);644 }645646 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))647 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)648 : 0;649 collectionData.admins = await this.getAdmins(collectionId);650651 return collectionData;652 }653654 655656657658659660661662 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {663 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();664665 return normalize666 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())667 : admins;668 }669670 671672673674675676677 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {678 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();679 return normalize680 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())681 : allowListed;682 }683684 685686687688689690691 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {692 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();693 }694695 696697698699700701702703 async burn(signer: TSigner, collectionId: number): Promise<boolean> {704 const result = await this.helper.executeExtrinsic(705 signer,706 'api.tx.unique.destroyCollection', [collectionId],707 true,708 );709710 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');711 }712713 714715716717718719720721722 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {723 const result = await this.helper.executeExtrinsic(724 signer,725 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],726 true,727 );728729 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');730 }731732 733734735736737738739740 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {741 const result = await this.helper.executeExtrinsic(742 signer,743 'api.tx.unique.confirmSponsorship', [collectionId],744 true,745 );746747 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');748 }749750 751752753754755756757758 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {759 const result = await this.helper.executeExtrinsic(760 signer,761 'api.tx.unique.removeCollectionSponsor', [collectionId],762 true,763 );764765 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');766 }767768 769770771772773774775776777778779780781782783784785 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {786 const result = await this.helper.executeExtrinsic(787 signer,788 'api.tx.unique.setCollectionLimits', [collectionId, limits],789 true,790 );791792 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');793 }794795 796797798799800801802803804 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {805 const result = await this.helper.executeExtrinsic(806 signer,807 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],808 true,809 );810811 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');812 }813814 815816817818819820821822823 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {824 const result = await this.helper.executeExtrinsic(825 signer,826 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],827 true,828 );829830 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');831 }832833 834835836837838839840841842 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {843 const result = await this.helper.executeExtrinsic(844 signer,845 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],846 true,847 );848849 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');850 }851852 853854855856857858859860 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {861 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();862 }863864 865866867868869870871 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {872 const result = await this.helper.executeExtrinsic(873 signer,874 'api.tx.unique.addToAllowList', [collectionId, addressObj],875 true,876 );877878 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');879 }880881 882883884885886887888889 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {890 const result = await this.helper.executeExtrinsic(891 signer,892 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],893 true,894 );895896 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');897 }898899 900901902903904905906907908 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {909 const result = await this.helper.executeExtrinsic(910 signer,911 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],912 true,913 );914915 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');916 }917918 919920921922923924925926927 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {928 return await this.setPermissions(signer, collectionId, {nesting: permissions});929 }930931 932933934935936937938939 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {940 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});941 }942943 944945946947948949950951952 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {953 const result = await this.helper.executeExtrinsic(954 signer,955 'api.tx.unique.setCollectionProperties', [collectionId, properties],956 true,957 );958959 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');960 }961962 963964965966967968969970 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {971 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();972 }973974 975976977978979980981982983 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {984 const result = await this.helper.executeExtrinsic(985 signer,986 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],987 true,988 );989990 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');991 }992993 99499599699799899910001001100210031004 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1005 const result = await this.helper.executeExtrinsic(1006 signer,1007 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1008 true, 1009 );10101011 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1012 }10131014 1015101610171018101910201021102210231024102510261027 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1028 const result = await this.helper.executeExtrinsic(1029 signer,1030 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1031 true, 1032 );1033 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1034 }10351036 10371038103910401041104210431044104510461047 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1048 const burnResult = await this.helper.executeExtrinsic(1049 signer,1050 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1051 true, 1052 );1053 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1054 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1055 return burnedTokens.success;1056 }10571058 10591060106110621063106410651066106710681069 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1070 const burnResult = await this.helper.executeExtrinsic(1071 signer,1072 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1073 true, 1074 );1075 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1076 return burnedTokens.success && burnedTokens.tokens.length > 0;1077 }10781079 1080108110821083108410851086108710881089 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1090 const approveResult = await this.helper.executeExtrinsic(1091 signer,1092 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1093 true, 1094 );10951096 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1097 }10981099 1100110111021103110411051106110711081109 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1110 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1111 }11121113 1114111511161117111811191120 async getLastTokenId(collectionId: number): Promise<number> {1121 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1122 }11231124 11251126112711281129113011311132 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1133 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1134 }1135}11361137class NFTnRFT extends CollectionGroup {1138 11391140114111421143114411451146 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1147 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1148 }11491150 1151115211531154115511561157115811591160 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1161 properties: IProperty[];1162 owner: CrossAccountId;1163 normalizedOwner: CrossAccountId;1164 }| null> {1165 let tokenData;1166 if(typeof blockHashAt === 'undefined') {1167 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1168 }1169 else {1170 if(propertyKeys.length == 0) {1171 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1172 if(!collection) return null;1173 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1174 }1175 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1176 }1177 tokenData = tokenData.toHuman();1178 if (tokenData === null || tokenData.owner === null) return null;1179 const owner = {} as any;1180 for (const key of Object.keys(tokenData.owner)) {1181 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1182 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1183 : tokenData.owner[key];1184 }1185 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1186 return tokenData;1187 }11881189 11901191119211931194119511961197119811991200 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1201 const result = await this.helper.executeExtrinsic(1202 signer,1203 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1204 true,1205 );12061207 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1208 }12091210 12111212121312141215121612171218 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1219 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1220 }12211222 1223122412251226122712281229123012311232 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1233 const result = await this.helper.executeExtrinsic(1234 signer,1235 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1236 true,1237 );12381239 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1240 }12411242 124312441245124612471248124912501251 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1252 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1253 }12541255 125612571258125912601261126212631264 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1265 const result = await this.helper.executeExtrinsic(1266 signer,1267 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1268 true,1269 );12701271 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1272 }12731274 127512761277127812791280128112821283 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1284 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1285 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1286 for (const key of ['name', 'description', 'tokenPrefix']) {1287 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);1288 }1289 const creationResult = await this.helper.executeExtrinsic(1290 signer,1291 'api.tx.unique.createCollectionEx', [collectionOptions],1292 true, 1293 );1294 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1295 }12961297 getCollectionObject(_collectionId: number): any {1298 return null;1299 }13001301 getTokenObject(_collectionId: number, _tokenId: number): any {1302 return null;1303 }1304}130513061307class NFTGroup extends NFTnRFT {1308 130913101311131213131314 getCollectionObject(collectionId: number): UniqueNFTCollection {1315 return new UniqueNFTCollection(collectionId, this.helper);1316 }13171318 1319132013211322132313241325 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1326 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1327 }13281329 13301331133213331334133513361337 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1338 let owner;1339 if (typeof blockHashAt === 'undefined') {1340 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1341 } else {1342 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1343 }1344 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1345 }13461347 1348134913501351135213531354 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1355 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1356 }13571358 1359136013611362136313641365136613671368 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1369 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1370 }13711372 137313741375137613771378137913801381138213831384 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1385 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1386 }13871388 13891390139113921393139413951396 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1397 let owner;1398 if (typeof blockHashAt === 'undefined') {1399 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1400 } else {1401 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1402 }14031404 if (owner === null) return null;14051406 return owner.toHuman();1407 }14081409 14101411141214131414141514161417 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1418 let children;1419 if(typeof blockHashAt === 'undefined') {1420 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1421 } else {1422 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1423 }14241425 return children.toJSON().map((x: any) => {1426 return {collectionId: x.collection, tokenId: x.token};1427 });1428 }14291430 14311432143314341435143614371438 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1439 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1440 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1441 if(!result) {1442 throw Error('Unable to nest token!');1443 }1444 return result;1445 }14461447 144814491450145114521453145414551456 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1457 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1458 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1459 if(!result) {1460 throw Error('Unable to unnest token!');1461 }1462 return result;1463 }14641465 146614671468146914701471147214731474147514761477 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1478 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1479 }14801481 148214831484148514861487 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1488 const creationResult = await this.helper.executeExtrinsic(1489 signer,1490 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1491 nft: {1492 properties: data.properties,1493 },1494 }],1495 true,1496 );1497 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1498 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1499 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1500 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1501 }15021503 150415051506150715081509151015111512151315141515151615171518 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1519 const creationResult = await this.helper.executeExtrinsic(1520 signer,1521 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],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 152915301531153215331534153515361537153815391540154115421543154415451546 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1547 const rawTokens = [];1548 for (const token of tokens) {1549 const raw = {NFT: {properties: token.properties}};1550 rawTokens.push(raw);1551 }1552 const creationResult = await this.helper.executeExtrinsic(1553 signer,1554 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1555 true,1556 );1557 const collection = this.getCollectionObject(collectionId);1558 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1559 }15601561 1562156315641565156615671568156915701571 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1572 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1573 }1574}157515761577class RFTGroup extends NFTnRFT {1578 157915801581158215831584 getCollectionObject(collectionId: number): UniqueRFTCollection {1585 return new UniqueRFTCollection(collectionId, this.helper);1586 }15871588 1589159015911592159315941595 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1596 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1597 }15981599 1600160116021603160416051606 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1607 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1608 }16091610 16111612161316141615161616171618 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1619 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1620 }16211622 1623162416251626162716281629163016311632 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1633 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1634 }16351636 16371638163916401641164216431644164516461647 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1648 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1649 }16501651 165216531654165516561657165816591660166116621663 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1664 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1665 }16661667 1668166916701671167216731674 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1675 const creationResult = await this.helper.executeExtrinsic(1676 signer,1677 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1678 refungible: {1679 pieces: data.pieces,1680 properties: data.properties,1681 },1682 }],1683 true,1684 );1685 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1686 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1687 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1688 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1689 }16901691 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1692 throw Error('Not implemented');1693 const creationResult = await this.helper.executeExtrinsic(1694 signer,1695 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1696 true, 1697 );1698 const collection = this.getCollectionObject(collectionId);1699 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1700 }17011702 170317041705170617071708170917101711 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1712 const rawTokens = [];1713 for (const token of tokens) {1714 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1715 rawTokens.push(raw);1716 }1717 const creationResult = await this.helper.executeExtrinsic(1718 signer,1719 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1720 true,1721 );1722 const collection = this.getCollectionObject(collectionId);1723 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1724 }17251726 172717281729173017311732173317341735 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1736 return await super.burnToken(signer, collectionId, tokenId, amount);1737 }17381739 1740174117421743174417451746174717481749 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1750 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1751 }17521753 17541755175617571758175917601761176217631764 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1765 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1766 }17671768 1769177017711772177317741775 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1776 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1777 }17781779 178017811782178317841785178617871788 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1789 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1790 const repartitionResult = await this.helper.executeExtrinsic(1791 signer,1792 'api.tx.unique.repartition', [collectionId, tokenId, amount],1793 true,1794 );1795 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1796 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1797 }1798}179918001801class FTGroup extends CollectionGroup {1802 180318041805180618071808 getCollectionObject(collectionId: number): UniqueFTCollection {1809 return new UniqueFTCollection(collectionId, this.helper);1810 }18111812 1813181418151816181718181819182018211822182318241825 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1826 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1827 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1828 collectionOptions.mode = {fungible: decimalPoints};1829 for (const key of ['name', 'description', 'tokenPrefix']) {1830 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);1831 }1832 const creationResult = await this.helper.executeExtrinsic(1833 signer,1834 'api.tx.unique.createCollectionEx', [collectionOptions],1835 true,1836 );1837 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1838 }18391840 184118421843184418451846184718481849 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1850 const creationResult = await this.helper.executeExtrinsic(1851 signer,1852 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1853 fungible: {1854 value: amount,1855 },1856 }],1857 true, 1858 );1859 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1860 }18611862 18631864186518661867186818691870 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1871 const rawTokens = [];1872 for (const token of tokens) {1873 const raw = {Fungible: {Value: token.value}};1874 rawTokens.push(raw);1875 }1876 const creationResult = await this.helper.executeExtrinsic(1877 signer,1878 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1879 true,1880 );1881 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1882 }18831884 188518861887188818891890 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1891 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1892 }18931894 1895189618971898189919001901 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1902 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1903 }19041905 190619071908190919101911191219131914 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1915 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1916 }19171918 1919192019211922192319241925192619271928 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1929 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1930 }19311932 19331934193519361937193819391940 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1941 return await super.burnToken(signer, collectionId, 0, amount);1942 }19431944 194519461947194819491950195119521953 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1954 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1955 }19561957 19581959196019611962 async getTotalPieces(collectionId: number): Promise<bigint> {1963 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1964 }19651966 1967196819691970197119721973197419751976 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1977 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1978 }19791980 1981198219831984198519861987 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1988 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1989 }1990}199119921993class ChainGroup extends HelperGroup {1994 19951996199719981999 getChainProperties(): IChainProperties {2000 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2001 return {2002 ss58Format: properties.ss58Format.toJSON(),2003 tokenDecimals: properties.tokenDecimals.toJSON(),2004 tokenSymbol: properties.tokenSymbol.toJSON(),2005 };2006 }20072008 20092010201120122013 async getLatestBlockNumber(): Promise<number> {2014 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2015 }20162017 201820192020202120222023 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2024 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2025 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2026 return blockHash;2027 }20282029 2030 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2031 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2032 if (!blockHash) return null;2033 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2034 }20352036 203720382039204020412042 async getNonce(address: TSubstrateAccount): Promise<number> {2043 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2044 }2045}204620472048class BalanceGroup extends HelperGroup {2049 getCollectionCreationPrice(): bigint {2050 return 2n * this.helper.balance.getOneTokenNominal();2051 }2052 20532054205520562057 getOneTokenNominal(): bigint {2058 const chainProperties = this.helper.chain.getChainProperties();2059 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2060 }20612062 206320642065206620672068 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2069 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2070 }20712072 20732074207520762077 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2078 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2079 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2080 }20812082 208320842085208620872088 async getEthereum(address: TEthereumAccount): Promise<bigint> {2089 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2090 }20912092 20932094209520962097209820992100 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2101 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21022103 let transfer = {from: null, to: null, amount: 0n} as any;2104 result.result.events.forEach(({event: {data, method, section}}) => {2105 if ((section === 'balances') && (method === 'Transfer')) {2106 transfer = {2107 from: this.helper.address.normalizeSubstrate(data[0]),2108 to: this.helper.address.normalizeSubstrate(data[1]),2109 amount: BigInt(data[2]),2110 };2111 }2112 });2113 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2114 && this.helper.address.normalizeSubstrate(address) === transfer.to 2115 && BigInt(amount) === transfer.amount;2116 return isSuccess;2117 }2118}211921202121class AddressGroup extends HelperGroup {2122 2123212421252126212721282129 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2130 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2131 }21322133 213421352136213721382139 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2140 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2141 }21422143 2144214521462147214821492150 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2151 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2152 }21532154 215521562157215821592160 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2161 return CrossAccountId.translateSubToEth(subAddress);2162 }2163}21642165class StakingGroup extends HelperGroup {2166 2167216821692170217121722173 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2174 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2175 const _stakeResult = await this.helper.executeExtrinsic(2176 signer, 'api.tx.appPromotion.stake',2177 [amountToStake], true,2178 );2179 2180 return true;2181 }21822183 2184218521862187218821892190 async unstake(signer: TSigner, label?: string): Promise<number> {2191 if(typeof label === 'undefined') label = `${signer.address}`;2192 const _unstakeResult = await this.helper.executeExtrinsic(2193 signer, 'api.tx.appPromotion.unstake',2194 [], true,2195 );2196 2197 return 1;2198 }21992200 22012202220322042205 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2206 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2207 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2208 }22092210 22112212221322142215 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2216 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2217 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2218 return { 2219 block: block.toBigInt(),2220 amount: amount.toBigInt(),2221 };2222 });2223 }22242225 22262227222822292230 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2231 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2232 }22332234 22352236223722382239 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2240 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2241 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2242 return {2243 block: block.toBigInt(),2244 amount: amount.toBigInt(),2245 };2246 });2247 return result;2248 }2249}22502251export class UniqueHelper extends ChainHelperBase {2252 chain: ChainGroup;2253 balance: BalanceGroup;2254 address: AddressGroup;2255 collection: CollectionGroup;2256 nft: NFTGroup;2257 rft: RFTGroup;2258 ft: FTGroup;2259 staking: StakingGroup;22602261 constructor(logger?: ILogger) {2262 super(logger);2263 this.chain = new ChainGroup(this);2264 this.balance = new BalanceGroup(this);2265 this.address = new AddressGroup(this);2266 this.collection = new CollectionGroup(this);2267 this.nft = new NFTGroup(this);2268 this.rft = new RFTGroup(this);2269 this.ft = new FTGroup(this);2270 this.staking = new StakingGroup(this);2271 }2272}227322742275export class UniqueBaseCollection {2276 helper: UniqueHelper;2277 collectionId: number;22782279 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2280 this.collectionId = collectionId;2281 this.helper = uniqueHelper;2282 }22832284 async getData() {2285 return await this.helper.collection.getData(this.collectionId);2286 }22872288 async getLastTokenId() {2289 return await this.helper.collection.getLastTokenId(this.collectionId);2290 }22912292 async doesTokenExist(tokenId: number) {2293 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2294 }22952296 async getAdmins() {2297 return await this.helper.collection.getAdmins(this.collectionId);2298 }22992300 async getAllowList() {2301 return await this.helper.collection.getAllowList(this.collectionId);2302 }23032304 async getEffectiveLimits() {2305 return await this.helper.collection.getEffectiveLimits(this.collectionId);2306 }23072308 async getProperties(propertyKeys?: string[] | null) {2309 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2310 }23112312 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2313 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2314 }23152316 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2317 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2318 }23192320 async confirmSponsorship(signer: TSigner) {2321 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2322 }23232324 async removeSponsor(signer: TSigner) {2325 return await this.helper.collection.removeSponsor(signer, this.collectionId);2326 }23272328 async setLimits(signer: TSigner, limits: ICollectionLimits) {2329 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2330 }23312332 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2333 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2334 }23352336 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2337 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2338 }23392340 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2341 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2342 }23432344 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2345 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2346 }23472348 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2349 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2350 }23512352 async setProperties(signer: TSigner, properties: IProperty[]) {2353 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2354 }23552356 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2357 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2358 }23592360 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2361 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2362 }23632364 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2365 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2366 }23672368 async disableNesting(signer: TSigner) {2369 return await this.helper.collection.disableNesting(signer, this.collectionId);2370 }23712372 async burn(signer: TSigner) {2373 return await this.helper.collection.burn(signer, this.collectionId);2374 }2375}237623772378export class UniqueNFTCollection extends UniqueBaseCollection {2379 getTokenObject(tokenId: number) {2380 return new UniqueNFToken(tokenId, this);2381 }23822383 async getTokensByAddress(addressObj: ICrossAccountId) {2384 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2385 }23862387 async getToken(tokenId: number, blockHashAt?: string) {2388 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2389 }23902391 async getTokenOwner(tokenId: number, blockHashAt?: string) {2392 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2393 }23942395 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2396 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2397 }23982399 async getTokenChildren(tokenId: number, blockHashAt?: string) {2400 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2401 }24022403 async getPropertyPermissions(propertyKeys: string[] | null = null) {2404 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2405 }24062407 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2408 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2409 }24102411 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2412 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2413 }24142415 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2416 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2417 }24182419 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2420 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2421 }24222423 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2424 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2425 }24262427 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2428 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2429 }24302431 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2432 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2433 }24342435 async burnToken(signer: TSigner, tokenId: number) {2436 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2437 }24382439 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2440 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2441 }24422443 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2444 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2445 }24462447 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2448 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2449 }24502451 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2452 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2453 }24542455 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2456 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2457 }24582459 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2460 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2461 }2462}246324642465export class UniqueRFTCollection extends UniqueBaseCollection {2466 getTokenObject(tokenId: number) {2467 return new UniqueRFToken(tokenId, this);2468 }24692470 async getToken(tokenId: number, blockHashAt?: string) {2471 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2472 }24732474 async getTokensByAddress(addressObj: ICrossAccountId) {2475 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2476 }24772478 async getTop10TokenOwners(tokenId: number) {2479 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2480 }24812482 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2483 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2484 }24852486 async getTokenTotalPieces(tokenId: number) {2487 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2488 }24892490 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2491 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2492 }24932494 async getPropertyPermissions(propertyKeys: string[] | null = null) {2495 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2496 }24972498 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2499 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2500 }25012502 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2503 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2504 }25052506 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2507 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2508 }25092510 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2511 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2512 }25132514 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2515 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2516 }25172518 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2519 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2520 }25212522 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2523 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2524 }25252526 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2527 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2528 }25292530 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2531 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2532 }25332534 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2535 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2536 }25372538 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2539 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2540 }25412542 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2543 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2544 }2545}254625472548export class UniqueFTCollection extends UniqueBaseCollection {2549 async getBalance(addressObj: ICrossAccountId) {2550 return await this.helper.ft.getBalance(this.collectionId, addressObj);2551 }25522553 async getTotalPieces() {2554 return await this.helper.ft.getTotalPieces(this.collectionId);2555 }25562557 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2558 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2559 }25602561 async getTop10Owners() {2562 return await this.helper.ft.getTop10Owners(this.collectionId);2563 }25642565 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2566 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2567 }25682569 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2570 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2571 }25722573 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2574 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2575 }25762577 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2578 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2579 }25802581 async burnTokens(signer: TSigner, amount=1n) {2582 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2583 }25842585 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2586 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2587 }25882589 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2590 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2591 }2592}259325942595export class UniqueBaseToken {2596 collection: UniqueNFTCollection | UniqueRFTCollection;2597 collectionId: number;2598 tokenId: number;25992600 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2601 this.collection = collection;2602 this.collectionId = collection.collectionId;2603 this.tokenId = tokenId;2604 }26052606 async getNextSponsored(addressObj: ICrossAccountId) {2607 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2608 }26092610 async getProperties(propertyKeys?: string[] | null) {2611 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2612 }26132614 async setProperties(signer: TSigner, properties: IProperty[]) {2615 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2616 }26172618 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2619 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2620 }26212622 async doesExist() {2623 return await this.collection.doesTokenExist(this.tokenId);2624 }26252626 nestingAccount() {2627 return this.collection.helper.util.getTokenAccount(this);2628 }2629}263026312632export class UniqueNFToken extends UniqueBaseToken {2633 collection: UniqueNFTCollection;26342635 constructor(tokenId: number, collection: UniqueNFTCollection) {2636 super(tokenId, collection);2637 this.collection = collection;2638 }26392640 async getData(blockHashAt?: string) {2641 return await this.collection.getToken(this.tokenId, blockHashAt);2642 }26432644 async getOwner(blockHashAt?: string) {2645 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2646 }26472648 async getTopmostOwner(blockHashAt?: string) {2649 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2650 }26512652 async getChildren(blockHashAt?: string) {2653 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2654 }26552656 async nest(signer: TSigner, toTokenObj: IToken) {2657 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2658 }26592660 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2661 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2662 }26632664 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2665 return await this.collection.transferToken(signer, this.tokenId, addressObj);2666 }26672668 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2669 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2670 }26712672 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2673 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2674 }26752676 async isApproved(toAddressObj: ICrossAccountId) {2677 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2678 }26792680 async burn(signer: TSigner) {2681 return await this.collection.burnToken(signer, this.tokenId);2682 }26832684 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2685 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2686 }2687}26882689export class UniqueRFToken extends UniqueBaseToken {2690 collection: UniqueRFTCollection;26912692 constructor(tokenId: number, collection: UniqueRFTCollection) {2693 super(tokenId, collection);2694 this.collection = collection;2695 }26962697 async getData(blockHashAt?: string) {2698 return await this.collection.getToken(this.tokenId, blockHashAt);2699 }27002701 async getTop10Owners() {2702 return await this.collection.getTop10TokenOwners(this.tokenId);2703 }27042705 async getBalance(addressObj: ICrossAccountId) {2706 return await this.collection.getTokenBalance(this.tokenId, addressObj);2707 }27082709 async getTotalPieces() {2710 return await this.collection.getTokenTotalPieces(this.tokenId);2711 }27122713 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2714 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2715 }27162717 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2718 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2719 }27202721 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2722 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2723 }27242725 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2726 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2727 }27282729 async repartition(signer: TSigner, amount: bigint) {2730 return await this.collection.repartitionToken(signer, this.tokenId, amount);2731 }27322733 async burn(signer: TSigner, amount=1n) {2734 return await this.collection.burnToken(signer, this.tokenId, amount);2735 }27362737 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2738 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2739 }2740}