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 (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();279 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();280 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);281 return data.toHuman();282 }283284 public static extractEvents(records: ITransactionResult): IEvent[] {285 const parsedEvents: IEvent[] = [];286287 records.result.events.forEach((record) => {288 const {event, phase} = record;289 const types = (event as any).typeDef;290291 const eventData: IEvent = {292 section: event.section.toString(),293 method: event.method.toString(),294 index: this.extractIndex(event.index),295 data: [],296 phase: phase.toJSON(),297 };298299 event.data.forEach((val: any, index: number) => {300 eventData.data.push(this.extractData(val, types[index]));301 });302303 parsedEvents.push(eventData);304 });305306 return parsedEvents;307 }308}309310class ChainHelperBase {311 transactionStatus = UniqueUtil.transactionStatus;312 chainLogType = UniqueUtil.chainLogType;313 util: typeof UniqueUtil;314 eventHelper: typeof UniqueEventHelper;315 logger: ILogger;316 api: ApiPromise | null;317 forcedNetwork: TUniqueNetworks | null;318 network: TUniqueNetworks | null;319 chainLog: IUniqueHelperLog[];320321 constructor(logger?: ILogger) {322 this.util = UniqueUtil;323 this.eventHelper = UniqueEventHelper;324 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();325 this.logger = logger;326 this.api = null;327 this.forcedNetwork = null;328 this.network = null;329 this.chainLog = [];330 }331332 clearChainLog(): void {333 this.chainLog = [];334 }335336 forceNetwork(value: TUniqueNetworks): void {337 this.forcedNetwork = value;338 }339340 async connect(wsEndpoint: string, listeners?: IApiListeners) {341 if (this.api !== null) throw Error('Already connected');342 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);343 this.api = api;344 this.network = network;345 }346347 async disconnect() {348 if (this.api === null) return;349 await this.api.disconnect();350 this.api = null;351 this.network = null;352 }353354 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {355 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;356 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;357 return 'opal';358 }359360 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {361 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});362 await api.isReady;363364 const network = await this.detectNetwork(api);365366 await api.disconnect();367368 return network;369 }370371 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{372 api: ApiPromise;373 network: TUniqueNetworks;374 }> {375 if(typeof network === 'undefined' || network === null) network = 'opal';376 const supportedRPC = {377 opal: {378 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,379 },380 quartz: {381 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,382 },383 unique: {384 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,385 },386 };387 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);388 const rpc = supportedRPC[network];389390 391 392393 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});394395 await api.isReadyOrError;396397 if (typeof listeners === 'undefined') listeners = {};398 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {399 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;400 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);401 }402403 return {api, network};404 }405406 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {407 const {events, status} = data;408 if (status.isReady) {409 return this.transactionStatus.NOT_READY;410 }411 if (status.isBroadcast) {412 return this.transactionStatus.NOT_READY;413 }414 if (status.isInBlock || status.isFinalized) {415 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');416 if (errors.length > 0) {417 return this.transactionStatus.FAIL;418 }419 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {420 return this.transactionStatus.SUCCESS;421 }422 }423424 return this.transactionStatus.FAIL;425 }426427 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {428 const sign = (callback: any) => {429 if(options !== null) return transaction.signAndSend(sender, options, callback);430 return transaction.signAndSend(sender, callback);431 };432 433 return new Promise(async (resolve, reject) => {434 try {435 const unsub = await sign((result: any) => {436 const status = this.getTransactionStatus(result);437438 if (status === this.transactionStatus.SUCCESS) {439 this.logger.log(`${label} successful`);440 unsub();441 resolve({result, status});442 } else if (status === this.transactionStatus.FAIL) {443 let moduleError = null;444445 if (result.hasOwnProperty('dispatchError')) {446 const dispatchError = result['dispatchError'];447448 if (dispatchError) {449 if (dispatchError.isModule) {450 const modErr = dispatchError.asModule;451 const errorMeta = dispatchError.registry.findMetaError(modErr);452453 moduleError = `${errorMeta.section}.${errorMeta.name}`;454 } else {455 moduleError = dispatchError.toHuman();456 }457 } else {458 this.logger.log(result, this.logger.level.ERROR);459 }460 }461462 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);463 unsub();464 reject({status, moduleError, result});465 }466 });467 } catch (e) {468 this.logger.log(e, this.logger.level.ERROR);469 reject(e);470 }471 });472 }473474 constructApiCall(apiCall: string, params: any[]) {475 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);476 let call = this.api as any;477 for(const part of apiCall.slice(4).split('.')) {478 call = call[part];479 }480 return call(...params);481 }482483 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {484 if(this.api === null) throw Error('API not initialized');485 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);486487 const startTime = (new Date()).getTime();488 let result: ITransactionResult;489 let events: IEvent[] = [];490 try {491 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;492 events = this.eventHelper.extractEvents(result);493 }494 catch(e) {495 if(!(e as object).hasOwnProperty('status')) throw e;496 result = e as ITransactionResult;497 }498499 const endTime = (new Date()).getTime();500501 const log = {502 executedAt: endTime,503 executionTime: endTime - startTime,504 type: this.chainLogType.EXTRINSIC,505 status: result.status,506 call: extrinsic,507 signer: this.getSignerAddress(sender),508 params,509 } as IUniqueHelperLog;510511 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;512 if(events.length > 0) log.events = events;513514 this.chainLog.push(log);515516 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);517 return result;518 }519520 async callRpc(rpc: string, params?: any[]) {521 if(typeof params === 'undefined') params = [];522 if(this.api === null) throw Error('API not initialized');523 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);524525 const startTime = (new Date()).getTime();526 let result;527 let error = null;528 const log = {529 type: this.chainLogType.RPC,530 call: rpc,531 params,532 } as IUniqueHelperLog;533534 try {535 result = await this.constructApiCall(rpc, params);536 }537 catch(e) {538 error = e;539 }540541 const endTime = (new Date()).getTime();542543 log.executedAt = endTime;544 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';545 log.executionTime = endTime - startTime;546547 this.chainLog.push(log);548549 if(error !== null) throw error;550551 return result;552 }553554 getSignerAddress(signer: IKeyringPair | string): string {555 if(typeof signer === 'string') return signer;556 return signer.address;557 }558559 fetchAllPalletNames(): string[] {560 if(this.api === null) throw Error('API not initialized');561 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());562 }563564 fetchMissingPalletNames(requiredPallets: string[]): string[] {565 const palletNames = this.fetchAllPalletNames();566 return requiredPallets.filter(p => !palletNames.includes(p));567 }568}569570571class HelperGroup {572 helper: UniqueHelper;573574 constructor(uniqueHelper: UniqueHelper) {575 this.helper = uniqueHelper;576 }577}578579580class CollectionGroup extends HelperGroup {581 582583584585586587588589590 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {591 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();592 }593594 595596597598599 async getTotalCount(): Promise<number> {600 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();601 }602603 604605606607608609610611612 async getData(collectionId: number): Promise<{613 id: number;614 name: string;615 description: string;616 tokensCount: number;617 admins: CrossAccountId[];618 normalizedOwner: TSubstrateAccount;619 raw: any620 } | null> {621 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);622 const humanCollection = collection.toHuman(), collectionData = {623 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],624 raw: humanCollection,625 } as any, jsonCollection = collection.toJSON();626 if (humanCollection === null) return null;627 collectionData.raw.limits = jsonCollection.limits;628 collectionData.raw.permissions = jsonCollection.permissions;629 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);630 for (const key of ['name', 'description']) {631 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);632 }633634 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))635 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)636 : 0;637 collectionData.admins = await this.getAdmins(collectionId);638639 return collectionData;640 }641642 643644645646647648649650 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {651 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();652653 return normalize654 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())655 : admins;656 }657658 659660661662663664665 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {666 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();667 return normalize668 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())669 : allowListed;670 }671672 673674675676677678679 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {680 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();681 }682683 684685686687688689690691 async burn(signer: TSigner, collectionId: number): Promise<boolean> {692 const result = await this.helper.executeExtrinsic(693 signer,694 'api.tx.unique.destroyCollection', [collectionId],695 true,696 );697698 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');699 }700701 702703704705706707708709710 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {711 const result = await this.helper.executeExtrinsic(712 signer,713 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],714 true,715 );716717 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');718 }719720 721722723724725726727728 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {729 const result = await this.helper.executeExtrinsic(730 signer,731 'api.tx.unique.confirmSponsorship', [collectionId],732 true,733 );734735 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');736 }737738 739740741742743744745746 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {747 const result = await this.helper.executeExtrinsic(748 signer,749 'api.tx.unique.removeCollectionSponsor', [collectionId],750 true,751 );752753 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');754 }755756 757758759760761762763764765766767768769770771772773 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {774 const result = await this.helper.executeExtrinsic(775 signer,776 'api.tx.unique.setCollectionLimits', [collectionId, limits],777 true,778 );779780 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');781 }782783 784785786787788789790791792 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {793 const result = await this.helper.executeExtrinsic(794 signer,795 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],796 true,797 );798799 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');800 }801802 803804805806807808809810811 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {812 const result = await this.helper.executeExtrinsic(813 signer,814 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],815 true,816 );817818 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');819 }820821 822823824825826827828829830 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');838 }839840 841842843844845846847848 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {849 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();850 }851852 853854855856857858859 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {860 const result = await this.helper.executeExtrinsic(861 signer,862 'api.tx.unique.addToAllowList', [collectionId, addressObj],863 true,864 );865866 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');867 }868869 870871872873874875876877 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {878 const result = await this.helper.executeExtrinsic(879 signer,880 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],881 true,882 );883884 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');885 }886887 888889890891892893894895896 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {897 const result = await this.helper.executeExtrinsic(898 signer,899 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],900 true,901 );902903 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');904 }905906 907908909910911912913914915 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {916 return await this.setPermissions(signer, collectionId, {nesting: permissions});917 }918919 920921922923924925926927 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {928 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});929 }930931 932933934935936937938939940 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {941 const result = await this.helper.executeExtrinsic(942 signer,943 'api.tx.unique.setCollectionProperties', [collectionId, properties],944 true,945 );946947 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');948 }949950 951952953954955956957958 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {959 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();960 }961962 963964965966967968969970971 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {972 const result = await this.helper.executeExtrinsic(973 signer,974 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],975 true,976 );977978 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');979 }980981 982983984985986987988989990991992 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {993 const result = await this.helper.executeExtrinsic(994 signer,995 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],996 true, 997 );998999 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1000 }10011002 1003100410051006100710081009101010111012101310141015 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1016 const result = await this.helper.executeExtrinsic(1017 signer,1018 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1019 true, 1020 );1021 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1022 }10231024 10251026102710281029103010311032103310341035 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1036 const burnResult = await this.helper.executeExtrinsic(1037 signer,1038 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1039 true, 1040 );1041 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1042 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1043 return burnedTokens.success;1044 }10451046 10471048104910501051105210531054105510561057 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1058 const burnResult = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1061 true, 1062 );1063 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1064 return burnedTokens.success && burnedTokens.tokens.length > 0;1065 }10661067 1068106910701071107210731074107510761077 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1078 const approveResult = await this.helper.executeExtrinsic(1079 signer,1080 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1081 true, 1082 );10831084 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1085 }10861087 1088108910901091109210931094109510961097 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1098 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1099 }11001101 1102110311041105110611071108 async getLastTokenId(collectionId: number): Promise<number> {1109 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1110 }11111112 11131114111511161117111811191120 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1121 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1122 }1123}11241125class NFTnRFT extends CollectionGroup {1126 11271128112911301131113211331134 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1135 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1136 }11371138 1139114011411142114311441145114611471148 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1149 properties: IProperty[];1150 owner: CrossAccountId;1151 normalizedOwner: CrossAccountId;1152 }| null> {1153 let tokenData;1154 if(typeof blockHashAt === 'undefined') {1155 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1156 }1157 else {1158 if(propertyKeys.length == 0) {1159 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1160 if(!collection) return null;1161 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1162 }1163 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1164 }1165 tokenData = tokenData.toHuman();1166 if (tokenData === null || tokenData.owner === null) return null;1167 const owner = {} as any;1168 for (const key of Object.keys(tokenData.owner)) {1169 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1170 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1171 : tokenData.owner[key];1172 }1173 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1174 return tokenData;1175 }11761177 11781179118011811182118311841185118611871188 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1189 const result = await this.helper.executeExtrinsic(1190 signer,1191 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1192 true,1193 );11941195 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1196 }11971198 11991200120112021203120412051206 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1207 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1208 }12091210 1211121212131214121512161217121812191220 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1221 const result = await this.helper.executeExtrinsic(1222 signer,1223 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1224 true,1225 );12261227 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1228 }12291230 123112321233123412351236123712381239 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1240 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1241 }12421243 124412451246124712481249125012511252 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1253 const result = await this.helper.executeExtrinsic(1254 signer,1255 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1256 true,1257 );12581259 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1260 }12611262 126312641265126612671268126912701271 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1272 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1273 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1274 for (const key of ['name', 'description', 'tokenPrefix']) {1275 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);1276 }1277 const creationResult = await this.helper.executeExtrinsic(1278 signer,1279 'api.tx.unique.createCollectionEx', [collectionOptions],1280 true, 1281 );1282 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1283 }12841285 getCollectionObject(_collectionId: number): any {1286 return null;1287 }12881289 getTokenObject(_collectionId: number, _tokenId: number): any {1290 return null;1291 }1292}129312941295class NFTGroup extends NFTnRFT {1296 129712981299130013011302 getCollectionObject(collectionId: number): UniqueNFTCollection {1303 return new UniqueNFTCollection(collectionId, this.helper);1304 }13051306 1307130813091310131113121313 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1314 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1315 }13161317 13181319132013211322132313241325 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1326 let owner;1327 if (typeof blockHashAt === 'undefined') {1328 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1329 } else {1330 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1331 }1332 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1333 }13341335 1336133713381339134013411342 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1343 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1344 }13451346 1347134813491350135113521353135413551356 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1357 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1358 }13591360 136113621363136413651366136713681369137013711372 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1373 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1374 }13751376 13771378137913801381138213831384 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1385 let owner;1386 if (typeof blockHashAt === 'undefined') {1387 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1388 } else {1389 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1390 }13911392 if (owner === null) return null;13931394 return owner.toHuman();1395 }13961397 13981399140014011402140314041405 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1406 let children;1407 if(typeof blockHashAt === 'undefined') {1408 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1409 } else {1410 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1411 }14121413 return children.toJSON().map((x: any) => {1414 return {collectionId: x.collection, tokenId: x.token};1415 });1416 }14171418 14191420142114221423142414251426 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1427 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1428 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1429 if(!result) {1430 throw Error('Unable to nest token!');1431 }1432 return result;1433 }14341435 143614371438143914401441144214431444 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1445 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1446 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1447 if(!result) {1448 throw Error('Unable to unnest token!');1449 }1450 return result;1451 }14521453 145414551456145714581459146014611462146314641465 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1466 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1467 }14681469 147014711472147314741475 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1476 const creationResult = await this.helper.executeExtrinsic(1477 signer,1478 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1479 nft: {1480 properties: data.properties,1481 },1482 }],1483 true,1484 );1485 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1486 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1487 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1488 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1489 }14901491 149214931494149514961497149814991500150115021503150415051506 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1507 const creationResult = await this.helper.executeExtrinsic(1508 signer,1509 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1510 true,1511 );1512 const collection = this.getCollectionObject(collectionId);1513 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1514 }15151516 151715181519152015211522152315241525152615271528152915301531153215331534 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1535 const rawTokens = [];1536 for (const token of tokens) {1537 const raw = {NFT: {properties: token.properties}};1538 rawTokens.push(raw);1539 }1540 const creationResult = await this.helper.executeExtrinsic(1541 signer,1542 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1543 true,1544 );1545 const collection = this.getCollectionObject(collectionId);1546 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1547 }15481549 1550155115521553155415551556155715581559 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1560 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1561 }1562}156315641565class RFTGroup extends NFTnRFT {1566 156715681569157015711572 getCollectionObject(collectionId: number): UniqueRFTCollection {1573 return new UniqueRFTCollection(collectionId, this.helper);1574 }15751576 1577157815791580158115821583 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1584 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1585 }15861587 1588158915901591159215931594 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1595 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1596 }15971598 15991600160116021603160416051606 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1607 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1608 }16091610 1611161216131614161516161617161816191620 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1621 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1622 }16231624 16251626162716281629163016311632163316341635 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1636 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1637 }16381639 164016411642164316441645164616471648164916501651 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1652 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1653 }16541655 1656165716581659166016611662 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1663 const creationResult = await this.helper.executeExtrinsic(1664 signer,1665 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1666 refungible: {1667 pieces: data.pieces,1668 properties: data.properties,1669 },1670 }],1671 true,1672 );1673 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1674 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1675 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1676 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1677 }16781679 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1680 throw Error('Not implemented');1681 const creationResult = await this.helper.executeExtrinsic(1682 signer,1683 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1684 true, 1685 );1686 const collection = this.getCollectionObject(collectionId);1687 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1688 }16891690 169116921693169416951696169716981699 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1700 const rawTokens = [];1701 for (const token of tokens) {1702 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1703 rawTokens.push(raw);1704 }1705 const creationResult = await this.helper.executeExtrinsic(1706 signer,1707 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1708 true,1709 );1710 const collection = this.getCollectionObject(collectionId);1711 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1712 }17131714 171517161717171817191720172117221723 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1724 return await super.burnToken(signer, collectionId, tokenId, amount);1725 }17261727 1728172917301731173217331734173517361737 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1738 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1739 }17401741 17421743174417451746174717481749175017511752 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1753 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1754 }17551756 1757175817591760176117621763 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1764 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1765 }17661767 176817691770177117721773177417751776 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1777 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1778 const repartitionResult = await this.helper.executeExtrinsic(1779 signer,1780 'api.tx.unique.repartition', [collectionId, tokenId, amount],1781 true,1782 );1783 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1784 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1785 }1786}178717881789class FTGroup extends CollectionGroup {1790 179117921793179417951796 getCollectionObject(collectionId: number): UniqueFTCollection {1797 return new UniqueFTCollection(collectionId, this.helper);1798 }17991800 1801180218031804180518061807180818091810181118121813 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1814 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1815 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1816 collectionOptions.mode = {fungible: decimalPoints};1817 for (const key of ['name', 'description', 'tokenPrefix']) {1818 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);1819 }1820 const creationResult = await this.helper.executeExtrinsic(1821 signer,1822 'api.tx.unique.createCollectionEx', [collectionOptions],1823 true,1824 );1825 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1826 }18271828 182918301831183218331834183518361837 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1838 const creationResult = await this.helper.executeExtrinsic(1839 signer,1840 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1841 fungible: {1842 value: amount,1843 },1844 }],1845 true, 1846 );1847 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1848 }18491850 18511852185318541855185618571858 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1859 const rawTokens = [];1860 for (const token of tokens) {1861 const raw = {Fungible: {Value: token.value}};1862 rawTokens.push(raw);1863 }1864 const creationResult = await this.helper.executeExtrinsic(1865 signer,1866 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1867 true,1868 );1869 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1870 }18711872 187318741875187618771878 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1879 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1880 }18811882 1883188418851886188718881889 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1890 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1891 }18921893 189418951896189718981899190019011902 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1903 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1904 }19051906 1907190819091910191119121913191419151916 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1917 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1918 }19191920 19211922192319241925192619271928 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1929 return await super.burnToken(signer, collectionId, 0, amount);1930 }19311932 193319341935193619371938193919401941 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1942 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1943 }19441945 19461947194819491950 async getTotalPieces(collectionId: number): Promise<bigint> {1951 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1952 }19531954 1955195619571958195919601961196219631964 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1965 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1966 }19671968 1969197019711972197319741975 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1976 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1977 }1978}197919801981class ChainGroup extends HelperGroup {1982 19831984198519861987 getChainProperties(): IChainProperties {1988 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1989 return {1990 ss58Format: properties.ss58Format.toJSON(),1991 tokenDecimals: properties.tokenDecimals.toJSON(),1992 tokenSymbol: properties.tokenSymbol.toJSON(),1993 };1994 }19951996 19971998199920002001 async getLatestBlockNumber(): Promise<number> {2002 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2003 }20042005 200620072008200920102011 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2012 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2013 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2014 return blockHash;2015 }20162017 2018 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2019 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2020 if (!blockHash) return null;2021 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2022 }20232024 202520262027202820292030 async getNonce(address: TSubstrateAccount): Promise<number> {2031 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2032 }2033}203420352036class BalanceGroup extends HelperGroup {2037 getCollectionCreationPrice(): bigint {2038 return 2n * this.helper.balance.getOneTokenNominal();2039 }2040 20412042204320442045 getOneTokenNominal(): bigint {2046 const chainProperties = this.helper.chain.getChainProperties();2047 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2048 }20492050 205120522053205420552056 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2057 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2058 }20592060 20612062206320642065 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2066 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2067 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2068 }20692070 207120722073207420752076 async getEthereum(address: TEthereumAccount): Promise<bigint> {2077 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2078 }20792080 20812082208320842085208620872088 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2089 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20902091 let transfer = {from: null, to: null, amount: 0n} as any;2092 result.result.events.forEach(({event: {data, method, section}}) => {2093 if ((section === 'balances') && (method === 'Transfer')) {2094 transfer = {2095 from: this.helper.address.normalizeSubstrate(data[0]),2096 to: this.helper.address.normalizeSubstrate(data[1]),2097 amount: BigInt(data[2]),2098 };2099 }2100 });2101 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2102 && this.helper.address.normalizeSubstrate(address) === transfer.to 2103 && BigInt(amount) === transfer.amount;2104 return isSuccess;2105 }2106}210721082109class AddressGroup extends HelperGroup {2110 2111211221132114211521162117 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2118 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2119 }21202121 212221232124212521262127 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2128 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2129 }21302131 2132213321342135213621372138 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2139 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2140 }21412142 214321442145214621472148 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2149 return CrossAccountId.translateSubToEth(subAddress);2150 }2151}21522153class StakingGroup extends HelperGroup {2154 2155215621572158215921602161 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2162 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2163 const stakeResult = await this.helper.executeExtrinsic(2164 signer, 'api.tx.appPromotion.stake',2165 [amountToStake], true,2166 );2167 2168 return true;2169 }21702171 2172217321742175217621772178 async unstake(signer: TSigner, label?: string): Promise<number> {2179 if(typeof label === 'undefined') label = `${signer.address}`;2180 const unstakeResult = await this.helper.executeExtrinsic(2181 signer, 'api.tx.appPromotion.unstake',2182 [], true,2183 );2184 2185 return 1;2186 }21872188 21892190219121922193 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2194 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2195 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2196 }21972198 21992200220122022203 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2204 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2205 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2206 return { 2207 block: block.toBigInt(),2208 amount: amount.toBigInt(),2209 };2210 });2211 }22122213 22142215221622172218 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2219 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2220 }22212222 22232224222522262227 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2228 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2229 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2230 return {2231 block: block.toBigInt(),2232 amount: amount.toBigInt(),2233 };2234 });2235 return result;2236 }2237}22382239export class UniqueHelper extends ChainHelperBase {2240 chain: ChainGroup;2241 balance: BalanceGroup;2242 address: AddressGroup;2243 collection: CollectionGroup;2244 nft: NFTGroup;2245 rft: RFTGroup;2246 ft: FTGroup;2247 staking: StakingGroup;22482249 constructor(logger?: ILogger) {2250 super(logger);2251 this.chain = new ChainGroup(this);2252 this.balance = new BalanceGroup(this);2253 this.address = new AddressGroup(this);2254 this.collection = new CollectionGroup(this);2255 this.nft = new NFTGroup(this);2256 this.rft = new RFTGroup(this);2257 this.ft = new FTGroup(this);2258 this.staking = new StakingGroup(this);2259 }2260}226122622263export class UniqueBaseCollection {2264 helper: UniqueHelper;2265 collectionId: number;22662267 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2268 this.collectionId = collectionId;2269 this.helper = uniqueHelper;2270 }22712272 async getData() {2273 return await this.helper.collection.getData(this.collectionId);2274 }22752276 async getLastTokenId() {2277 return await this.helper.collection.getLastTokenId(this.collectionId);2278 }22792280 async isTokenExists(tokenId: number) {2281 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2282 }22832284 async getAdmins() {2285 return await this.helper.collection.getAdmins(this.collectionId);2286 }22872288 async getAllowList() {2289 return await this.helper.collection.getAllowList(this.collectionId);2290 }22912292 async getEffectiveLimits() {2293 return await this.helper.collection.getEffectiveLimits(this.collectionId);2294 }22952296 async getProperties(propertyKeys?: string[] | null) {2297 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2298 }22992300 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2301 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2302 }23032304 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2305 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2306 }23072308 async confirmSponsorship(signer: TSigner) {2309 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2310 }23112312 async removeSponsor(signer: TSigner) {2313 return await this.helper.collection.removeSponsor(signer, this.collectionId);2314 }23152316 async setLimits(signer: TSigner, limits: ICollectionLimits) {2317 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2318 }23192320 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2321 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2322 }23232324 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2325 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2326 }23272328 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2329 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2330 }23312332 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2333 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2334 }23352336 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2337 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2338 }23392340 async setProperties(signer: TSigner, properties: IProperty[]) {2341 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2342 }23432344 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2345 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2346 }23472348 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2349 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2350 }23512352 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2353 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2354 }23552356 async disableNesting(signer: TSigner) {2357 return await this.helper.collection.disableNesting(signer, this.collectionId);2358 }23592360 async burn(signer: TSigner) {2361 return await this.helper.collection.burn(signer, this.collectionId);2362 }2363}236423652366export class UniqueNFTCollection extends UniqueBaseCollection {2367 getTokenObject(tokenId: number) {2368 return new UniqueNFToken(tokenId, this);2369 }23702371 async getTokensByAddress(addressObj: ICrossAccountId) {2372 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2373 }23742375 async getToken(tokenId: number, blockHashAt?: string) {2376 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2377 }23782379 async getTokenOwner(tokenId: number, blockHashAt?: string) {2380 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2381 }23822383 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2384 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2385 }23862387 async getTokenChildren(tokenId: number, blockHashAt?: string) {2388 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2389 }23902391 async getPropertyPermissions(propertyKeys: string[] | null = null) {2392 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2393 }23942395 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2396 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2397 }23982399 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2400 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2401 }24022403 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2404 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2405 }24062407 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2408 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2409 }24102411 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2412 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2413 }24142415 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2416 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2417 }24182419 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2420 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2421 }24222423 async burnToken(signer: TSigner, tokenId: number) {2424 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2425 }24262427 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2428 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2429 }24302431 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2432 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2433 }24342435 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2436 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2437 }24382439 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2440 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2441 }24422443 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2444 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2445 }24462447 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2448 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2449 }2450}245124522453export class UniqueRFTCollection extends UniqueBaseCollection {2454 getTokenObject(tokenId: number) {2455 return new UniqueRFToken(tokenId, this);2456 }24572458 async getToken(tokenId: number, blockHashAt?: string) {2459 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2460 }24612462 async getTokensByAddress(addressObj: ICrossAccountId) {2463 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2464 }24652466 async getTop10TokenOwners(tokenId: number) {2467 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2468 }24692470 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2471 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2472 }24732474 async getTokenTotalPieces(tokenId: number) {2475 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2476 }24772478 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2479 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2480 }24812482 async getPropertyPermissions(propertyKeys: string[] | null = null) {2483 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2484 }24852486 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2487 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2488 }24892490 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2491 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2492 }24932494 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2495 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2496 }24972498 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2499 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2500 }25012502 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2503 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2504 }25052506 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2507 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2508 }25092510 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2511 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2512 }25132514 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2515 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2516 }25172518 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2519 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2520 }25212522 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2523 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2524 }25252526 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2527 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2528 }25292530 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2531 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2532 }2533}253425352536export class UniqueFTCollection extends UniqueBaseCollection {2537 async getBalance(addressObj: ICrossAccountId) {2538 return await this.helper.ft.getBalance(this.collectionId, addressObj);2539 }25402541 async getTotalPieces() {2542 return await this.helper.ft.getTotalPieces(this.collectionId);2543 }25442545 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2546 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2547 }25482549 async getTop10Owners() {2550 return await this.helper.ft.getTop10Owners(this.collectionId);2551 }25522553 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2554 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2555 }25562557 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2558 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2559 }25602561 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2562 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2563 }25642565 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2566 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2567 }25682569 async burnTokens(signer: TSigner, amount=1n) {2570 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2571 }25722573 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2574 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2575 }25762577 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2578 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2579 }2580}258125822583export class UniqueBaseToken {2584 collection: UniqueNFTCollection | UniqueRFTCollection;2585 collectionId: number;2586 tokenId: number;25872588 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2589 this.collection = collection;2590 this.collectionId = collection.collectionId;2591 this.tokenId = tokenId;2592 }25932594 async getNextSponsored(addressObj: ICrossAccountId) {2595 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2596 }25972598 async getProperties(propertyKeys?: string[] | null) {2599 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2600 }26012602 async setProperties(signer: TSigner, properties: IProperty[]) {2603 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2604 }26052606 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2607 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2608 }26092610 nestingAccount() {2611 return this.collection.helper.util.getTokenAccount(this);2612 }2613}261426152616export class UniqueNFToken extends UniqueBaseToken {2617 collection: UniqueNFTCollection;26182619 constructor(tokenId: number, collection: UniqueNFTCollection) {2620 super(tokenId, collection);2621 this.collection = collection;2622 }26232624 async getData(blockHashAt?: string) {2625 return await this.collection.getToken(this.tokenId, blockHashAt);2626 }26272628 async getOwner(blockHashAt?: string) {2629 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2630 }26312632 async getTopmostOwner(blockHashAt?: string) {2633 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2634 }26352636 async getChildren(blockHashAt?: string) {2637 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2638 }26392640 async nest(signer: TSigner, toTokenObj: IToken) {2641 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2642 }26432644 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2645 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2646 }26472648 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2649 return await this.collection.transferToken(signer, this.tokenId, addressObj);2650 }26512652 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2653 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2654 }26552656 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2657 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2658 }26592660 async isApproved(toAddressObj: ICrossAccountId) {2661 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2662 }26632664 async burn(signer: TSigner) {2665 return await this.collection.burnToken(signer, this.tokenId);2666 }26672668 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2669 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2670 }2671}26722673export class UniqueRFToken extends UniqueBaseToken {2674 collection: UniqueRFTCollection;26752676 constructor(tokenId: number, collection: UniqueRFTCollection) {2677 super(tokenId, collection);2678 this.collection = collection;2679 }26802681 async getData(blockHashAt?: string) {2682 return await this.collection.getToken(this.tokenId, blockHashAt);2683 }26842685 async getTop10Owners() {2686 return await this.collection.getTop10TokenOwners(this.tokenId);2687 }26882689 async getBalance(addressObj: ICrossAccountId) {2690 return await this.collection.getTokenBalance(this.tokenId, addressObj);2691 }26922693 async getTotalPieces() {2694 return await this.collection.getTokenTotalPieces(this.tokenId);2695 }26962697 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2698 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2699 }27002701 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2702 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2703 }27042705 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2706 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2707 }27082709 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2710 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2711 }27122713 async repartition(signer: TSigner, amount: bigint) {2714 return await this.collection.repartitionToken(signer, this.tokenId, amount);2715 }27162717 async burn(signer: TSigner, amount=1n) {2718 return await this.collection.burnToken(signer, this.tokenId, amount);2719 }27202721 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2722 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2723 }2724}