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, IForeignAssetMetadata} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair, domain: 'Substrate' | 'Ethereum' = 'Substrate') {24 switch (domain) {25 case 'Substrate': return new CrossAccountId({Substrate: account.address});26 case 'Ethereum': return new CrossAccountId({Substrate: account.address}).toEthereum();27 }28 }2930 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {31 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});32 }3334 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {35 return encodeAddress(decodeAddress(address), ss58Format);36 }3738 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {39 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});40 }41 42 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {43 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);44 return this;45 }4647 static translateSubToEth(address: TSubstrateAccount): TEthereumAccount {48 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(address), i => i.toString(16).padStart(2, '0')).join(''));49 }5051 toEthereum(): CrossAccountId {52 if (this.Substrate) return new CrossAccountId({Ethereum: CrossAccountId.translateSubToEth(this.Substrate)});53 return this;54 }5556 static translateEthToSub(address: TEthereumAccount, ss58Format?: number): TSubstrateAccount {57 return evmToAddress(address, ss58Format);58 }5960 toSubstrate(ss58Format?: number): CrossAccountId {61 if (this.Ethereum) return new CrossAccountId({Substrate: CrossAccountId.translateEthToSub(this.Ethereum, ss58Format)});62 return this;63 }64 65 toLowerCase(): CrossAccountId {66 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();67 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();68 return this;69 }70}7172const nesting = {73 toChecksumAddress(address: string): string {74 if (typeof address === 'undefined') return '';7576 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);7778 address = address.toLowerCase().replace(/^0x/i,'');79 const addressHash = keccakAsHex(address).replace(/^0x/i,'');80 const checksumAddress = ['0x'];8182 for (let i = 0; i < address.length; i++) {83 84 if (parseInt(addressHash[i], 16) > 7) {85 checksumAddress.push(address[i].toUpperCase());86 } else {87 checksumAddress.push(address[i]);88 }89 }90 return checksumAddress.join('');91 },92 tokenIdToAddress(collectionId: number, tokenId: number) {93 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);94 },95};9697class UniqueUtil {98 static transactionStatus = {99 NOT_READY: 'NotReady',100 FAIL: 'Fail',101 SUCCESS: 'Success',102 };103104 static chainLogType = {105 EXTRINSIC: 'extrinsic',106 RPC: 'rpc',107 };108109 static getTokenAccount(token: IToken): CrossAccountId {110 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});111 }112113 static getTokenAddress(token: IToken): string {114 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);115 }116117 static getDefaultLogger(): ILogger {118 return {119 log(msg: any, level = 'INFO') {120 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));121 },122 level: {123 ERROR: 'ERROR',124 WARNING: 'WARNING',125 INFO: 'INFO',126 },127 };128 }129130 static vec2str(arr: string[] | number[]) {131 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');132 }133134 static str2vec(string: string) {135 if (typeof string !== 'string') return string;136 return Array.from(string).map(x => x.charCodeAt(0));137 }138139 static fromSeed(seed: string, ss58Format = 42) {140 const keyring = new Keyring({type: 'sr25519', ss58Format});141 return keyring.addFromUri(seed);142 }143144 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult): number {145 if (creationResult.status !== this.transactionStatus.SUCCESS) {146 throw Error('Unable to create collection!');147 }148149 let collectionId = null;150 creationResult.result.events.forEach(({event: {data, method, section}}) => {151 if ((section === 'common') && (method === 'CollectionCreated')) {152 collectionId = parseInt(data[0].toString(), 10);153 }154 });155156 if (collectionId === null) {157 throw Error('No CollectionCreated event was found!');158 }159160 return collectionId;161 }162163 static extractTokensFromCreationResult(creationResult: ITransactionResult): {164 success: boolean, 165 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],166 } {167 if (creationResult.status !== this.transactionStatus.SUCCESS) {168 throw Error('Unable to create tokens!');169 }170 let success = false;171 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];172 creationResult.result.events.forEach(({event: {data, method, section}}) => {173 if (method === 'ExtrinsicSuccess') {174 success = true;175 } else if ((section === 'common') && (method === 'ItemCreated')) {176 tokens.push({177 collectionId: parseInt(data[0].toString(), 10),178 tokenId: parseInt(data[1].toString(), 10),179 owner: data[2].toHuman(),180 amount: data[3].toBigInt(),181 });182 }183 });184 return {success, tokens};185 }186187 static extractTokensFromBurnResult(burnResult: ITransactionResult): {188 success: boolean, 189 tokens: {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[],190 } {191 if (burnResult.status !== this.transactionStatus.SUCCESS) {192 throw Error('Unable to burn tokens!');193 }194 let success = false;195 const tokens = [] as {collectionId: number, tokenId: number, owner: CrossAccountId, amount: bigint}[];196 burnResult.result.events.forEach(({event: {data, method, section}}) => {197 if (method === 'ExtrinsicSuccess') {198 success = true;199 } else if ((section === 'common') && (method === 'ItemDestroyed')) {200 tokens.push({201 collectionId: parseInt(data[0].toString(), 10),202 tokenId: parseInt(data[1].toString(), 10),203 owner: data[2].toHuman(),204 amount: data[3].toBigInt(),205 });206 }207 });208 return {success, tokens};209 }210211 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string): boolean {212 let eventId = null;213 events.forEach(({event: {data, method, section}}) => {214 if ((section === expectedSection) && (method === expectedMethod)) {215 eventId = parseInt(data[0].toString(), 10);216 }217 });218219 if (eventId === null) {220 throw Error(`No ${expectedMethod} event was found!`);221 }222 return eventId === collectionId;223 }224225 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {226 const normalizeAddress = (address: string | ICrossAccountId) => {227 if(typeof address === 'string') return address;228 const obj = {} as any;229 Object.keys(address).forEach(k => {230 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];231 });232 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);233 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();234 return address;235 };236 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;237 events.forEach(({event: {data, method, section}}) => {238 if ((section === 'common') && (method === 'Transfer')) {239 const hData = (data as any).toJSON();240 transfer = {241 collectionId: hData[0],242 tokenId: hData[1],243 from: normalizeAddress(hData[2]),244 to: normalizeAddress(hData[3]),245 amount: BigInt(hData[4]),246 };247 }248 });249 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;250 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);251 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);252 isSuccess = isSuccess && amount === transfer.amount;253 return isSuccess;254 }255}256257class UniqueEventHelper {258 private static extractIndex(index: any): [number, number] | string {259 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];260 return index.toJSON();261 }262263 private static extractSub(data: any, subTypes: any): {[key: string]: any} {264 let obj: any = {};265 let index = 0;266267 if (data.entries) {268 for(const [key, value] of data.entries()) {269 obj[key] = this.extractData(value, subTypes[index]);270 index++;271 }272 } else obj = data.toJSON();273274 return obj;275 }276 277 private static extractData(data: any, type: any): any {278 if(!type) return data.toHuman();279 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();280 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();281 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);282 return data.toHuman();283 }284285 public static extractEvents(records: ITransactionResult): IEvent[] {286 const parsedEvents: IEvent[] = [];287288 records.result.events.forEach((record) => {289 const {event, phase} = record;290 const types = (event as any).typeDef;291292 const eventData: IEvent = {293 section: event.section.toString(),294 method: event.method.toString(),295 index: this.extractIndex(event.index),296 data: [],297 phase: phase.toJSON(),298 };299300 event.data.forEach((val: any, index: number) => {301 eventData.data.push(this.extractData(val, types[index]));302 });303304 parsedEvents.push(eventData);305 });306307 return parsedEvents;308 }309}310311class ChainHelperBase {312 transactionStatus = UniqueUtil.transactionStatus;313 chainLogType = UniqueUtil.chainLogType;314 util: typeof UniqueUtil;315 eventHelper: typeof UniqueEventHelper;316 logger: ILogger;317 api: ApiPromise | null;318 forcedNetwork: TUniqueNetworks | null;319 network: TUniqueNetworks | null;320 chainLog: IUniqueHelperLog[];321 children: ChainHelperBase[];322323 constructor(logger?: ILogger) {324 this.util = UniqueUtil;325 this.eventHelper = UniqueEventHelper;326 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();327 this.logger = logger;328 this.api = null;329 this.forcedNetwork = null;330 this.network = null;331 this.chainLog = [];332 this.children = [];333 }334335 getApi(): ApiPromise {336 if(this.api === null) throw Error('API not initialized');337 return this.api;338 }339340 clearChainLog(): void {341 this.chainLog = [];342 }343344 forceNetwork(value: TUniqueNetworks): void {345 this.forcedNetwork = value;346 }347348 async connect(wsEndpoint: string, listeners?: IApiListeners) {349 if (this.api !== null) throw Error('Already connected');350 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);351 this.api = api;352 this.network = network;353 }354355 async disconnect() {356 for (const child of this.children) {357 child.clearApi();358 }359360 if (this.api === null) return;361 await this.api.disconnect();362 this.clearApi();363 }364365 clearApi() {366 this.api = null;367 this.network = null;368 }369370 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {371 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;372 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;373 return 'opal';374 }375376 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {377 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});378 await api.isReady;379380 const network = await this.detectNetwork(api);381382 await api.disconnect();383384 return network;385 }386387 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{388 api: ApiPromise;389 network: TUniqueNetworks;390 }> {391 if(typeof network === 'undefined' || network === null) network = 'opal';392 const supportedRPC = {393 opal: {394 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,395 },396 quartz: {397 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,398 },399 unique: {400 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,401 },402 };403 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);404 const rpc = supportedRPC[network];405406 407 408409 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});410411 await api.isReadyOrError;412413 if (typeof listeners === 'undefined') listeners = {};414 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {415 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;416 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);417 }418419 return {api, network};420 }421422 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {423 const {events, status} = data;424 if (status.isReady) {425 return this.transactionStatus.NOT_READY;426 }427 if (status.isBroadcast) {428 return this.transactionStatus.NOT_READY;429 }430 if (status.isInBlock || status.isFinalized) {431 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');432 if (errors.length > 0) {433 return this.transactionStatus.FAIL;434 }435 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {436 return this.transactionStatus.SUCCESS;437 }438 }439440 return this.transactionStatus.FAIL;441 }442443 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {444 const sign = (callback: any) => {445 if(options !== null) return transaction.signAndSend(sender, options, callback);446 return transaction.signAndSend(sender, callback);447 };448 449 return new Promise(async (resolve, reject) => {450 try {451 const unsub = await sign((result: any) => {452 const status = this.getTransactionStatus(result);453454 if (status === this.transactionStatus.SUCCESS) {455 this.logger.log(`${label} successful`);456 unsub();457 resolve({result, status});458 } else if (status === this.transactionStatus.FAIL) {459 let moduleError = null;460461 if (result.hasOwnProperty('dispatchError')) {462 const dispatchError = result['dispatchError'];463464 if (dispatchError) {465 if (dispatchError.isModule) {466 const modErr = dispatchError.asModule;467 const errorMeta = dispatchError.registry.findMetaError(modErr);468469 moduleError = `${errorMeta.section}.${errorMeta.name}`;470 } else {471 moduleError = dispatchError.toHuman();472 }473 } else {474 this.logger.log(result, this.logger.level.ERROR);475 }476 }477478 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);479 unsub();480 reject({status, moduleError, result});481 }482 });483 } catch (e) {484 this.logger.log(e, this.logger.level.ERROR);485 reject(e);486 }487 });488 }489490 constructApiCall(apiCall: string, params: any[]) {491 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);492 let call = this.getApi() as any;493 for(const part of apiCall.slice(4).split('.')) {494 call = call[part];495 }496 return call(...params);497 }498499 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {500 if(this.api === null) throw Error('API not initialized');501 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);502503 const startTime = (new Date()).getTime();504 let result: ITransactionResult;505 let events: IEvent[] = [];506 try {507 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;508 events = this.eventHelper.extractEvents(result);509 }510 catch(e) {511 if(!(e as object).hasOwnProperty('status')) throw e;512 result = e as ITransactionResult;513 }514515 const endTime = (new Date()).getTime();516517 const log = {518 executedAt: endTime,519 executionTime: endTime - startTime,520 type: this.chainLogType.EXTRINSIC,521 status: result.status,522 call: extrinsic,523 signer: this.getSignerAddress(sender),524 params,525 } as IUniqueHelperLog;526527 if(result.status !== this.transactionStatus.SUCCESS) {528 if (result.moduleError) log.moduleError = result.moduleError;529 else if (result.result.dispatchError) log.dispatchError = result.result.dispatchError;530 }531 if(events.length > 0) log.events = events;532533 this.chainLog.push(log);534535 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) {536 if (result.moduleError) throw Error(`${result.moduleError}`);537 else if (result.result.dispatchError) throw Error(JSON.stringify(result.result.dispatchError));538 }539 return result;540 }541542 async callRpc(rpc: string, params?: any[]) {543 if(typeof params === 'undefined') params = [];544 if(this.api === null) throw Error('API not initialized');545 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);546547 const startTime = (new Date()).getTime();548 let result;549 let error = null;550 const log = {551 type: this.chainLogType.RPC,552 call: rpc,553 params,554 } as IUniqueHelperLog;555556 try {557 result = await this.constructApiCall(rpc, params);558 }559 catch(e) {560 error = e;561 }562563 const endTime = (new Date()).getTime();564565 log.executedAt = endTime;566 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';567 log.executionTime = endTime - startTime;568569 this.chainLog.push(log);570571 if(error !== null) throw error;572573 return result;574 }575576 getSignerAddress(signer: IKeyringPair | string): string {577 if(typeof signer === 'string') return signer;578 return signer.address;579 }580581 fetchAllPalletNames(): string[] {582 if(this.api === null) throw Error('API not initialized');583 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());584 }585586 fetchMissingPalletNames(requiredPallets: string[]): string[] {587 const palletNames = this.fetchAllPalletNames();588 return requiredPallets.filter(p => !palletNames.includes(p));589 }590}591592593class HelperGroup {594 helper: UniqueHelper;595596 constructor(uniqueHelper: UniqueHelper) {597 this.helper = uniqueHelper;598 }599}600601602class CollectionGroup extends HelperGroup {603 604605606607608609610611612 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {613 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();614 }615616 617618619620621 async getTotalCount(): Promise<number> {622 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();623 }624625 626627628629630631632633634 async getData(collectionId: number): Promise<{635 id: number;636 name: string;637 description: string;638 tokensCount: number;639 admins: CrossAccountId[];640 normalizedOwner: TSubstrateAccount;641 raw: any642 } | null> {643 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);644 const humanCollection = collection.toHuman(), collectionData = {645 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],646 raw: humanCollection,647 } as any, jsonCollection = collection.toJSON();648 if (humanCollection === null) return null;649 collectionData.raw.limits = jsonCollection.limits;650 collectionData.raw.permissions = jsonCollection.permissions;651 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);652 for (const key of ['name', 'description']) {653 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);654 }655656 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))657 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)658 : 0;659 collectionData.admins = await this.getAdmins(collectionId);660661 return collectionData;662 }663664 665666667668669670671672 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {673 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();674675 return normalize676 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())677 : admins;678 }679680 681682683684685686687 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {688 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();689 return normalize690 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())691 : allowListed;692 }693694 695696697698699700701 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {702 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();703 }704705 706707708709710711712713 async burn(signer: TSigner, collectionId: number): Promise<boolean> {714 const result = await this.helper.executeExtrinsic(715 signer,716 'api.tx.unique.destroyCollection', [collectionId],717 true,718 );719720 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');721 }722723 724725726727728729730731732 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {733 const result = await this.helper.executeExtrinsic(734 signer,735 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],736 true,737 );738739 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');740 }741742 743744745746747748749750 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {751 const result = await this.helper.executeExtrinsic(752 signer,753 'api.tx.unique.confirmSponsorship', [collectionId],754 true,755 );756757 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');758 }759760 761762763764765766767768 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {769 const result = await this.helper.executeExtrinsic(770 signer,771 'api.tx.unique.removeCollectionSponsor', [collectionId],772 true,773 );774775 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');776 }777778 779780781782783784785786787788789790791792793794795 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {796 const result = await this.helper.executeExtrinsic(797 signer,798 'api.tx.unique.setCollectionLimits', [collectionId, limits],799 true,800 );801802 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');803 }804805 806807808809810811812813814 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {815 const result = await this.helper.executeExtrinsic(816 signer,817 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],818 true,819 );820821 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');822 }823824 825826827828829830831832833 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {834 const result = await this.helper.executeExtrinsic(835 signer,836 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],837 true,838 );839840 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');841 }842843 844845846847848849850851852 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {853 const result = await this.helper.executeExtrinsic(854 signer,855 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],856 true,857 );858859 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');860 }861862 863864865866867868869870 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {871 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();872 }873874 875876877878879880881 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {882 const result = await this.helper.executeExtrinsic(883 signer,884 'api.tx.unique.addToAllowList', [collectionId, addressObj],885 true,886 );887888 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');889 }890891 892893894895896897898899 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {900 const result = await this.helper.executeExtrinsic(901 signer,902 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],903 true,904 );905906 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');907 }908909 910911912913914915916917918 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {919 const result = await this.helper.executeExtrinsic(920 signer,921 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],922 true,923 );924925 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');926 }927928 929930931932933934935936937 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {938 return await this.setPermissions(signer, collectionId, {nesting: permissions});939 }940941 942943944945946947948949 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {950 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});951 }952953 954955956957958959960961962 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {963 const result = await this.helper.executeExtrinsic(964 signer,965 'api.tx.unique.setCollectionProperties', [collectionId, properties],966 true,967 );968969 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');970 }971972 973974975976977978979980 async getProperties(collectionId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {981 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, propertyKeys])).toHuman();982 }983984 985986987988989990991992993 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {994 const result = await this.helper.executeExtrinsic(995 signer,996 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],997 true,998 );9991000 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');1001 }10021003 10041005100610071008100910101011101210131014 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1015 const result = await this.helper.executeExtrinsic(1016 signer,1017 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],1018 true, 1019 );10201021 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);1022 }10231024 1025102610271028102910301031103210331034103510361037 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1038 const result = await this.helper.executeExtrinsic(1039 signer,1040 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],1041 true, 1042 );1043 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1044 }10451046 10471048104910501051105210531054105510561057 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1058 const burnResult = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1061 true, 1062 );1063 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1064 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1065 return burnedTokens.success;1066 }10671068 10691070107110721073107410751076107710781079 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1080 const burnResult = await this.helper.executeExtrinsic(1081 signer,1082 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1083 true, 1084 );1085 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1086 return burnedTokens.success && burnedTokens.tokens.length > 0;1087 }10881089 1090109110921093109410951096109710981099 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1100 const approveResult = await this.helper.executeExtrinsic(1101 signer,1102 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1103 true, 1104 );11051106 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1107 }11081109 1110111111121113111411151116111711181119 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1120 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1121 }11221123 1124112511261127112811291130 async getLastTokenId(collectionId: number): Promise<number> {1131 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1132 }11331134 11351136113711381139114011411142 async doesTokenExist(collectionId: number, tokenId: number): Promise<boolean> {1143 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1144 }1145}11461147class NFTnRFT extends CollectionGroup {1148 11491150115111521153115411551156 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1157 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1158 }11591160 1161116211631164116511661167116811691170 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1171 properties: IProperty[];1172 owner: CrossAccountId;1173 normalizedOwner: CrossAccountId;1174 }| null> {1175 let tokenData;1176 if(typeof blockHashAt === 'undefined') {1177 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1178 }1179 else {1180 if(propertyKeys.length == 0) {1181 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1182 if(!collection) return null;1183 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1184 }1185 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1186 }1187 tokenData = tokenData.toHuman();1188 if (tokenData === null || tokenData.owner === null) return null;1189 const owner = {} as any;1190 for (const key of Object.keys(tokenData.owner)) {1191 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() == 'substrate' 1192 ? CrossAccountId.normalizeSubstrateAddress(tokenData.owner[key]) 1193 : tokenData.owner[key];1194 }1195 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1196 return tokenData;1197 }11981199 12001201120212031204120512061207120812091210 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1211 const result = await this.helper.executeExtrinsic(1212 signer,1213 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1214 true,1215 );12161217 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1218 }12191220 12211222122312241225122612271228 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1229 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1230 }12311232 1233123412351236123712381239124012411242 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1243 const result = await this.helper.executeExtrinsic(1244 signer,1245 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1246 true,1247 );12481249 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1250 }12511252 125312541255125612571258125912601261 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys?: string[] | null): Promise<IProperty[]> {1262 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, propertyKeys])).toHuman();1263 }12641265 126612671268126912701271127212731274 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1275 const result = await this.helper.executeExtrinsic(1276 signer,1277 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1278 true,1279 );12801281 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1282 }12831284 128512861287128812891290129112921293 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1294 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1295 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1296 for (const key of ['name', 'description', 'tokenPrefix']) {1297 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);1298 }1299 const creationResult = await this.helper.executeExtrinsic(1300 signer,1301 'api.tx.unique.createCollectionEx', [collectionOptions],1302 true, 1303 );1304 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1305 }13061307 getCollectionObject(_collectionId: number): any {1308 return null;1309 }13101311 getTokenObject(_collectionId: number, _tokenId: number): any {1312 return null;1313 }1314}131513161317class NFTGroup extends NFTnRFT {1318 131913201321132213231324 getCollectionObject(collectionId: number): UniqueNFTCollection {1325 return new UniqueNFTCollection(collectionId, this.helper);1326 }13271328 1329133013311332133313341335 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1336 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1337 }13381339 13401341134213431344134513461347 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1348 let owner;1349 if (typeof blockHashAt === 'undefined') {1350 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1351 } else {1352 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1353 }1354 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1355 }13561357 1358135913601361136213631364 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1365 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1366 }13671368 1369137013711372137313741375137613771378 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1379 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1380 }13811382 138313841385138613871388138913901391139213931394 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1395 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1396 }13971398 13991400140114021403140414051406 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1407 let owner;1408 if (typeof blockHashAt === 'undefined') {1409 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1410 } else {1411 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1412 }14131414 if (owner === null) return null;14151416 return owner.toHuman();1417 }14181419 14201421142214231424142514261427 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1428 let children;1429 if(typeof blockHashAt === 'undefined') {1430 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1431 } else {1432 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1433 }14341435 return children.toJSON().map((x: any) => {1436 return {collectionId: x.collection, tokenId: x.token};1437 });1438 }14391440 14411442144314441445144614471448 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1449 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1450 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1451 if(!result) {1452 throw Error('Unable to nest token!');1453 }1454 return result;1455 }14561457 145814591460146114621463146414651466 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1467 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1468 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1469 if(!result) {1470 throw Error('Unable to unnest token!');1471 }1472 return result;1473 }14741475 147614771478147914801481148214831484148514861487 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1488 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1489 }14901491 149214931494149514961497 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1498 const creationResult = await this.helper.executeExtrinsic(1499 signer,1500 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1501 nft: {1502 properties: data.properties,1503 },1504 }],1505 true,1506 );1507 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1508 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1509 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1510 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1511 }15121513 151415151516151715181519152015211522152315241525152615271528 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1529 const creationResult = await this.helper.executeExtrinsic(1530 signer,1531 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1532 true,1533 );1534 const collection = this.getCollectionObject(collectionId);1535 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1536 }15371538 153915401541154215431544154515461547154815491550155115521553155415551556 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1557 const rawTokens = [];1558 for (const token of tokens) {1559 const raw = {NFT: {properties: token.properties}};1560 rawTokens.push(raw);1561 }1562 const creationResult = await this.helper.executeExtrinsic(1563 signer,1564 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1565 true,1566 );1567 const collection = this.getCollectionObject(collectionId);1568 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1569 }15701571 1572157315741575157615771578157915801581 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1582 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1583 }1584}158515861587class RFTGroup extends NFTnRFT {1588 158915901591159215931594 getCollectionObject(collectionId: number): UniqueRFTCollection {1595 return new UniqueRFTCollection(collectionId, this.helper);1596 }15971598 1599160016011602160316041605 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1606 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1607 }16081609 1610161116121613161416151616 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1617 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1618 }16191620 16211622162316241625162616271628 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1629 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1630 }16311632 1633163416351636163716381639164016411642 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1643 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1644 }16451646 16471648164916501651165216531654165516561657 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1658 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1659 }16601661 166216631664166516661667166816691670167116721673 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1674 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1675 }16761677 1678167916801681168216831684 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1685 const creationResult = await this.helper.executeExtrinsic(1686 signer,1687 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1688 refungible: {1689 pieces: data.pieces,1690 properties: data.properties,1691 },1692 }],1693 true,1694 );1695 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1696 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1697 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1698 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1699 }17001701 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1702 throw Error('Not implemented');1703 const creationResult = await this.helper.executeExtrinsic(1704 signer,1705 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1706 true, 1707 );1708 const collection = this.getCollectionObject(collectionId);1709 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1710 }17111712 171317141715171617171718171917201721 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1722 const rawTokens = [];1723 for (const token of tokens) {1724 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1725 rawTokens.push(raw);1726 }1727 const creationResult = await this.helper.executeExtrinsic(1728 signer,1729 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1730 true,1731 );1732 const collection = this.getCollectionObject(collectionId);1733 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1734 }17351736 173717381739174017411742174317441745 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<boolean> {1746 return await super.burnToken(signer, collectionId, tokenId, amount);1747 }17481749 1750175117521753175417551756175717581759 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1760 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1761 }17621763 17641765176617671768176917701771177217731774 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1775 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1776 }17771778 1779178017811782178317841785 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1786 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1787 }17881789 179017911792179317941795179617971798 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1799 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1800 const repartitionResult = await this.helper.executeExtrinsic(1801 signer,1802 'api.tx.unique.repartition', [collectionId, tokenId, amount],1803 true,1804 );1805 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1806 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1807 }1808}180918101811class FTGroup extends CollectionGroup {1812 181318141815181618171818 getCollectionObject(collectionId: number): UniqueFTCollection {1819 return new UniqueFTCollection(collectionId, this.helper);1820 }18211822 1823182418251826182718281829183018311832183318341835 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1836 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1837 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1838 collectionOptions.mode = {fungible: decimalPoints};1839 for (const key of ['name', 'description', 'tokenPrefix']) {1840 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);1841 }1842 const creationResult = await this.helper.executeExtrinsic(1843 signer,1844 'api.tx.unique.createCollectionEx', [collectionOptions],1845 true,1846 );1847 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1848 }18491850 185118521853185418551856185718581859 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1860 const creationResult = await this.helper.executeExtrinsic(1861 signer,1862 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1863 fungible: {1864 value: amount,1865 },1866 }],1867 true, 1868 );1869 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1870 }18711872 18731874187518761877187818791880 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1881 const rawTokens = [];1882 for (const token of tokens) {1883 const raw = {Fungible: {Value: token.value}};1884 rawTokens.push(raw);1885 }1886 const creationResult = await this.helper.executeExtrinsic(1887 signer,1888 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1889 true,1890 );1891 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1892 }18931894 189518961897189818991900 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1901 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1902 }19031904 1905190619071908190919101911 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1912 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1913 }19141915 191619171918191919201921192219231924 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1925 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1926 }19271928 1929193019311932193319341935193619371938 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1939 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1940 }19411942 19431944194519461947194819491950 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1951 return await super.burnToken(signer, collectionId, 0, amount);1952 }19531954 195519561957195819591960196119621963 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1964 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1965 }19661967 19681969197019711972 async getTotalPieces(collectionId: number): Promise<bigint> {1973 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1974 }19751976 1977197819791980198119821983198419851986 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1987 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1988 }19891990 1991199219931994199519961997 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1998 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1999 }2000}200120022003class ChainGroup extends HelperGroup {2004 20052006200720082009 getChainProperties(): IChainProperties {2010 const properties = (this.helper.getApi() as any).registry.getChainProperties().toJSON();2011 return {2012 ss58Format: properties.ss58Format.toJSON(),2013 tokenDecimals: properties.tokenDecimals.toJSON(),2014 tokenSymbol: properties.tokenSymbol.toJSON(),2015 };2016 }20172018 20192020202120222023 async getLatestBlockNumber(): Promise<number> {2024 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();2025 }20262027 202820292030203120322033 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {2034 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();2035 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;2036 return blockHash;2037 }20382039 2040 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {2041 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);2042 if (!blockHash) return null;2043 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;2044 }20452046 204720482049205020512052 async getNonce(address: TSubstrateAccount): Promise<number> {2053 return (await this.helper.callRpc('api.query.system.account', [address])).nonce.toNumber();2054 }2055}205620572058class BalanceGroup extends HelperGroup {2059 getCollectionCreationPrice(): bigint {2060 return 2n * this.helper.balance.getOneTokenNominal();2061 }2062 20632064206520662067 getOneTokenNominal(): bigint {2068 const chainProperties = this.helper.chain.getChainProperties();2069 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2070 }20712072 207320742075207620772078 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2079 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2080 }20812082 20832084208520862087 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2088 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2089 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2090 }20912092 209320942095209620972098 async getEthereum(address: TEthereumAccount): Promise<bigint> {2099 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2100 }21012102 21032104210521062107210821092110 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2111 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);21122113 let transfer = {from: null, to: null, amount: 0n} as any;2114 result.result.events.forEach(({event: {data, method, section}}) => {2115 if ((section === 'balances') && (method === 'Transfer')) {2116 transfer = {2117 from: this.helper.address.normalizeSubstrate(data[0]),2118 to: this.helper.address.normalizeSubstrate(data[1]),2119 amount: BigInt(data[2]),2120 };2121 }2122 });2123 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2124 && this.helper.address.normalizeSubstrate(address) === transfer.to 2125 && BigInt(amount) === transfer.amount;2126 return isSuccess;2127 }2128}212921302131class AddressGroup extends HelperGroup {2132 2133213421352136213721382139 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2140 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2141 }21422143 214421452146214721482149 normalizeSubstrateToChainFormat(address: TSubstrateAccount): TSubstrateAccount {2150 return this.normalizeSubstrate(address, this.helper.chain.getChainProperties().ss58Format);2151 }21522153 2154215521562157215821592160 ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): TSubstrateAccount {2161 return CrossAccountId.translateEthToSub(ethAddress, toChainFormat ? this.helper.chain.getChainProperties().ss58Format : undefined);2162 }21632164 216521662167216821692170 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2171 return CrossAccountId.translateSubToEth(subAddress);2172 }2173}21742175class StakingGroup extends HelperGroup {2176 2177217821792180218121822183 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2184 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2185 const _stakeResult = await this.helper.executeExtrinsic(2186 signer, 'api.tx.appPromotion.stake',2187 [amountToStake], true,2188 );2189 2190 return true;2191 }21922193 2194219521962197219821992200 async unstake(signer: TSigner, label?: string): Promise<number> {2201 if(typeof label === 'undefined') label = `${signer.address}`;2202 const _unstakeResult = await this.helper.executeExtrinsic(2203 signer, 'api.tx.appPromotion.unstake',2204 [], true,2205 );2206 2207 return 1;2208 }22092210 22112212221322142215 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2216 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2217 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2218 }22192220 22212222222322242225 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2226 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2227 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2228 return { 2229 block: block.toBigInt(),2230 amount: amount.toBigInt(),2231 };2232 });2233 }22342235 22362237223822392240 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2241 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2242 }22432244 22452246224722482249 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2250 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2251 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2252 return {2253 block: block.toBigInt(),2254 amount: amount.toBigInt(),2255 };2256 });2257 return result;2258 }2259}22602261class SchedulerGroup extends HelperGroup {2262 constructor(helper: UniqueHelper) {2263 super(helper);2264 }22652266 async cancelScheduled(signer: TSigner, scheduledId: string) {2267 return this.helper.executeExtrinsic(2268 signer,2269 'api.tx.scheduler.cancelNamed',2270 [scheduledId],2271 true,2272 );2273 }22742275 async changePriority(signer: TSigner, scheduledId: string, priority: number) {2276 return this.helper.executeExtrinsic(2277 signer,2278 'api.tx.scheduler.changeNamedPriority',2279 [scheduledId, priority],2280 true,2281 );2282 }22832284 scheduleAt<T extends UniqueHelper>(2285 scheduledId: string,2286 executionBlockNumber: number,2287 options: ISchedulerOptions = {},2288 ) {2289 return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);2290 }22912292 scheduleAfter<T extends UniqueHelper>(2293 scheduledId: string,2294 blocksBeforeExecution: number,2295 options: ISchedulerOptions = {},2296 ) {2297 return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);2298 }22992300 schedule<T extends UniqueHelper>(2301 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2302 scheduledId: string,2303 blocksNum: number,2304 options: ISchedulerOptions = {},2305 ) {2306 2307 const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);2308 return this.helper.clone(ScheduledHelperType, {2309 scheduleFn,2310 scheduledId,2311 blocksNum,2312 options,2313 }) as T;2314 }2315}23162317class ForeignAssetsGroup extends HelperGroup {2318 constructor(helper: UniqueHelper) {2319 super(helper);2320 }23212322 async register(signer: TSigner, ownerAddress: TSubstrateAccount, location: any, metadata: IForeignAssetMetadata) {2323 await this.helper.executeExtrinsic(2324 signer,2325 'api.tx.foreignAssets.registerForeignAsset',2326 [ownerAddress, location, metadata],2327 true,2328 );2329 }23302331 async update(signer: TSigner, foreignAssetId: number, location: any, metadata: IForeignAssetMetadata) {2332 await this.helper.executeExtrinsic(2333 signer,2334 'api.tx.foreignAssets.updateForeignAsset',2335 [foreignAssetId, location, metadata],2336 true,2337 );2338 }2339}23402341export type UniqueHelperConstructor = new(...args: any[]) => UniqueHelper;23422343export class UniqueHelper extends ChainHelperBase {2344 helperBase: any;23452346 chain: ChainGroup;2347 balance: BalanceGroup;2348 address: AddressGroup;2349 collection: CollectionGroup;2350 nft: NFTGroup;2351 rft: RFTGroup;2352 ft: FTGroup;2353 staking: StakingGroup;2354 scheduler: SchedulerGroup;2355 foreignAssets: ForeignAssetsGroup;23562357 constructor(logger?: ILogger, options: {[key: string]: any} = {}) {2358 super(logger);23592360 this.helperBase = options.helperBase ?? UniqueHelper;23612362 this.chain = new ChainGroup(this);2363 this.balance = new BalanceGroup(this);2364 this.address = new AddressGroup(this);2365 this.collection = new CollectionGroup(this);2366 this.nft = new NFTGroup(this);2367 this.rft = new RFTGroup(this);2368 this.ft = new FTGroup(this);2369 this.staking = new StakingGroup(this);2370 this.scheduler = new SchedulerGroup(this);2371 this.foreignAssets = new ForeignAssetsGroup(this);2372 }23732374 clone(helperCls: UniqueHelperConstructor, options: {[key: string]: any} = {}) {2375 Object.setPrototypeOf(helperCls.prototype, this);2376 const newHelper = new helperCls(this.logger, options);23772378 newHelper.api = this.api;2379 newHelper.network = this.network;2380 newHelper.forceNetwork = this.forceNetwork;23812382 this.children.push(newHelper);23832384 return newHelper;2385 }23862387 getSudo<T extends UniqueHelper>() {2388 2389 const SudoHelperType = SudoUniqueHelper(this.helperBase);2390 return this.clone(SudoHelperType) as T;2391 }2392}239323942395function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2396 return class extends Base {2397 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';2398 scheduledId: string;2399 blocksNum: number;2400 options: ISchedulerOptions;24012402 constructor(...args: any[]) {2403 const logger = args[0] as ILogger;2404 const options = args[1] as {2405 scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',2406 scheduledId: string,2407 blocksNum: number,2408 options: ISchedulerOptions2409 };24102411 super(logger);24122413 this.scheduleFn = options.scheduleFn;2414 this.scheduledId = options.scheduledId;2415 this.blocksNum = options.blocksNum;2416 this.options = options.options;2417 }24182419 executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {2420 const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);2421 const extrinsic = 'api.tx.scheduler.' + this.scheduleFn;24222423 return super.executeExtrinsic(2424 sender,2425 extrinsic,2426 [2427 this.scheduledId,2428 this.blocksNum,2429 this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,2430 this.options.priority ?? null,2431 {Value: scheduledTx},2432 ],2433 expectSuccess,2434 );2435 }2436 };2437}243824392440function SudoUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {2441 return class extends Base {2442 constructor(...args: any[]) {2443 super(...args);2444 }24452446 executeExtrinsic (2447 sender: IKeyringPair,2448 extrinsic: string,2449 params: any[],2450 expectSuccess?: boolean,2451 ): Promise<ITransactionResult> {2452 const call = this.constructApiCall(extrinsic, params);24532454 return super.executeExtrinsic(2455 sender,2456 'api.tx.sudo.sudo',2457 [call],2458 expectSuccess,2459 );2460 }2461 };2462}24632464export class UniqueBaseCollection {2465 helper: UniqueHelper;2466 collectionId: number;24672468 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2469 this.collectionId = collectionId;2470 this.helper = uniqueHelper;2471 }24722473 async getData() {2474 return await this.helper.collection.getData(this.collectionId);2475 }24762477 async getLastTokenId() {2478 return await this.helper.collection.getLastTokenId(this.collectionId);2479 }24802481 async doesTokenExist(tokenId: number) {2482 return await this.helper.collection.doesTokenExist(this.collectionId, tokenId);2483 }24842485 async getAdmins() {2486 return await this.helper.collection.getAdmins(this.collectionId);2487 }24882489 async getAllowList() {2490 return await this.helper.collection.getAllowList(this.collectionId);2491 }24922493 async getEffectiveLimits() {2494 return await this.helper.collection.getEffectiveLimits(this.collectionId);2495 }24962497 async getProperties(propertyKeys?: string[] | null) {2498 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2499 }25002501 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2502 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2503 }25042505 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2506 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2507 }25082509 async confirmSponsorship(signer: TSigner) {2510 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2511 }25122513 async removeSponsor(signer: TSigner) {2514 return await this.helper.collection.removeSponsor(signer, this.collectionId);2515 }25162517 async setLimits(signer: TSigner, limits: ICollectionLimits) {2518 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2519 }25202521 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2522 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2523 }25242525 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2526 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2527 }25282529 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2530 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2531 }25322533 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2534 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2535 }25362537 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2538 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2539 }25402541 async setProperties(signer: TSigner, properties: IProperty[]) {2542 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2543 }25442545 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2546 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2547 }25482549 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2550 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2551 }25522553 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2554 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2555 }25562557 async disableNesting(signer: TSigner) {2558 return await this.helper.collection.disableNesting(signer, this.collectionId);2559 }25602561 async burn(signer: TSigner) {2562 return await this.helper.collection.burn(signer, this.collectionId);2563 }25642565 scheduleAt<T extends UniqueHelper>(2566 scheduledId: string,2567 executionBlockNumber: number,2568 options: ISchedulerOptions = {},2569 ) {2570 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2571 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2572 }25732574 scheduleAfter<T extends UniqueHelper>(2575 scheduledId: string,2576 blocksBeforeExecution: number,2577 options: ISchedulerOptions = {},2578 ) {2579 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2580 return new UniqueBaseCollection(this.collectionId, scheduledHelper);2581 }25822583 getSudo<T extends UniqueHelper>() {2584 return new UniqueBaseCollection(this.collectionId, this.helper.getSudo<T>());2585 }2586}258725882589export class UniqueNFTCollection extends UniqueBaseCollection {2590 getTokenObject(tokenId: number) {2591 return new UniqueNFToken(tokenId, this);2592 }25932594 async getTokensByAddress(addressObj: ICrossAccountId) {2595 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2596 }25972598 async getToken(tokenId: number, blockHashAt?: string) {2599 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2600 }26012602 async getTokenOwner(tokenId: number, blockHashAt?: string) {2603 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2604 }26052606 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2607 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2608 }26092610 async getTokenChildren(tokenId: number, blockHashAt?: string) {2611 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2612 }26132614 async getPropertyPermissions(propertyKeys: string[] | null = null) {2615 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2616 }26172618 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2619 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2620 }26212622 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2623 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2624 }26252626 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2627 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2628 }26292630 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2631 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2632 }26332634 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2635 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2636 }26372638 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2639 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2640 }26412642 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2643 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2644 }26452646 async burnToken(signer: TSigner, tokenId: number) {2647 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2648 }26492650 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2651 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2652 }26532654 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2655 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2656 }26572658 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2659 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2660 }26612662 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2663 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2664 }26652666 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2667 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2668 }26692670 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2671 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2672 }26732674 scheduleAt<T extends UniqueHelper>(2675 scheduledId: string,2676 executionBlockNumber: number,2677 options: ISchedulerOptions = {},2678 ) {2679 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2680 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2681 }26822683 scheduleAfter<T extends UniqueHelper>(2684 scheduledId: string,2685 blocksBeforeExecution: number,2686 options: ISchedulerOptions = {},2687 ) {2688 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2689 return new UniqueNFTCollection(this.collectionId, scheduledHelper);2690 }26912692 getSudo<T extends UniqueHelper>() {2693 return new UniqueNFTCollection(this.collectionId, this.helper.getSudo<T>());2694 }2695}269626972698export class UniqueRFTCollection extends UniqueBaseCollection {2699 getTokenObject(tokenId: number) {2700 return new UniqueRFToken(tokenId, this);2701 }27022703 async getToken(tokenId: number, blockHashAt?: string) {2704 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2705 }27062707 async getTokensByAddress(addressObj: ICrossAccountId) {2708 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2709 }27102711 async getTop10TokenOwners(tokenId: number) {2712 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2713 }27142715 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2716 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2717 }27182719 async getTokenTotalPieces(tokenId: number) {2720 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2721 }27222723 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2724 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2725 }27262727 async getPropertyPermissions(propertyKeys: string[] | null = null) {2728 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2729 }27302731 async getTokenProperties(tokenId: number, propertyKeys?: string[] | null) {2732 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2733 }27342735 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2736 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2737 }27382739 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2740 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2741 }27422743 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2744 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2745 }27462747 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2748 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2749 }27502751 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2752 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2753 }27542755 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2756 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2757 }27582759 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2760 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2761 }27622763 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2764 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2765 }27662767 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2768 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2769 }27702771 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2772 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2773 }27742775 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2776 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2777 }27782779 scheduleAt<T extends UniqueHelper>(2780 scheduledId: string,2781 executionBlockNumber: number,2782 options: ISchedulerOptions = {},2783 ) {2784 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2785 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2786 }27872788 scheduleAfter<T extends UniqueHelper>(2789 scheduledId: string,2790 blocksBeforeExecution: number,2791 options: ISchedulerOptions = {},2792 ) {2793 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2794 return new UniqueRFTCollection(this.collectionId, scheduledHelper);2795 }27962797 getSudo<T extends UniqueHelper>() {2798 return new UniqueRFTCollection(this.collectionId, this.helper.getSudo<T>());2799 }2800}280128022803export class UniqueFTCollection extends UniqueBaseCollection {2804 async getBalance(addressObj: ICrossAccountId) {2805 return await this.helper.ft.getBalance(this.collectionId, addressObj);2806 }28072808 async getTotalPieces() {2809 return await this.helper.ft.getTotalPieces(this.collectionId);2810 }28112812 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2813 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2814 }28152816 async getTop10Owners() {2817 return await this.helper.ft.getTop10Owners(this.collectionId);2818 }28192820 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2821 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2822 }28232824 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2825 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2826 }28272828 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2829 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2830 }28312832 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2833 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2834 }28352836 async burnTokens(signer: TSigner, amount=1n) {2837 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2838 }28392840 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2841 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2842 }28432844 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2845 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2846 }28472848 scheduleAt<T extends UniqueHelper>(2849 scheduledId: string,2850 executionBlockNumber: number,2851 options: ISchedulerOptions = {},2852 ) {2853 const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);2854 return new UniqueFTCollection(this.collectionId, scheduledHelper);2855 }28562857 scheduleAfter<T extends UniqueHelper>(2858 scheduledId: string,2859 blocksBeforeExecution: number,2860 options: ISchedulerOptions = {},2861 ) {2862 const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2863 return new UniqueFTCollection(this.collectionId, scheduledHelper);2864 }28652866 getSudo<T extends UniqueHelper>() {2867 return new UniqueFTCollection(this.collectionId, this.helper.getSudo<T>());2868 }2869}287028712872export class UniqueBaseToken {2873 collection: UniqueNFTCollection | UniqueRFTCollection;2874 collectionId: number;2875 tokenId: number;28762877 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2878 this.collection = collection;2879 this.collectionId = collection.collectionId;2880 this.tokenId = tokenId;2881 }28822883 async getNextSponsored(addressObj: ICrossAccountId) {2884 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2885 }28862887 async getProperties(propertyKeys?: string[] | null) {2888 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2889 }28902891 async setProperties(signer: TSigner, properties: IProperty[]) {2892 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2893 }28942895 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2896 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2897 }28982899 async doesExist() {2900 return await this.collection.doesTokenExist(this.tokenId);2901 }29022903 nestingAccount() {2904 return this.collection.helper.util.getTokenAccount(this);2905 }29062907 scheduleAt<T extends UniqueHelper>(2908 scheduledId: string,2909 executionBlockNumber: number,2910 options: ISchedulerOptions = {},2911 ) {2912 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2913 return new UniqueBaseToken(this.tokenId, scheduledCollection);2914 }29152916 scheduleAfter<T extends UniqueHelper>(2917 scheduledId: string,2918 blocksBeforeExecution: number,2919 options: ISchedulerOptions = {},2920 ) {2921 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);2922 return new UniqueBaseToken(this.tokenId, scheduledCollection);2923 }29242925 getSudo<T extends UniqueHelper>() {2926 return new UniqueBaseToken(this.tokenId, this.collection.getSudo<T>());2927 }2928}292929302931export class UniqueNFToken extends UniqueBaseToken {2932 collection: UniqueNFTCollection;29332934 constructor(tokenId: number, collection: UniqueNFTCollection) {2935 super(tokenId, collection);2936 this.collection = collection;2937 }29382939 async getData(blockHashAt?: string) {2940 return await this.collection.getToken(this.tokenId, blockHashAt);2941 }29422943 async getOwner(blockHashAt?: string) {2944 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2945 }29462947 async getTopmostOwner(blockHashAt?: string) {2948 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2949 }29502951 async getChildren(blockHashAt?: string) {2952 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2953 }29542955 async nest(signer: TSigner, toTokenObj: IToken) {2956 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2957 }29582959 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2960 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2961 }29622963 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2964 return await this.collection.transferToken(signer, this.tokenId, addressObj);2965 }29662967 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2968 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2969 }29702971 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2972 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2973 }29742975 async isApproved(toAddressObj: ICrossAccountId) {2976 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2977 }29782979 async burn(signer: TSigner) {2980 return await this.collection.burnToken(signer, this.tokenId);2981 }29822983 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2984 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2985 }29862987 scheduleAt<T extends UniqueHelper>(2988 scheduledId: string,2989 executionBlockNumber: number,2990 options: ISchedulerOptions = {},2991 ) {2992 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);2993 return new UniqueNFToken(this.tokenId, scheduledCollection);2994 }29952996 scheduleAfter<T extends UniqueHelper>(2997 scheduledId: string,2998 blocksBeforeExecution: number,2999 options: ISchedulerOptions = {},3000 ) {3001 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3002 return new UniqueNFToken(this.tokenId, scheduledCollection);3003 }30043005 getSudo<T extends UniqueHelper>() {3006 return new UniqueNFToken(this.tokenId, this.collection.getSudo<T>());3007 }3008}30093010export class UniqueRFToken extends UniqueBaseToken {3011 collection: UniqueRFTCollection;30123013 constructor(tokenId: number, collection: UniqueRFTCollection) {3014 super(tokenId, collection);3015 this.collection = collection;3016 }30173018 async getData(blockHashAt?: string) {3019 return await this.collection.getToken(this.tokenId, blockHashAt);3020 }30213022 async getTop10Owners() {3023 return await this.collection.getTop10TokenOwners(this.tokenId);3024 }30253026 async getBalance(addressObj: ICrossAccountId) {3027 return await this.collection.getTokenBalance(this.tokenId, addressObj);3028 }30293030 async getTotalPieces() {3031 return await this.collection.getTokenTotalPieces(this.tokenId);3032 }30333034 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {3035 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);3036 }30373038 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {3039 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);3040 }30413042 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {3043 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);3044 }30453046 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {3047 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);3048 }30493050 async repartition(signer: TSigner, amount: bigint) {3051 return await this.collection.repartitionToken(signer, this.tokenId, amount);3052 }30533054 async burn(signer: TSigner, amount=1n) {3055 return await this.collection.burnToken(signer, this.tokenId, amount);3056 }30573058 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {3059 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);3060 }30613062 scheduleAt<T extends UniqueHelper>(3063 scheduledId: string,3064 executionBlockNumber: number,3065 options: ISchedulerOptions = {},3066 ) {3067 const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);3068 return new UniqueRFToken(this.tokenId, scheduledCollection);3069 }30703071 scheduleAfter<T extends UniqueHelper>(3072 scheduledId: string,3073 blocksBeforeExecution: number,3074 options: ISchedulerOptions = {},3075 ) {3076 const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);3077 return new UniqueRFToken(this.tokenId, scheduledCollection);3078 }30793080 getSudo<T extends UniqueHelper>() {3081 return new UniqueRFToken(this.tokenId, this.collection.getSudo<T>());3082 }3083}