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, ISchedulerOptions, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';13import {RuntimeDispatchInfo} from '@polkadot/types/interfaces';1415export class CrossAccountId implements ICrossAccountId {16 Substrate?: TSubstrateAccount;17 Ethereum?: TEthereumAccount;1819 constructor(account: ICrossAccountId) {20 if (account.Substrate) this.Substrate = account.Substrate;21 if (account.Ethereum) this.Ethereum = account.Ethereum;22 }2324 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {25 switch (domain) {26 case 'Substrate': return new CrossAccountId({Substrate: account.address});27 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();28 }29 }3031 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {32 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});33 }3435 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {36 return encodeAddress(decodeAddress(address), ss58Format);37 }3839 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {40 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});41 }42 43 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {44 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);45 return this;46 }4748 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {49 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));50 }5152 toEthereum(): CrossAccountId {53 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});54 return this;55 }5657 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {58 return evmToAddress(address, ss58Format);59 }6061 toSubstrate(ss58Format?: number): CrossAccountId {62 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});63 return this;64 }65 66 toLowerCase(): CrossAccountId {67 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();68 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();69 return this;70 }71}7273const nesting = {74 toChecksumAddress(address: string): string {75 if (typeof address === 'undefined') return '';7677 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7879 address = address.toLowerCase().replace(/^0x/i,'');80 const addressHash = keccakAsHex(address).replace(/^0x/i,'');81 const checksumAddress = ['0x'];8283 for (let i = 0; i < address.length; i++) {84 85 if (parseInt(addressHash[i], 16) > 7) {86 checksumAddress.push(address[i].toUpperCase());87 } else {88 checksumAddress.push(address[i]);89 }90 }91 return checksumAddress.join('');92 },93 tokenIdToAddress(collectionId: number, tokenId: number) {94 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);95 },96};9798class UniqueUtil {99 static transactionStatus = {100 NOT_READY: 'NotReady',101 FAIL: 'Fail',102 SUCCESS: 'Success',103 };104105 static chainLogType = {106 EXTRINSIC: 'extrinsic',107 RPC: 'rpc',108 };109110 static getTokenAccount(token: IToken): CrossAccountId {111 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});112 }113114 static getTokenAddress(token: IToken): string {115 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);116 }117118 static getDefaultLogger(): ILogger {119 return {120 log(msg: any, level = 'INFO') {121 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));122 },123 level: {124 ERROR: 'ERROR',125 WARNING: 'WARNING',126 INFO: 'INFO',127 },128 };129 }130131 static vec2str(arr: string[] | number[]) {132 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');133 }134135 static str2vec(string: string) {136 if (typeof string !== 'string') return string;137 return Array.from(string).map(x => x.charCodeAt(0));138 }139140 static fromSeed(seed: string, ss58Format = 42) {141 const keyring = new Keyring({type: 'sr25519', ss58Format});142 return keyring.addFromUri(seed);143 }144145 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {146 if (creationResult.status !== this.transactionStatus.SUCCESS) {147 throw Error('Unable to create collection!');148 }149150 let collectionId = null;151 creationResult.result.events.forEach(({event: {data, method, section}}) => {152 if ((section === 'common') && (method === 'CollectionCreated')) {153 collectionId = parseInt(data[0].toString(), 10);154 }155 });156157 if (collectionId === null) {158 throw Error('No CollectionCreated event was found!');159 }160161 return collectionId;162 }163164 static extractTokensFromCreationResult(creationResult: ITransactionResult): {165 success: boolean, 166 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],167 } {168 if (creationResult.status !== this.transactionStatus.SUCCESS) {169 throw Error('Unable to create tokens!');170 }171 let success = false;172 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];173 creationResult.result.events.forEach(({event: {data, method, section}}) => {174 if (method === 'ExtrinsicSuccess') {175 success = true;176 } else if ((section === 'common') && (method === 'ItemCreated')) {177 tokens.push({178 collectionId: parseInt(data[0].toString(), 10),179 tokenId: parseInt(data[1].toString(), 10),180 owner: data[2].toHuman(),181 amount: data[3].toBigInt(),182 });183 }184 });185 return {success, tokens};186 }187188 static extractTokensFromBurnResult(burnResult: ITransactionResult): {189 success: boolean, 190 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],191 } {192 if (burnResult.status !== this.transactionStatus.SUCCESS) {193 throw Error('Unable to burn tokens!');194 }195 let success = false;196 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];197 burnResult.result.events.forEach(({event: {data, method, section}}) => {198 if (method === 'ExtrinsicSuccess') {199 success = true;200 } else if ((section === 'common') && (method === 'ItemDestroyed')) {201 tokens.push({202 collectionId: parseInt(data[0].toString(), 10),203 tokenId: parseInt(data[1].toString(), 10),204 owner: data[2].toHuman(),205 amount: data[3].toBigInt(),206 });207 }208 });209 return {success, tokens};210 }211212 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {213 let eventId = null;214 events.forEach(({event: {data, method, section}}) => {215 if ((section === expectedSection) && (method === expectedMethod)) {216 eventId = parseInt(data[0].toString(), 10);217 }218 });219220 if (eventId === null) {221 throw Error(`No ${expectedMethod} event was found!`);222 }223 return eventId === collectionId;224 }225226 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {227 const normalizeAddress = (address: string | ICrossAccountId) => {228 if(typeof address === 'string') return address;229 const obj = {} as any;230 Object.keys(address).forEach(k => {231 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];232 });233 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);234 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();235 return address;236 };237 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;238 events.forEach(({event: {data, method, section}}) => {239 if ((section === 'common') && (method === 'Transfer')) {240 const hData = (data as any).toJSON();241 transfer = {242 collectionId: hData[0],243 tokenId: hData[1],244 from: normalizeAddress(hData[2]),245 to: normalizeAddress(hData[3]),246 amount: BigInt(hData[4]),247 };248 }249 });250 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);252 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);253 isSuccess = isSuccess && amount === transfer.amount;254 return isSuccess;255 }256}257258class UniqueEventHelper {259 private static extractIndex(index: any): [number, number] | string {260 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];261 return index.toJSON();262 }263264 private static extractSub(data: any, subTypes: any): {[key: string]: any} {265 let obj: any = {};266 let index = 0;267268 if (data.entries) {269 for(const [key, value] of data.entries()) {270 obj[key] = this.extractData(value, subTypes[index]);271 index++;272 }273 } else obj = data.toJSON();274275 return obj;276 }277 278 private static extractData(data: any, type: any): any {279 if(!type) return data.toHuman();280 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();281 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();282 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);283 return data.toHuman();284 }285286 public static extractEvents(records: ITransactionResult): IEvent[] {287 const parsedEvents: IEvent[] = [];288289 records.result.events.forEach((record) => {290 const {event, phase} = record;291 const types = (event as any).typeDef;292293 const eventData: IEvent = {294 section: event.section.toString(),295 method: event.method.toString(),296 index: this.extractIndex(event.index),297 data: [],298 phase: phase.toJSON(),299 };300301 event.data.forEach((val: any, index: number) => {302 eventData.data.push(this.extractData(val, types[index]));303 });304305 parsedEvents.push(eventData);306 });307308 return parsedEvents;309 }310}311312class ChainHelperBase {313 transactionStatus = UniqueUtil.transactionStatus;314 chainLogType = UniqueUtil.chainLogType;315 util: typeof UniqueUtil;316 eventHelper: typeof UniqueEventHelper;317 logger: ILogger;318 api: ApiPromise | null;319 forcedNetwork: TUniqueNetworks | null;320 network: TUniqueNetworks | null;321 chainLog: IUniqueHelperLog[];322 children: ChainHelperBase[];323324 constructor(logger?: ILogger) {325 this.util = UniqueUtil;326 this.eventHelper = UniqueEventHelper;327 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();328 this.logger = logger;329 this.api = null;330 this.forcedNetwork = null;331 this.network = null;332 this.chainLog = [];333 this.children = [];334 }335336 getApi(): ApiPromise {337 if(this.api === null) throw Error('API not initialized');338 return this.api;339 }340341 clearChainLog(): void {342 this.chainLog = [];343 }344345 forceNetwork(value: TUniqueNetworks): void {346 this.forcedNetwork = value;347 }348349 async connect(wsEndpoint: string, listeners?: IApiListeners) {350 if (this.api !== null) throw Error('Already connected');351 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);352 this.api = api;353 this.network = network;354 }355356 async disconnect() {357 for (const child of this.children) {358 child.clearApi();359 }360361 if (this.api === null) return;362 await this.api.disconnect();363 this.clearApi();364 }365366 clearApi() {367 this.api = null;368 this.network = null;369 }370371 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {372 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;373 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;374 return 'opal';375 }376377 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {378 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});379 await api.isReady;380381 const network = await this.detectNetwork(api);382383 await api.disconnect();384385 return network;386 }387388 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{389 api: ApiPromise;390 network: TUniqueNetworks;391 }> {392 if(typeof network === 'undefined' || network === null) network = 'opal';393 const supportedRPC = {394 opal: {395 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,396 },397 quartz: {398 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,399 },400 unique: {401 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,402 },403 };404 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);405 const rpc = supportedRPC[network];406407 408 409410 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});411412 await api.isReadyOrError;413414 if (typeof listeners === 'undefined') listeners = {};415 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {416 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;417 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);418 }419420 return {api, network};421 }422423 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {424 const {events, status} = data;425 if (status.isReady) {426 return this.transactionStatus.NOT_READY;427 }428 if (status.isBroadcast) {429 return this.transactionStatus.NOT_READY;430 }431 if (status.isInBlock || status.isFinalized) {432 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');433 if (errors.length > 0) {434 return this.transactionStatus.FAIL;435 }436 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {437 return this.transactionStatus.SUCCESS;438 }439 }440441 return this.transactionStatus.FAIL;442 }443444 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {445 const sign = (callback: any) => {446 if(options !== null) return transaction.signAndSend(sender, options, callback);447 return transaction.signAndSend(sender, callback);448 };449 450 return new Promise(async (resolve, reject) => {451 try {452 const unsub = await sign((result: any) => {453 const status = this.getTransactionStatus(result);454455 if (status === this.transactionStatus.SUCCESS) {456 this.logger.log(`${label} successful`);457 unsub();458 resolve({result, status});459 } else if (status === this.transactionStatus.FAIL) {460 let moduleError = null;461462 if (result.hasOwnProperty('dispatchError')) {463 const dispatchError = result['dispatchError'];464465 if (dispatchError) {466 if (dispatchError.isModule) {467 const modErr = dispatchError.asModule;468 const errorMeta = dispatchError.registry.findMetaError(modErr);469470 moduleError = `${errorMeta.section}.${errorMeta.name}`;471 } else {472 moduleError = dispatchError.toHuman();473 }474 } else {475 this.logger.log(result, this.logger.level.ERROR);476 }477 }478479 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);480 unsub();481 reject({status, moduleError, result});482 }483 });484 } catch (e) {485 this.logger.log(e, this.logger.level.ERROR);486 reject(e);487 }488 });489 }490491 constructApiCall(apiCall: string, params: any[]) {492 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);493 let call = this.getApi() as any;494 for(const part of apiCall.slice(4).split('.')) {495 call = call[part];496 }497 return call(...params);498 }499500 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {501 if(this.api === null) throw Error('API not initialized');502 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);503504 const startTime = (new Date()).getTime();505 let result: ITransactionResult;506 let events: IEvent[] = [];507 try {508 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;509 events = this.eventHelper.extractEvents(result);510 }511 catch(e) {512 if(!(e as object).hasOwnProperty('status')) throw e;513 result = e as ITransactionResult;514 }515516 const endTime = (new Date()).getTime();517518 const log = {519 executedAt: endTime,520 executionTime: endTime - startTime,521 type: this.chainLogType.EXTRINSIC,522 status: result.status,523 call: extrinsic,524 signer: this.getSignerAddress(sender),525 params,526 } as IUniqueHelperLog;527528 if(result.status !== this.transactionStatus.SUCCESS) {529 if (result.moduleError) log.moduleError = result.moduleError;530 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;531 }532 if(events.length > 0) log.events = events;533534 this.chainLog.push(log);535536 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {537 if (result.moduleError) throw Error(`${result.moduleError}`);538 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));539 }540 return result;541 }542543 async callRpc(rpc: string, params?: any[]) {544 if(typeof params === 'undefined') params = [];545 if(this.api === null) throw Error('API not initialized');546 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);547548 const startTime = (new Date()).getTime();549 let result;550 let error = null;551 const log = {552 type: this.chainLogType.RPC,553 call: rpc,554 params,555 } as IUniqueHelperLog;556557 try {558 result = await this.constructApiCall(rpc, params);559 }560 catch(e) {561 error = e;562 }563564 const endTime = (new Date()).getTime();565566 log.executedAt = endTime;567 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';568 log.executionTime = endTime - startTime;569570 this.chainLog.push(log);571572 if(error !== null) throw error;573574 return result;575 }576577 getSignerAddress(signer: IKeyringPair | string): string {578 if(typeof signer === 'string') return signer;579 return signer.address;580 }581582 fetchAllPalletNames(): string[] {583 if(this.api === null) throw Error('API not initialized');584 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());585 }586587 fetchMissingPalletNames(requiredPallets: string[]): string[] {588 const palletNames = this.fetchAllPalletNames();589 return requiredPallets.filter(p => !palletNames.includes(p));590 }591}592593594class HelperGroup {595 helper: UniqueHelper;596597 constructor(uniqueHelper: UniqueHelper) {598 this.helper = uniqueHelper;599 }600}601602603class CollectionGroup extends HelperGroup {604 605606607608609610611612613 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {614 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();615 }616617 618619620621622 async getTotalCount(): Promise<number> {623 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();624 }625626 627628629630631632633634635 async getData(collectionId: number): Promise<{636 id: number;637 name: string;638 description: string;639 tokensCount: number;640 admins: CrossAccountId[];641 normalizedOwner: TSubstrateAccount;642 raw: any643 } | null> {644 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);645 const humanCollection = collection.toHuman(), collectionData = {646 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],647 raw: humanCollection,648 } as any, jsonCollection = collection.toJSON();649 if (humanCollection === null) return null;650 collectionData.raw.limits = jsonCollection.limits;651 collectionData.raw.permissions = jsonCollection.permissions;652 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);653 for (const key of ['name', 'description']) {654 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);655 }656657 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))658 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)659 : 0;660 collectionData.admins = await this.getAdmins(collectionId);661662 return collectionData;663 }664665 666667668669670671672673 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {674 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();675676 return normalize677 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())678 : admins;679 }680681 682683684685686687688 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {689 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();690 return normalize691 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())692 : allowListed;693 }694695 696697698699700701702 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {703 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();704 }705706 707708709710711712713714 async burn(signer: TSigner, collectionId: number): Promise<boolean> {715 const result = await this.helper.executeExtrinsic(716 signer,717 'api.tx.unique.destroyCollection', [collectionId],718 true,719 );720721 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');722 }723724 725726727728729730731732733 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {734 const result = await this.helper.executeExtrinsic(735 signer,736 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],737 true,738 );739740 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');741 }742743 744745746747748749750751 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {752 const result = await this.helper.executeExtrinsic(753 signer,754 'api.tx.unique.confirmSponsorship', [collectionId],755 true,756 );757758 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');759 }760761 762763764765766767768769 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {770 const result = await this.helper.executeExtrinsic(771 signer,772 'api.tx.unique.removeCollectionSponsor', [collectionId],773 true,774 );775776 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');777 }778779 780781782783784785786787788789790791792793794795796 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {797 const result = await this.helper.executeExtrinsic(798 signer,799 'api.tx.unique.setCollectionLimits', [collectionId, limits],800 true,801 );802803 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');804 }805806 807808809810811812813814815 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {816 const result = await this.helper.executeExtrinsic(817 signer,818 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],819 true,820 );821822 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');823 }824825 826827828829830831832833834 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {835 const result = await this.helper.executeExtrinsic(836 signer,837 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],838 true,839 );840841 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');842 }843844 845846847848849850851852853 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {854 const result = await this.helper.executeExtrinsic(855 signer,856 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],857 true,858 );859860 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');861 }862863 864865866867868869870871 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {872 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();873 }874875 876877878879880881882 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {883 const result = await this.helper.executeExtrinsic(884 signer,885 'api.tx.unique.addToAllowList', [collectionId, addressObj],886 true,887 );888889 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');890 }891892 893894895896897898899900 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {901 const result = await this.helper.executeExtrinsic(902 signer,903 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],904 true,905 );906907 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');908 }909910 911912913914915916917918919 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {920 const result = await this.helper.executeExtrinsic(921 signer,922 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],923 true,924 );925926 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');927 }928929 930931932933934935936937938 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {939 return await this.setPermissions(signer, collectionId, {nesting: permissions});940 }941942 943944945946947948949950 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {951 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});952 }953954 955956957958959960961962963 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.setCollectionProperties', [collectionId, properties],967 true,968 );969970 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');971 }972973 974975976977978979980981 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {982 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();983 }984985 986987988989990991992993994 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {995 const result = await this.helper.executeExtrinsic(996 signer,997 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],998 true,999 );10001001 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1002 }10031004 10051006100710081009101010111012101310141015 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1016 const result = await this.helper.executeExtrinsic(1017 signer,1018 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1019 true, 1020 );10211022 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1023 }10241025 1026102710281029103010311032103310341035103610371038 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1039 const result = await this.helper.executeExtrinsic(1040 signer,1041 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1042 true, 1043 );1044 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1045 }10461047 10481049105010511052105310541055105610571058 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1059 const burnResult = await this.helper.executeExtrinsic(1060 signer,1061 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1062 true, 1063 );1064 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1065 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1066 return burnedTokens.success;1067 }10681069 10701071107210731074107510761077107810791080 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1081 const burnResult = await this.helper.executeExtrinsic(1082 signer,1083 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1084 true, 1085 );1086 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1087 return burnedTokens.success && burnedTokens.tokens.length > 0;1088 }10891090 1091109210931094109510961097109810991100 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1101 const approveResult = await this.helper.executeExtrinsic(1102 signer,1103 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1104 true, 1105 );11061107 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1108 }11091110 1111111211131114111511161117111811191120 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1121 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1122 }11231124 1125112611271128112911301131 async getLastTokenId(collectionId: number): Promise<number> {1132 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1133 }11341135 11361137113811391140114111421143 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1144 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1145 }1146}11471148class NFTnRFT extends CollectionGroup {1149 11501151115211531154115511561157 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1158 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1159 }11601161 1162116311641165116611671168116911701171 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1172 properties: IProperty[];1173 owner: CrossAccountId;1174 normalizedOwner: CrossAccountId;1175 }| null> {1176 let tokenData;1177 if(typeof blockHashAt === 'undefined') {1178 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1179 }1180 else {1181 if(propertyKeys.length == 0) {1182 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1183 if(!collection) return null;1184 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1185 }1186 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1187 }1188 tokenData = tokenData.toHuman();1189 if (tokenData === null || tokenData.owner === null) return null;1190 const owner = {} as any;1191 for (const key of Object.keys(tokenData.owner)) {1192 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1193 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1194 : tokenData.owner[key];1195 }1196 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1197 return tokenData;1198 }11991200 12011202120312041205120612071208120912101211 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1212 const result = await this.helper.executeExtrinsic(1213 signer,1214 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1215 true,1216 );12171218 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1219 }12201221 12221223122412251226122712281229 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1230 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1231 }12321233 1234123512361237123812391240124112421243 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1244 const result = await this.helper.executeExtrinsic(1245 signer,1246 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1247 true,1248 );12491250 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1251 }12521253 125412551256125712581259126012611262 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1263 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1264 }12651266 126712681269127012711272127312741275 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1276 const result = await this.helper.executeExtrinsic(1277 signer,1278 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1279 true,1280 );12811282 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1283 }12841285 128612871288128912901291129212931294 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1295 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1296 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1297 for (const key of ['name', 'description', 'tokenPrefix']) {1298 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);1299 }1300 const creationResult = await this.helper.executeExtrinsic(1301 signer,1302 'api.tx.unique.createCollectionEx', [collectionOptions],1303 true, 1304 );1305 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1306 }13071308 getCollectionObject(_collectionId: number): any {1309 return null;1310 }13111312 getTokenObject(_collectionId: number, _tokenId: number): any {1313 return null;1314 }1315}131613171318class NFTGroup extends NFTnRFT {1319 132013211322132313241325 getCollectionObject(collectionId: number): UniqueNFTCollection {1326 return new UniqueNFTCollection(collectionId, this.helper);1327 }13281329 1330133113321333133413351336 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1337 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1338 }13391340 13411342134313441345134613471348 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1349 let owner;1350 if (typeof blockHashAt === 'undefined') {1351 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1352 } else {1353 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1354 }1355 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1356 }13571358 1359136013611362136313641365 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1366 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1367 }13681369 1370137113721373137413751376137713781379 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1380 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1381 }13821383 138413851386138713881389139013911392139313941395 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1396 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1397 }13981399 14001401140214031404140514061407 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1408 let owner;1409 if (typeof blockHashAt === 'undefined') {1410 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1411 } else {1412 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1413 }14141415 if (owner === null) return null;14161417 return owner.toHuman();1418 }14191420 14211422142314241425142614271428 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1429 let children;1430 if(typeof blockHashAt === 'undefined') {1431 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1432 } else {1433 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1434 }14351436 return children.toJSON().map((x: any) => {1437 return {collectionId: x.collection, tokenId: x.token};1438 });1439 }14401441 14421443144414451446144714481449 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1450 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1451 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1452 if(!result) {1453 throw Error('Unable to nest token!');1454 }1455 return result;1456 }14571458 145914601461146214631464146514661467 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1468 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1469 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1470 if(!result) {1471 throw Error('Unable to unnest token!');1472 }1473 return result;1474 }14751476 147714781479148014811482148314841485148614871488 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1489 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1490 }14911492 149314941495149614971498 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1499 const creationResult = await this.helper.executeExtrinsic(1500 signer,1501 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1502 nft: {1503 properties: data.properties,1504 },1505 }],1506 true,1507 );1508 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1509 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1510 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1511 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1512 }15131514 151515161517151815191520152115221523152415251526152715281529 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1530 const creationResult = await this.helper.executeExtrinsic(1531 signer,1532 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1533 true,1534 );1535 const collection = this.getCollectionObject(collectionId);1536 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1537 }15381539 154015411542154315441545154615471548154915501551155215531554155515561557 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1558 const rawTokens = [];1559 for (const token of tokens) {1560 const raw = {NFT: {properties: token.properties}};1561 rawTokens.push(raw);1562 }1563 const creationResult = await this.helper.executeExtrinsic(1564 signer,1565 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1566 true,1567 );1568 const collection = this.getCollectionObject(collectionId);1569 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1570 }15711572 1573157415751576157715781579158015811582 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1583 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1584 }1585}158615871588class RFTGroup extends NFTnRFT {1589 159015911592159315941595 getCollectionObject(collectionId: number): UniqueRFTCollection {1596 return new UniqueRFTCollection(collectionId, this.helper);1597 }15981599 1600160116021603160416051606 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1607 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1608 }16091610 1611161216131614161516161617 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1618 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1619 }16201621 16221623162416251626162716281629 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1630 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1631 }16321633 1634163516361637163816391640164116421643 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1644 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1645 }16461647 16481649165016511652165316541655165616571658 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1659 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1660 }16611662 166316641665166616671668166916701671167216731674 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1675 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1676 }16771678 1679168016811682168316841685 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1686 const creationResult = await this.helper.executeExtrinsic(1687 signer,1688 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1689 refungible: {1690 pieces: data.pieces,1691 properties: data.properties,1692 },1693 }],1694 true,1695 );1696 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1697 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1698 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1699 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1700 }17011702 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1703 throw Error('Not implemented');1704 const creationResult = await this.helper.executeExtrinsic(1705 signer,1706 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1707 true, 1708 );1709 const collection = this.getCollectionObject(collectionId);1710 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1711 }17121713 171417151716171717181719172017211722 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1723 const rawTokens = [];1724 for (const token of tokens) {1725 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1726 rawTokens.push(raw);1727 }1728 const creationResult = await this.helper.executeExtrinsic(1729 signer,1730 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1731 true,1732 );1733 const collection = this.getCollectionObject(collectionId);1734 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1735 }17361737 173817391740174117421743174417451746 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1747 return await super.burnToken(signer, collectionId, tokenId, amount);1748 }17491750 1751175217531754175517561757175817591760 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1761 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1762 }17631764 17651766176717681769177017711772177317741775 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1776 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1777 }17781779 1780178117821783178417851786 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1787 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1788 }17891790 179117921793179417951796179717981799 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1800 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1801 const repartitionResult = await this.helper.executeExtrinsic(1802 signer,1803 'api.tx.unique.repartition', [collectionId, tokenId, amount],1804 true,1805 );1806 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1807 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1808 }1809}181018111812class FTGroup extends CollectionGroup {1813 181418151816181718181819 getCollectionObject(collectionId: number): UniqueFTCollection {1820 return new UniqueFTCollection(collectionId, this.helper);1821 }18221823 1824182518261827182818291830183118321833183418351836 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1837 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1838 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1839 collectionOptions.mode = {fungible: decimalPoints};1840 for (const key of ['name', 'description', 'tokenPrefix']) {1841 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);1842 }1843 const creationResult = await this.helper.executeExtrinsic(1844 signer,1845 'api.tx.unique.createCollectionEx', [collectionOptions],1846 true,1847 );1848 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1849 }18501851 185218531854185518561857185818591860 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1861 const creationResult = await this.helper.executeExtrinsic(1862 signer,1863 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1864 fungible: {1865 value: amount,1866 },1867 }],1868 true, 1869 );1870 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1871 }18721873 18741875187618771878187918801881 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1882 const rawTokens = [];1883 for (const token of tokens) {1884 const raw = {Fungible: {Value: token.value}};1885 rawTokens.push(raw);1886 }1887 const creationResult = await this.helper.executeExtrinsic(1888 signer,1889 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1890 true,1891 );1892 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1893 }18941895 189618971898189919001901 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1902 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1903 }19041905 1906190719081909191019111912 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1913 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1914 }19151916 191719181919192019211922192319241925 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1926 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1927 }19281929 1930193119321933193419351936193719381939 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1940 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1941 }19421943 19441945194619471948194919501951 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1952 return await super.burnToken(signer, collectionId, 0, amount);1953 }19541955 195619571958195919601961196219631964 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1965 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1966 }19671968 19691970197119721973 async getTotalPieces(collectionId: number): Promise<bigint> {1974 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1975 }19761977 1978197919801981198219831984198519861987 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1988 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1989 }19901991 1992199319941995199619971998 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1999 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);2000 }2001}200220032004class ChainGroup extends HelperGroup {2005 20062007200820092010 getChainProperties(): IChainProperties {2011 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2012 return {2013 ss58Format: properties.ss58Format.toJSON(),2014 tokenDecimals: properties.tokenDecimals.toJSON(),2015 tokenSymbol: properties.tokenSymbol.toJSON(),2016 };2017 }20182019 20202021202220232024 async getLatestBlockNumber(): Promise<number> {2025 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2026 }20272028 202920302031203220332034 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2035 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2036 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2037 return blockHash;2038 }20392040 2041 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2042 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2043 if (!blockHash) return null;2044 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2045 }20462047 204820492050205120522053 async getNonce(address: TSubstrateAccount): Promise<number> {2054 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2055 }2056}205720582059class BalanceGroup extends HelperGroup {2060 getCollectionCreationPrice(): bigint {2061 return 2n * this.helper.balance.getOneTokenNominal();2062 }2063 20642065206620672068 getOneTokenNominal(): bigint {2069 const chainProperties = this.helper.chain.getChainProperties();2070 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2071 }20722073 207420752076207720782079 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2080 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2081 }20822083 20842085208620872088 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2089 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2090 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2091 }20922093 209420952096209720982099 async getEthereum(address: TEthereumAccount): Promise<bigint> {2100 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2101 }21022103 21042105210621072108210921102111 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2112 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21132114 let transfer = {from: null, to: null, amount: 0n} as any;2115 result.result.events.forEach(({event: {data, method, section}}) => {2116 if ((section === 'balances') && (method === 'Transfer')) {2117 transfer = {2118 from: this.helper.address.normalizeSubstrate(data[0]),2119 to: this.helper.address.normalizeSubstrate(data[1]),2120 amount: BigInt(data[2]),2121 };2122 }2123 });2124 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2125 && this.helper.address.normalizeSubstrate(address) === transfer.to 2126 && BigInt(amount) === transfer.amount;2127 return isSuccess;2128 }2129}213021312132class AddressGroup extends HelperGroup {2133 2134213521362137213821392140 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2141 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2142 }21432144 214521462147214821492150 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2151 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2152 }21532154 2155215621572158215921602161 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2162 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2163 }21642165 216621672168216921702171 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2172 return CrossAccountId.translateSubToEth(subAddress);2173 }2174}21752176class StakingGroup extends HelperGroup {2177 2178217921802181218221832184 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2185 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2186 const _stakeResult = await this.helper.executeExtrinsic(2187 signer, 'api.tx.appPromotion.stake',2188 [amountToStake], true,2189 );2190 2191 return true;2192 }21932194 2195219621972198219922002201 async unstake(signer: TSigner, label?: string): Promise<number> {2202 if(typeof label === 'undefined') label = `${signer.address}`;2203 const _unstakeResult = await this.helper.executeExtrinsic(2204 signer, 'api.tx.appPromotion.unstake',2205 [], true,2206 );2207 2208 return 1;2209 }22102211 22122213221422152216 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2217 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2218 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2219 }22202221 22222223222422252226 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2227 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2228 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2229 return { 2230 block: block.toBigInt(),2231 amount: amount.toBigInt(),2232 };2233 });2234 }22352236 22372238223922402241 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2242 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2243 }22442245 22462247224822492250 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2251 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2252 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2253 return {2254 block: block.toBigInt(),2255 amount: amount.toBigInt(),2256 };2257 });2258 return result;2259 }2260}22612262class SchedulerGroup extends HelperGroup {2263 constructor(helper: UniqueHelper) {2264 super(helper);2265 }22662267 async cancelScheduled(signer: TSigner, scheduledId: string) {2268 return this.helper.executeExtrinsic(2269 signer,2270 'api.tx.scheduler.cancelNamed',2271 [scheduledId],2272 true,2273 );2274 }22752276 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2277 return this.helper.executeExtrinsic(2278 signer,2279 'api.tx.scheduler.changeNamedPriority',2280 [scheduledId, priority],2281 true,2282 );2283 }22842285 scheduleAt<T extends UniqueHelper>(2286 scheduledId: string,2287 executionBlockNumber: number,2288 options: ISchedulerOptions = {},2289 ) {2290 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2291 }22922293 scheduleAfter<T extends UniqueHelper>(2294 scheduledId: string,2295 blocksBeforeExecution: number,2296 options: ISchedulerOptions = {},2297 ) {2298 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2299 }23002301 schedule<T extends UniqueHelper>(2302 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2303 scheduledId: string,2304 blocksNum: number,2305 options: ISchedulerOptions = {},2306 ) {2307 2308 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2309 return this.helper.clone(ScheduledHelperType, {2310 scheduleFn,2311 scheduledId,2312 blocksNum,2313 options,2314 }) as T;2315 }2316}23172318export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;23192320export class UniqueHelper extends ChainHelperBase {2321 helperBase: any;23222323 chain: ChainGroup;2324 balance: BalanceGroup;2325 address: AddressGroup;2326 collection: CollectionGroup;2327 nft: NFTGroup;2328 rft: RFTGroup;2329 ft: FTGroup;2330 staking: StakingGroup;2331 scheduler: SchedulerGroup;23322333 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2334 super(logger);23352336 this.helperBase = options.helperBase ?? UniqueHelper;23372338 this.chain = new ChainGroup(this);2339 this.balance = new BalanceGroup(this);2340 this.address = new AddressGroup(this);2341 this.collection = new CollectionGroup(this);2342 this.nft = new NFTGroup(this);2343 this.rft = new RFTGroup(this);2344 this.ft = new FTGroup(this);2345 this.staking = new StakingGroup(this);2346 this.scheduler = new SchedulerGroup(this);2347 }23482349 clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {2350 Object.setPrototypeOf(helperCls.prototype, this);2351 const newHelper = new helperCls(this.logger, options);23522353 newHelper.api = this.api;2354 newHelper.network = this.network;2355 newHelper.forceNetwork = this.forceNetwork;23562357 this.children.push(newHelper);23582359 return newHelper;2360 }23612362 getSudo<T extends UniqueHelper>() {2363 2364 const SudoHelperType = SudoUniqueHelper(this.helperBase);2365 return this.clone(SudoHelperType) as T;2366 }2367}236823692370function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2371 return class extends Base {2372 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2373 scheduledId: string;2374 blocksNum: number;2375 options: ISchedulerOptions;23762377 constructor(...args: any[]) {2378 const logger = args[0] as ILogger;2379 const options = args[1] as {2380 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2381 scheduledId: string,2382 blocksNum: number,2383 options: ISchedulerOptions2384 };23852386 super(logger);23872388 this.scheduleFn = options.scheduleFn;2389 this.scheduledId = options.scheduledId;2390 this.blocksNum = options.blocksNum;2391 this.options = options.options;2392 }23932394 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2395 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2396 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;23972398 return super.executeExtrinsic(2399 sender,2400 extrinsic,2401 [2402 this.scheduledId,2403 this.blocksNum,2404 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2405 this.options.priority ?? null,2406 {Value: scheduledTx},2407 ],2408 expectSuccess,2409 );2410 }2411 };2412}241324142415function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2416 return class extends Base {2417 constructor(...args: any[]) {2418 super(...args);2419 }24202421 executeExtrinsic (2422 sender: IKeyringPair,2423 extrinsic: string,2424 params: any[],2425 expectSuccess?: boolean,2426 ): Promise<ITransactionResult> {2427 const call = this.constructApiCall(extrinsic, params);24282429 return super.executeExtrinsic(2430 sender,2431 'api.tx.sudo.sudo',2432 [call],2433 expectSuccess,2434 );2435 }2436 };2437}24382439export class UniqueBaseCollection {2440 helper: UniqueHelper;2441 collectionId: number;24422443 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2444 this.collectionId = collectionId;2445 this.helper = uniqueHelper;2446 }24472448 async getData() {2449 return await this.helper.collection.getData(this.collectionId);2450 }24512452 async getLastTokenId() {2453 return await this.helper.collection.getLastTokenId(this.collectionId);2454 }24552456 async doesTokenExist(tokenId: number) {2457 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2458 }24592460 async getAdmins() {2461 return await this.helper.collection.getAdmins(this.collectionId);2462 }24632464 async getAllowList() {2465 return await this.helper.collection.getAllowList(this.collectionId);2466 }24672468 async getEffectiveLimits() {2469 return await this.helper.collection.getEffectiveLimits(this.collectionId);2470 }24712472 async getProperties(propertyKeys?: string[] | null) {2473 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2474 }24752476 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2477 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2478 }24792480 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2481 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2482 }24832484 async confirmSponsorship(signer: TSigner) {2485 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2486 }24872488 async removeSponsor(signer: TSigner) {2489 return await this.helper.collection.removeSponsor(signer, this.collectionId);2490 }24912492 async setLimits(signer: TSigner, limits: ICollectionLimits) {2493 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2494 }24952496 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2497 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2498 }24992500 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2501 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2502 }25032504 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2505 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2506 }25072508 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2509 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2510 }25112512 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2513 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2514 }25152516 async setProperties(signer: TSigner, properties: IProperty[]) {2517 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2518 }25192520 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2521 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2522 }25232524 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2525 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2526 }25272528 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2529 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2530 }25312532 async disableNesting(signer: TSigner) {2533 return await this.helper.collection.disableNesting(signer, this.collectionId);2534 }25352536 async burn(signer: TSigner) {2537 return await this.helper.collection.burn(signer, this.collectionId);2538 }25392540 scheduleAt<T extends UniqueHelper>(2541 scheduledId: string,2542 executionBlockNumber: number,2543 options: ISchedulerOptions = {},2544 ) {2545 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2546 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2547 }25482549 scheduleAfter<T extends UniqueHelper>(2550 scheduledId: string,2551 blocksBeforeExecution: number,2552 options: ISchedulerOptions = {},2553 ) {2554 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2555 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2556 }25572558 getSudo<T extends UniqueHelper>() {2559 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2560 }2561}256225632564export class UniqueNFTCollection extends UniqueBaseCollection {2565 getTokenObject(tokenId: number) {2566 return new UniqueNFToken(tokenId, this);2567 }25682569 async getTokensByAddress(addressObj: ICrossAccountId) {2570 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2571 }25722573 async getToken(tokenId: number, blockHashAt?: string) {2574 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2575 }25762577 async getTokenOwner(tokenId: number, blockHashAt?: string) {2578 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2579 }25802581 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2582 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2583 }25842585 async getTokenChildren(tokenId: number, blockHashAt?: string) {2586 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2587 }25882589 async getPropertyPermissions(propertyKeys: string[] | null = null) {2590 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2591 }25922593 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2594 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2595 }25962597 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2598 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2599 }26002601 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2602 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2603 }26042605 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2606 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2607 }26082609 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2610 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2611 }26122613 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2614 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2615 }26162617 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2618 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2619 }26202621 async burnToken(signer: TSigner, tokenId: number) {2622 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2623 }26242625 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2626 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2627 }26282629 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2630 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2631 }26322633 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2634 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2635 }26362637 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2638 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2639 }26402641 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2642 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2643 }26442645 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2646 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2647 }26482649 scheduleAt<T extends UniqueHelper>(2650 scheduledId: string,2651 executionBlockNumber: number,2652 options: ISchedulerOptions = {},2653 ) {2654 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2655 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2656 }26572658 scheduleAfter<T extends UniqueHelper>(2659 scheduledId: string,2660 blocksBeforeExecution: number,2661 options: ISchedulerOptions = {},2662 ) {2663 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2664 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2665 }26662667 getSudo<T extends UniqueHelper>() {2668 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2669 }2670}267126722673export class UniqueRFTCollection extends UniqueBaseCollection {2674 getTokenObject(tokenId: number) {2675 return new UniqueRFToken(tokenId, this);2676 }26772678 async getToken(tokenId: number, blockHashAt?: string) {2679 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2680 }26812682 async getTokensByAddress(addressObj: ICrossAccountId) {2683 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2684 }26852686 async getTop10TokenOwners(tokenId: number) {2687 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2688 }26892690 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2691 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2692 }26932694 async getTokenTotalPieces(tokenId: number) {2695 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2696 }26972698 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2699 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2700 }27012702 async getPropertyPermissions(propertyKeys: string[] | null = null) {2703 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2704 }27052706 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2707 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2708 }27092710 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2711 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2712 }27132714 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2715 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2716 }27172718 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2719 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2720 }27212722 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2723 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2724 }27252726 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2727 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2728 }27292730 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2731 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2732 }27332734 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2735 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2736 }27372738 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2739 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2740 }27412742 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2743 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2744 }27452746 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2747 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2748 }27492750 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2751 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2752 }27532754 scheduleAt<T extends UniqueHelper>(2755 scheduledId: string,2756 executionBlockNumber: number,2757 options: ISchedulerOptions = {},2758 ) {2759 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2760 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2761 }27622763 scheduleAfter<T extends UniqueHelper>(2764 scheduledId: string,2765 blocksBeforeExecution: number,2766 options: ISchedulerOptions = {},2767 ) {2768 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2769 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2770 }27712772 getSudo<T extends UniqueHelper>() {2773 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());2774 }2775}277627772778export class UniqueFTCollection extends UniqueBaseCollection {2779 async getBalance(addressObj: ICrossAccountId) {2780 return await this.helper.ft.getBalance(this.collectionId, addressObj);2781 }27822783 async getTotalPieces() {2784 return await this.helper.ft.getTotalPieces(this.collectionId);2785 }27862787 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2788 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2789 }27902791 async getTop10Owners() {2792 return await this.helper.ft.getTop10Owners(this.collectionId);2793 }27942795 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2796 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2797 }27982799 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2800 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2801 }28022803 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2804 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2805 }28062807 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2808 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2809 }28102811 async burnTokens(signer: TSigner, amount=1n) {2812 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2813 }28142815 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2816 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2817 }28182819 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2820 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2821 }28222823 scheduleAt<T extends UniqueHelper>(2824 scheduledId: string,2825 executionBlockNumber: number,2826 options: ISchedulerOptions = {},2827 ) {2828 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2829 return new UniqueFTCollection(this.collectionId, scheduledHelper);2830 }28312832 scheduleAfter<T extends UniqueHelper>(2833 scheduledId: string,2834 blocksBeforeExecution: number,2835 options: ISchedulerOptions = {},2836 ) {2837 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2838 return new UniqueFTCollection(this.collectionId, scheduledHelper);2839 }28402841 getSudo<T extends UniqueHelper>() {2842 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());2843 }2844}284528462847export class UniqueBaseToken {2848 collection: UniqueNFTCollection | UniqueRFTCollection;2849 collectionId: number;2850 tokenId: number;28512852 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2853 this.collection = collection;2854 this.collectionId = collection.collectionId;2855 this.tokenId = tokenId;2856 }28572858 async getNextSponsored(addressObj: ICrossAccountId) {2859 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2860 }28612862 async getProperties(propertyKeys?: string[] | null) {2863 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2864 }28652866 async setProperties(signer: TSigner, properties: IProperty[]) {2867 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2868 }28692870 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2871 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2872 }28732874 async doesExist() {2875 return await this.collection.doesTokenExist(this.tokenId);2876 }28772878 nestingAccount() {2879 return this.collection.helper.util.getTokenAccount(this);2880 }28812882 scheduleAt<T extends UniqueHelper>(2883 scheduledId: string,2884 executionBlockNumber: number,2885 options: ISchedulerOptions = {},2886 ) {2887 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2888 return new UniqueBaseToken(this.tokenId, scheduledCollection);2889 }28902891 scheduleAfter<T extends UniqueHelper>(2892 scheduledId: string,2893 blocksBeforeExecution: number,2894 options: ISchedulerOptions = {},2895 ) {2896 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2897 return new UniqueBaseToken(this.tokenId, scheduledCollection);2898 }28992900 getSudo<T extends UniqueHelper>() {2901 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());2902 }2903}290429052906export class UniqueNFToken extends UniqueBaseToken {2907 collection: UniqueNFTCollection;29082909 constructor(tokenId: number, collection: UniqueNFTCollection) {2910 super(tokenId, collection);2911 this.collection = collection;2912 }29132914 async getData(blockHashAt?: string) {2915 return await this.collection.getToken(this.tokenId, blockHashAt);2916 }29172918 async getOwner(blockHashAt?: string) {2919 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2920 }29212922 async getTopmostOwner(blockHashAt?: string) {2923 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2924 }29252926 async getChildren(blockHashAt?: string) {2927 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2928 }29292930 async nest(signer: TSigner, toTokenObj: IToken) {2931 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2932 }29332934 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2935 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2936 }29372938 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2939 return await this.collection.transferToken(signer, this.tokenId, addressObj);2940 }29412942 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2943 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2944 }29452946 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2947 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2948 }29492950 async isApproved(toAddressObj: ICrossAccountId) {2951 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2952 }29532954 async burn(signer: TSigner) {2955 return await this.collection.burnToken(signer, this.tokenId);2956 }29572958 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2959 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2960 }29612962 scheduleAt<T extends UniqueHelper>(2963 scheduledId: string,2964 executionBlockNumber: number,2965 options: ISchedulerOptions = {},2966 ) {2967 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2968 return new UniqueNFToken(this.tokenId, scheduledCollection);2969 }29702971 scheduleAfter<T extends UniqueHelper>(2972 scheduledId: string,2973 blocksBeforeExecution: number,2974 options: ISchedulerOptions = {},2975 ) {2976 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2977 return new UniqueNFToken(this.tokenId, scheduledCollection);2978 }29792980 getSudo<T extends UniqueHelper>() {2981 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());2982 }2983}29842985export class UniqueRFToken extends UniqueBaseToken {2986 collection: UniqueRFTCollection;29872988 constructor(tokenId: number, collection: UniqueRFTCollection) {2989 super(tokenId, collection);2990 this.collection = collection;2991 }29922993 async getData(blockHashAt?: string) {2994 return await this.collection.getToken(this.tokenId, blockHashAt);2995 }29962997 async getTop10Owners() {2998 return await this.collection.getTop10TokenOwners(this.tokenId);2999 }30003001 async getBalance(addressObj: ICrossAccountId) {3002 return await this.collection.getTokenBalance(this.tokenId, addressObj);3003 }30043005 async getTotalPieces() {3006 return await this.collection.getTokenTotalPieces(this.tokenId);3007 }30083009 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3010 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3011 }30123013 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3014 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3015 }30163017 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3018 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3019 }30203021 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3022 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3023 }30243025 async repartition(signer: TSigner, amount: bigint) {3026 return await this.collection.repartitionToken(signer, this.tokenId, amount);3027 }30283029 async burn(signer: TSigner, amount=1n) {3030 return await this.collection.burnToken(signer, this.tokenId, amount);3031 }30323033 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3034 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3035 }30363037 scheduleAt<T extends UniqueHelper>(3038 scheduledId: string,3039 executionBlockNumber: number,3040 options: ISchedulerOptions = {},3041 ) {3042 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3043 return new UniqueRFToken(this.tokenId, scheduledCollection);3044 }30453046 scheduleAfter<T extends UniqueHelper>(3047 scheduledId: string,3048 blocksBeforeExecution: number,3049 options: ISchedulerOptions = {},3050 ) {3051 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3052 return new UniqueRFToken(this.tokenId, scheduledCollection);3053 }30543055 getSudo<T extends UniqueHelper>() {3056 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3057 }3058}