12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents, SignerOptions} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IBlock, IEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IStakingInfo, ISubstrateBalance, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314export class CrossAccountId implements ICrossAccountId {15 Substrate?: TSubstrateAccount;16 Ethereum?: TEthereumAccount;1718 constructor(account: ICrossAccountId) {19 if (account.Substrate) this.Substrate = account.Substrate;20 if (account.Ethereum) this.Ethereum = account.Ethereum;21 }2223 static fromKeyring(account: IKeyringPair) {24 return new CrossAccountId({Substrate: account.address});25 }2627 static fromLowerCaseKeys(address: ICrossAccountIdLower): CrossAccountId {28 return new CrossAccountId({Substrate: address.substrate, Ethereum: address.ethereum});29 }3031 static normalizeSubstrateAddress(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {32 return encodeAddress(decodeAddress(address), ss58Format);33 }3435 static withNormalizedSubstrate(address: TSubstrateAccount, ss58Format = 42): CrossAccountId {36 return new CrossAccountId({Substrate: CrossAccountId.normalizeSubstrateAddress(address, ss58Format)});37 }38 39 withNormalizedSubstrate(ss58Format = 42): CrossAccountId {40 if (this.Substrate) return CrossAccountId.withNormalizedSubstrate(this.Substrate, ss58Format);41 return this;42 }43 44 toLowerCase(): CrossAccountId {45 if (this.Substrate) this.Substrate = this.Substrate.toLowerCase();46 if (this.Ethereum) this.Ethereum = this.Ethereum.toLowerCase();47 return this;48 }49}5051const nesting = {52 toChecksumAddress(address: string): string {53 if (typeof address === 'undefined') return '';5455 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);5657 address = address.toLowerCase().replace(/^0x/i,'');58 const addressHash = keccakAsHex(address).replace(/^0x/i,'');59 const checksumAddress = ['0x'];6061 for (let i = 0; i < address.length; i++) {62 63 if (parseInt(addressHash[i], 16) > 7) {64 checksumAddress.push(address[i].toUpperCase());65 } else {66 checksumAddress.push(address[i]);67 }68 }69 return checksumAddress.join('');70 },71 tokenIdToAddress(collectionId: number, tokenId: number) {72 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);73 },74};7576class UniqueUtil {77 static transactionStatus = {78 NOT_READY: 'NotReady',79 FAIL: 'Fail',80 SUCCESS: 'Success',81 };8283 static chainLogType = {84 EXTRINSIC: 'extrinsic',85 RPC: 'rpc',86 };8788 static getTokenAccount(token: IToken): CrossAccountId {89 return new CrossAccountId({Ethereum: this.getTokenAddress(token)});90 }9192 static getTokenAddress(token: IToken): string {93 return nesting.tokenIdToAddress(token.collectionId, token.tokenId);94 }9596 static getDefaultLogger(): ILogger {97 return {98 log(msg: any, level = 'INFO') {99 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));100 },101 level: {102 ERROR: 'ERROR',103 WARNING: 'WARNING',104 INFO: 'INFO',105 },106 };107 }108109 static vec2str(arr: string[] | number[]) {110 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');111 }112113 static str2vec(string: string) {114 if (typeof string !== 'string') return string;115 return Array.from(string).map(x => x.charCodeAt(0));116 }117118 static fromSeed(seed: string, ss58Format = 42) {119 const keyring = new Keyring({type: 'sr25519', ss58Format});120 return keyring.addFromUri(seed);121 }122123 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {124 if (creationResult.status !== this.transactionStatus.SUCCESS) {125 throw Error('Unable to create collection!');126 }127128 let collectionId = null;129 creationResult.result.events.forEach(({event: {data, method, section}}) => {130 if ((section === 'common') && (method === 'CollectionCreated')) {131 collectionId = parseInt(data[0].toString(), 10);132 }133 });134135 if (collectionId === null) {136 throw Error('No CollectionCreated event was found!');137 }138139 return collectionId;140 }141142 static extractTokensFromCreationResult(creationResult: ITransactionResult) {143 if (creationResult.status !== this.transactionStatus.SUCCESS) {144 throw Error('Unable to create tokens!');145 }146 let success = false;147 const tokens = [] as any;148 creationResult.result.events.forEach(({event: {data, method, section}}) => {149 if (method === 'ExtrinsicSuccess') {150 success = true;151 } else if ((section === 'common') && (method === 'ItemCreated')) {152 tokens.push({153 collectionId: parseInt(data[0].toString(), 10),154 tokenId: parseInt(data[1].toString(), 10),155 owner: data[2].toJSON(),156 });157 }158 });159 return {success, tokens};160 }161162 static extractTokensFromBurnResult(burnResult: ITransactionResult) {163 if (burnResult.status !== this.transactionStatus.SUCCESS) {164 throw Error('Unable to burn tokens!');165 }166 let success = false;167 const tokens = [] as any;168 burnResult.result.events.forEach(({event: {data, method, section}}) => {169 if (method === 'ExtrinsicSuccess') {170 success = true;171 } else if ((section === 'common') && (method === 'ItemDestroyed')) {172 tokens.push({173 collectionId: parseInt(data[0].toString(), 10),174 tokenId: parseInt(data[1].toString(), 10),175 owner: data[2].toJSON(),176 });177 }178 });179 return {success, tokens};180 }181182 static findCollectionInEvents(events: {event: IEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {183 let eventId = null;184 events.forEach(({event: {data, method, section}}) => {185 if ((section === expectedSection) && (method === expectedMethod)) {186 eventId = parseInt(data[0].toString(), 10);187 }188 });189190 if (eventId === null) {191 throw Error(`No ${expectedMethod} event was found!`);192 }193 return eventId === collectionId;194 }195196 static isTokenTransferSuccess(events: {event: IEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {197 const normalizeAddress = (address: string | ICrossAccountId) => {198 if(typeof address === 'string') return address;199 const obj = {} as any;200 Object.keys(address).forEach(k => {201 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];202 });203 if(obj.substrate) return CrossAccountId.withNormalizedSubstrate(obj.substrate);204 if(obj.ethereum) return CrossAccountId.fromLowerCaseKeys(obj).toLowerCase();205 return address;206 };207 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;208 events.forEach(({event: {data, method, section}}) => {209 if ((section === 'common') && (method === 'Transfer')) {210 const hData = (data as any).toJSON();211 transfer = {212 collectionId: hData[0],213 tokenId: hData[1],214 from: normalizeAddress(hData[2]),215 to: normalizeAddress(hData[3]),216 amount: BigInt(hData[4]),217 };218 }219 });220 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;221 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);222 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);223 isSuccess = isSuccess && amount === transfer.amount;224 return isSuccess;225 }226}227228class UniqueEventHelper {229 private static extractIndex(index: any): [number, number] | string {230 if(index.toRawType() === '[u8;2]') return [index[0], index[1]];231 return index.toJSON();232 }233234 private static extractSub(data: any, subTypes: any): {[key: string]: any} {235 let obj: any = {};236 let index = 0;237238 if (data.entries) {239 for(const [key, value] of data.entries()) {240 obj[key] = this.extractData(value, subTypes[index]);241 index++;242 }243 } else obj = data.toJSON();244245 return obj;246 }247 248 private static extractData(data: any, type: any): any {249 if (['u16', 'u32'].indexOf(type.type) > -1) return data.toNumber();250 if (['u64', 'u128', 'u256'].indexOf(type.type) > -1) return data.toBigInt();251 if(type.hasOwnProperty('sub')) return this.extractSub(data, type.sub);252 return data.toHuman();253 }254255 public static extractEvents(records: ITransactionResult): IEvent[] {256 const parsedEvents: IEvent[] = [];257258 records.result.events.forEach((record) => {259 const {event, phase} = record;260 const types = (event as any).typeDef;261262 const eventData: IEvent = {263 section: event.section.toString(),264 method: event.method.toString(),265 index: this.extractIndex(event.index),266 data: [],267 phase: phase.toJSON(),268 };269270 event.data.forEach((val: any, index: number) => {271 eventData.data.push(this.extractData(val, types[index]));272 });273274 parsedEvents.push(eventData);275 });276277 return parsedEvents;278 }279}280281class ChainHelperBase {282 transactionStatus = UniqueUtil.transactionStatus;283 chainLogType = UniqueUtil.chainLogType;284 util: typeof UniqueUtil;285 eventHelper: typeof UniqueEventHelper;286 logger: ILogger;287 api: ApiPromise | null;288 forcedNetwork: TUniqueNetworks | null;289 network: TUniqueNetworks | null;290 chainLog: IUniqueHelperLog[];291292 constructor(logger?: ILogger) {293 this.util = UniqueUtil;294 this.eventHelper = UniqueEventHelper;295 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();296 this.logger = logger;297 this.api = null;298 this.forcedNetwork = null;299 this.network = null;300 this.chainLog = [];301 }302303 clearChainLog(): void {304 this.chainLog = [];305 }306307 forceNetwork(value: TUniqueNetworks): void {308 this.forcedNetwork = value;309 }310311 async connect(wsEndpoint: string, listeners?: IApiListeners) {312 if (this.api !== null) throw Error('Already connected');313 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);314 this.api = api;315 this.network = network;316 }317318 async disconnect() {319 if (this.api === null) return;320 await this.api.disconnect();321 this.api = null;322 this.network = null;323 }324325 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {326 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;327 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;328 return 'opal';329 }330331 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {332 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});333 await api.isReady;334335 const network = await this.detectNetwork(api);336337 await api.disconnect();338339 return network;340 }341342 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{343 api: ApiPromise;344 network: TUniqueNetworks;345 }> {346 if(typeof network === 'undefined' || network === null) network = 'opal';347 const supportedRPC = {348 opal: {349 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,350 },351 quartz: {352 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,353 },354 unique: {355 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,356 },357 };358 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);359 const rpc = supportedRPC[network];360361 362 363364 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});365366 await api.isReadyOrError;367368 if (typeof listeners === 'undefined') listeners = {};369 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {370 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;371 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);372 }373374 return {api, network};375 }376377 getTransactionStatus(data: {events: {event: IEvent}[], status: any}) {378 const {events, status} = data;379 if (status.isReady) {380 return this.transactionStatus.NOT_READY;381 }382 if (status.isBroadcast) {383 return this.transactionStatus.NOT_READY;384 }385 if (status.isInBlock || status.isFinalized) {386 const errors = events.filter(e => e.event.method === 'ExtrinsicFailed');387 if (errors.length > 0) {388 return this.transactionStatus.FAIL;389 }390 if (events.filter(e => e.event.method === 'ExtrinsicSuccess').length > 0) {391 return this.transactionStatus.SUCCESS;392 }393 }394395 return this.transactionStatus.FAIL;396 }397398 signTransaction(sender: TSigner, transaction: any, options: Partial<SignerOptions> | null = null, label = 'transaction') {399 const sign = (callback: any) => {400 if(options !== null) return transaction.signAndSend(sender, options, callback);401 return transaction.signAndSend(sender, callback);402 };403 404 return new Promise(async (resolve, reject) => {405 try {406 const unsub = await sign((result: any) => {407 const status = this.getTransactionStatus(result);408409 if (status === this.transactionStatus.SUCCESS) {410 this.logger.log(`${label} successful`);411 unsub();412 resolve({result, status});413 } else if (status === this.transactionStatus.FAIL) {414 let moduleError = null;415416 if (result.hasOwnProperty('dispatchError')) {417 const dispatchError = result['dispatchError'];418419 if (dispatchError) {420 if (dispatchError.isModule) {421 const modErr = dispatchError.asModule;422 const errorMeta = dispatchError.registry.findMetaError(modErr);423424 moduleError = `${errorMeta.section}.${errorMeta.name}`;425 } else {426 moduleError = dispatchError.toHuman();427 }428 } else {429 this.logger.log(result, this.logger.level.ERROR);430 }431 }432433 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);434 unsub();435 reject({status, moduleError, result});436 }437 });438 } catch (e) {439 this.logger.log(e, this.logger.level.ERROR);440 reject(e);441 }442 });443 }444445 constructApiCall(apiCall: string, params: any[]) {446 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);447 let call = this.api as any;448 for(const part of apiCall.slice(4).split('.')) {449 call = call[part];450 }451 return call(...params);452 }453454 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=true, options: Partial<SignerOptions>|null = null) {455 if(this.api === null) throw Error('API not initialized');456 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);457458 const startTime = (new Date()).getTime();459 let result: ITransactionResult;460 let events: IEvent[] = [];461 try {462 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), options, extrinsic) as ITransactionResult;463 events = this.eventHelper.extractEvents(result);464 }465 catch(e) {466 if(!(e as object).hasOwnProperty('status')) throw e;467 result = e as ITransactionResult;468 }469470 const endTime = (new Date()).getTime();471472 const log = {473 executedAt: endTime,474 executionTime: endTime - startTime,475 type: this.chainLogType.EXTRINSIC,476 status: result.status,477 call: extrinsic,478 signer: this.getSignerAddress(sender),479 params,480 } as IUniqueHelperLog;481482 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;483 if(events.length > 0) log.events = events;484485 this.chainLog.push(log);486487 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);488 return result;489 }490491 async callRpc(rpc: string, params?: any[]) {492 if(typeof params === 'undefined') params = [];493 if(this.api === null) throw Error('API not initialized');494 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);495496 const startTime = (new Date()).getTime();497 let result;498 let error = null;499 const log = {500 type: this.chainLogType.RPC,501 call: rpc,502 params,503 } as IUniqueHelperLog;504505 try {506 result = await this.constructApiCall(rpc, params);507 }508 catch(e) {509 error = e;510 }511512 const endTime = (new Date()).getTime();513514 log.executedAt = endTime;515 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';516 log.executionTime = endTime - startTime;517518 this.chainLog.push(log);519520 if(error !== null) throw error;521522 return result;523 }524525 getSignerAddress(signer: IKeyringPair | string): string {526 if(typeof signer === 'string') return signer;527 return signer.address;528 }529530 fetchAllPalletNames(): string[] {531 if(this.api === null) throw Error('API not initialized');532 return this.api.runtimeMetadata.asLatest.pallets.map(m => m.name.toString().toLowerCase());533 }534535 fetchMissingPalletNames(requiredPallets: string[]): string[] {536 const palletNames = this.fetchAllPalletNames();537 return requiredPallets.filter(p => !palletNames.includes(p));538 }539}540541542class HelperGroup {543 helper: UniqueHelper;544545 constructor(uniqueHelper: UniqueHelper) {546 this.helper = uniqueHelper;547 }548}549550551class CollectionGroup extends HelperGroup {552 553554555556557558559560561 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {562 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();563 }564565 566567568569570 async getTotalCount(): Promise<number> {571 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();572 }573574 575576577578579580581582583 async getData(collectionId: number): Promise<{584 id: number;585 name: string;586 description: string;587 tokensCount: number;588 admins: CrossAccountId[];589 normalizedOwner: TSubstrateAccount;590 raw: any591 } | null> {592 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);593 const humanCollection = collection.toHuman(), collectionData = {594 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],595 raw: humanCollection,596 } as any, jsonCollection = collection.toJSON();597 if (humanCollection === null) return null;598 collectionData.raw.limits = jsonCollection.limits;599 collectionData.raw.permissions = jsonCollection.permissions;600 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);601 for (const key of ['name', 'description']) {602 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);603 }604605 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode))606 ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId)607 : 0;608 collectionData.admins = await this.getAdmins(collectionId);609610 return collectionData;611 }612613 614615616617618619620621 async getAdmins(collectionId: number, normalize = false): Promise<CrossAccountId[]> {622 const admins = (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman();623624 return normalize625 ? admins.map((address: CrossAccountId) => address.withNormalizedSubstrate())626 : admins;627 }628629 630631632633634635636 async getAllowList(collectionId: number, normalize = false): Promise<CrossAccountId[]> {637 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();638 return normalize639 ? allowListed.map((address: CrossAccountId) => address.withNormalizedSubstrate())640 : allowListed;641 }642643 644645646647648649650 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {651 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();652 }653654 655656657658659660661662 async burn(signer: TSigner, collectionId: number): Promise<boolean> {663 const result = await this.helper.executeExtrinsic(664 signer,665 'api.tx.unique.destroyCollection', [collectionId],666 true,667 );668669 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');670 }671672 673674675676677678679680681 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {682 const result = await this.helper.executeExtrinsic(683 signer,684 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],685 true,686 );687688 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');689 }690691 692693694695696697698699 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {700 const result = await this.helper.executeExtrinsic(701 signer,702 'api.tx.unique.confirmSponsorship', [collectionId],703 true,704 );705706 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');707 }708709 710711712713714715716717 async removeSponsor(signer: TSigner, collectionId: number): Promise<boolean> {718 const result = await this.helper.executeExtrinsic(719 signer,720 'api.tx.unique.removeCollectionSponsor', [collectionId],721 true,722 );723724 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorRemoved');725 }726727 728729730731732733734735736737738739740741742743744 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {745 const result = await this.helper.executeExtrinsic(746 signer,747 'api.tx.unique.setCollectionLimits', [collectionId, limits],748 true,749 );750751 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');752 }753754 755756757758759760761762763 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {764 const result = await this.helper.executeExtrinsic(765 signer,766 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],767 true,768 );769770 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');771 }772773 774775776777778779780781782 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {783 const result = await this.helper.executeExtrinsic(784 signer,785 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],786 true,787 );788789 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');790 }791792 793794795796797798799800801 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {802 const result = await this.helper.executeExtrinsic(803 signer,804 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],805 true,806 );807808 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');809 }810811 812813814815816817818819 async allowed(collectionId: number, user: ICrossAccountId): Promise<boolean> {820 return (await this.helper.callRpc('api.rpc.unique.allowed', [collectionId, user])).toJSON();821 }822823 824825826827828829830 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {831 const result = await this.helper.executeExtrinsic(832 signer,833 'api.tx.unique.addToAllowList', [collectionId, addressObj],834 true,835 );836837 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');838 }839840 841842843844845846847848 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {849 const result = await this.helper.executeExtrinsic(850 signer,851 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],852 true,853 );854855 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');856 }857858 859860861862863864865866867 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {868 const result = await this.helper.executeExtrinsic(869 signer,870 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],871 true,872 );873874 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');875 }876877 878879880881882883884885886 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {887 return await this.setPermissions(signer, collectionId, {nesting: permissions});888 }889890 891892893894895896897898 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {899 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});900 }901902 903904905906907908909910911 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {912 const result = await this.helper.executeExtrinsic(913 signer,914 'api.tx.unique.setCollectionProperties', [collectionId, properties],915 true,916 );917918 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');919 }920921 922923924925926927928929 async getProperties(collectionId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {930 return (await this.helper.callRpc('api.rpc.unique.collectionProperties', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();931 }932933 934935936937938939940941942 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {943 const result = await this.helper.executeExtrinsic(944 signer,945 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],946 true,947 );948949 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');950 }951952 953954955956957958959960961962963 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {964 const result = await this.helper.executeExtrinsic(965 signer,966 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],967 true, 968 );969970 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);971 }972973 974975976977978979980981982983984985986 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {987 const result = await this.helper.executeExtrinsic(988 signer,989 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],990 true, 991 );992 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);993 }994995 9969979989991000100110021003100410051006 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{1007 success: boolean,1008 token: number | null1009 }> {1010 const burnResult = await this.helper.executeExtrinsic(1011 signer,1012 'api.tx.unique.burnItem', [collectionId, tokenId, amount],1013 true, 1014 );1015 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1016 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');1017 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};1018 }10191020 10211022102310241025102610271028102910301031 async burnTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1032 const burnResult = await this.helper.executeExtrinsic(1033 signer,1034 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],1035 true, 1036 );1037 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);1038 return burnedTokens.success && burnedTokens.tokens.length > 0;1039 }10401041 1042104310441045104610471048104910501051 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1052 const approveResult = await this.helper.executeExtrinsic(1053 signer,1054 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],1055 true, 1056 );10571058 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');1059 }10601061 1062106310641065106610671068106910701071 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {1072 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();1073 }10741075 1076107710781079108010811082 async getLastTokenId(collectionId: number): Promise<number> {1083 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();1084 }10851086 10871088108910901091109210931094 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {1095 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();1096 }1097}10981099class NFTnRFT extends CollectionGroup {1100 11011102110311041105110611071108 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {1109 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();1110 }11111112 1113111411151116111711181119112011211122 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{1123 properties: IProperty[];1124 owner: CrossAccountId;1125 normalizedOwner: CrossAccountId;1126 }| null> {1127 let tokenData;1128 if(typeof blockHashAt === 'undefined') {1129 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);1130 }1131 else {1132 if(propertyKeys.length == 0) {1133 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();1134 if(!collection) return null;1135 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);1136 }1137 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);1138 }1139 tokenData = tokenData.toHuman();1140 if (tokenData === null || tokenData.owner === null) return null;1141 const owner = {} as any;1142 for (const key of Object.keys(tokenData.owner)) {1143 owner[key.toLocaleLowerCase()] = new CrossAccountId(tokenData.owner[key]).withNormalizedSubstrate();1144 }1145 tokenData.normalizedOwner = CrossAccountId.fromLowerCaseKeys(owner);1146 return tokenData;1147 }11481149 11501151115211531154115511561157115811591160 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1161 const result = await this.helper.executeExtrinsic(1162 signer,1163 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1164 true,1165 );11661167 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1168 }11691170 11711172117311741175117611771178 async getPropertyPermissions(collectionId: number, propertyKeys: string[] | null = null): Promise<ITokenPropertyPermission[]> {1179 return (await this.helper.callRpc('api.rpc.unique.propertyPermissions', [collectionId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1180 }11811182 1183118411851186118711881189119011911192 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1193 const result = await this.helper.executeExtrinsic(1194 signer,1195 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1196 true,1197 );11981199 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1200 }12011202 120312041205120612071208120912101211 async getTokenProperties(collectionId: number, tokenId: number, propertyKeys: string[] | null = null): Promise<IProperty[]> {1212 return (await this.helper.callRpc('api.rpc.unique.tokenProperties', [collectionId, tokenId, ...(propertyKeys === null ? [] : [propertyKeys])])).toHuman();1213 }12141215 121612171218121912201221122212231224 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1225 const result = await this.helper.executeExtrinsic(1226 signer,1227 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1228 true,1229 );12301231 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1232 }12331234 123512361237123812391240124112421243 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueBaseCollection> {1244 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1245 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1246 for (const key of ['name', 'description', 'tokenPrefix']) {1247 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);1248 }1249 const creationResult = await this.helper.executeExtrinsic(1250 signer,1251 'api.tx.unique.createCollectionEx', [collectionOptions],1252 true, 1253 );1254 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1255 }12561257 getCollectionObject(_collectionId: number): any {1258 return null;1259 }12601261 getTokenObject(_collectionId: number, _tokenId: number): any {1262 return null;1263 }1264}126512661267class NFTGroup extends NFTnRFT {1268 126912701271127212731274 getCollectionObject(collectionId: number): UniqueNFTCollection {1275 return new UniqueNFTCollection(collectionId, this.helper);1276 }12771278 1279128012811282128312841285 getTokenObject(collectionId: number, tokenId: number): UniqueNFToken {1286 return new UniqueNFToken(tokenId, this.getCollectionObject(collectionId));1287 }12881289 12901291129212931294129512961297 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId> {1298 let owner;1299 if (typeof blockHashAt === 'undefined') {1300 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1301 } else {1302 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1303 }1304 return CrossAccountId.fromLowerCaseKeys(owner.toJSON());1305 }13061307 1308130913101311131213131314 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1315 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1316 }13171318 1319132013211322132313241325132613271328 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1329 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1330 }13311332 133313341335133613371338133913401341134213431344 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1345 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1346 }13471348 13491350135113521353135413551356 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<CrossAccountId | null> {1357 let owner;1358 if (typeof blockHashAt === 'undefined') {1359 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1360 } else {1361 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1362 }13631364 if (owner === null) return null;13651366 return owner.toHuman();1367 }13681369 13701371137213731374137513761377 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1378 let children;1379 if(typeof blockHashAt === 'undefined') {1380 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1381 } else {1382 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1383 }13841385 return children.toJSON().map((x: any) => {1386 return {collectionId: x.collection, tokenId: x.token};1387 });1388 }13891390 13911392139313941395139613971398 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1399 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1400 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1401 if(!result) {1402 throw Error('Unable to nest token!');1403 }1404 return result;1405 }14061407 140814091410141114121413141414151416 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1417 const rootTokenAddress = this.helper.util.getTokenAccount(rootTokenObj);1418 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1419 if(!result) {1420 throw Error('Unable to unnest token!');1421 }1422 return result;1423 }14241425 142614271428142914301431143214331434143514361437 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueNFTCollection> {1438 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1439 }14401441 144214431444144514461447 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFToken> {1448 const creationResult = await this.helper.executeExtrinsic(1449 signer,1450 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1451 nft: {1452 properties: data.properties,1453 },1454 }],1455 true,1456 );1457 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1458 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1459 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1460 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1461 }14621463 146414651466146714681469147014711472147314741475147614771478 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1479 const creationResult = await this.helper.executeExtrinsic(1480 signer,1481 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1482 true,1483 );1484 const collection = this.getCollectionObject(collectionId);1485 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1486 }14871488 148914901491149214931494149514961497149814991500150115021503150415051506 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFToken[]> {1507 const rawTokens = [];1508 for (const token of tokens) {1509 const raw = {NFT: {properties: token.properties}};1510 rawTokens.push(raw);1511 }1512 const creationResult = await this.helper.executeExtrinsic(1513 signer,1514 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1515 true,1516 );1517 const collection = this.getCollectionObject(collectionId);1518 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1519 }15201521 1522152315241525152615271528152915301531 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1532 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1533 }1534}153515361537class RFTGroup extends NFTnRFT {1538 153915401541154215431544 getCollectionObject(collectionId: number): UniqueRFTCollection {1545 return new UniqueRFTCollection(collectionId, this.helper);1546 }15471548 1549155015511552155315541555 getTokenObject(collectionId: number, tokenId: number): UniqueRFToken {1556 return new UniqueRFToken(tokenId, this.getCollectionObject(collectionId));1557 }15581559 1560156115621563156415651566 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<CrossAccountId[]> {1567 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1568 }15691570 15711572157315741575157615771578 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1579 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1580 }15811582 1583158415851586158715881589159015911592 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1593 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1594 }15951596 15971598159916001601160216031604160516061607 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1608 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1609 }16101611 161216131614161516161617161816191620162116221623 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}): Promise<UniqueRFTCollection> {1624 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1625 }16261627 1628162916301631163216331634 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFToken> {1635 const creationResult = await this.helper.executeExtrinsic(1636 signer,1637 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1638 refungible: {1639 pieces: data.pieces,1640 properties: data.properties,1641 },1642 }],1643 true,1644 );1645 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1646 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1647 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1648 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1649 }16501651 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1652 throw Error('Not implemented');1653 const creationResult = await this.helper.executeExtrinsic(1654 signer,1655 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1656 true, 1657 );1658 const collection = this.getCollectionObject(collectionId);1659 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1660 }16611662 166316641665166616671668166916701671 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFToken[]> {1672 const rawTokens = [];1673 for (const token of tokens) {1674 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1675 rawTokens.push(raw);1676 }1677 const creationResult = await this.helper.executeExtrinsic(1678 signer,1679 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1680 true,1681 );1682 const collection = this.getCollectionObject(collectionId);1683 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1684 }16851686 168716881689169016911692169316941695 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1696 return await super.burnToken(signer, collectionId, tokenId, amount);1697 }16981699 1700170117021703170417051706170717081709 async burnTokenFrom(signer: IKeyringPair, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1710 return await super.burnTokenFrom(signer, collectionId, tokenId, fromAddressObj, amount);1711 }17121713 17141715171617171718171917201721172217231724 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1725 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1726 }17271728 1729173017311732173317341735 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1736 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1737 }17381739 174017411742174317441745174617471748 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1749 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1750 const repartitionResult = await this.helper.executeExtrinsic(1751 signer,1752 'api.tx.unique.repartition', [collectionId, tokenId, amount],1753 true,1754 );1755 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1756 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1757 }1758}175917601761class FTGroup extends CollectionGroup {1762 176317641765176617671768 getCollectionObject(collectionId: number): UniqueFTCollection {1769 return new UniqueFTCollection(collectionId, this.helper);1770 }17711772 1773177417751776177717781779178017811782178317841785 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions = {}, decimalPoints = 0): Promise<UniqueFTCollection> {1786 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1787 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1788 collectionOptions.mode = {fungible: decimalPoints};1789 for (const key of ['name', 'description', 'tokenPrefix']) {1790 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);1791 }1792 const creationResult = await this.helper.executeExtrinsic(1793 signer,1794 'api.tx.unique.createCollectionEx', [collectionOptions],1795 true,1796 );1797 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1798 }17991800 180118021803180418051806180718081809 async mintTokens(signer: TSigner, collectionId: number, amount: bigint, owner: ICrossAccountId | string): Promise<boolean> {1810 const creationResult = await this.helper.executeExtrinsic(1811 signer,1812 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1813 fungible: {1814 value: amount,1815 },1816 }],1817 true, 1818 );1819 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1820 }18211822 18231824182518261827182818291830 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, tokens: {value: bigint}[], owner: ICrossAccountId): Promise<boolean> {1831 const rawTokens = [];1832 for (const token of tokens) {1833 const raw = {Fungible: {Value: token.value}};1834 rawTokens.push(raw);1835 }1836 const creationResult = await this.helper.executeExtrinsic(1837 signer,1838 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1839 true,1840 );1841 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1842 }18431844 184518461847184818491850 async getTop10Owners(collectionId: number): Promise<CrossAccountId[]> {1851 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(CrossAccountId.fromLowerCaseKeys);1852 }18531854 1855185618571858185918601861 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1862 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1863 }18641865 186618671868186918701871187218731874 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1875 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1876 }18771878 1879188018811882188318841885188618871888 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1889 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1890 }18911892 18931894189518961897189818991900 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1901 return (await super.burnToken(signer, collectionId, 0, amount)).success;1902 }19031904 190519061907190819091910191119121913 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1914 return await super.burnTokenFrom(signer, collectionId, 0, fromAddressObj, amount);1915 }19161917 19181919192019211922 async getTotalPieces(collectionId: number): Promise<bigint> {1923 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1924 }19251926 1927192819291930193119321933193419351936 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1937 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1938 }19391940 1941194219431944194519461947 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1948 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1949 }1950}195119521953class ChainGroup extends HelperGroup {1954 19551956195719581959 getChainProperties(): IChainProperties {1960 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1961 return {1962 ss58Format: properties.ss58Format.toJSON(),1963 tokenDecimals: properties.tokenDecimals.toJSON(),1964 tokenSymbol: properties.tokenSymbol.toJSON(),1965 };1966 }19671968 19691970197119721973 async getLatestBlockNumber(): Promise<number> {1974 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1975 }19761977 197819791980198119821983 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1984 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1985 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1986 return blockHash;1987 }19881989 1990 async getBlock(blockHashOrNumber: string | number): Promise<IBlock | null> {1991 const blockHash = typeof blockHashOrNumber === 'string' ? blockHashOrNumber : await this.getBlockHashByNumber(blockHashOrNumber);1992 if (!blockHash) return null;1993 return (await this.helper.callRpc('api.rpc.chain.getBlock', [blockHash])).toHuman().block;1994 }19951996 199719981999200020012002 async getNonce(address: TSubstrateAccount): Promise<number> {2003 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();2004 }2005}200620072008class BalanceGroup extends HelperGroup {2009 20102011201220132014 getOneTokenNominal(): bigint {2015 const chainProperties = this.helper.chain.getChainProperties();2016 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);2017 }20182019 202020212022202320242025 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {2026 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();2027 }20282029 20302031203220332034 async getSubstrateFull(address: TSubstrateAccount): Promise<ISubstrateBalance> {2035 const accountInfo = (await this.helper.callRpc('api.query.system.account', [address])).data;2036 return {free: accountInfo.free.toBigInt(), miscFrozen: accountInfo.miscFrozen.toBigInt(), feeFrozen: accountInfo.feeFrozen.toBigInt(), reserved: accountInfo.reserved.toBigInt()};2037 }20382039 204020412042204320442045 async getEthereum(address: TEthereumAccount): Promise<bigint> {2046 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();2047 }20482049 20502051205220532054205520562057 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {2058 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);20592060 let transfer = {from: null, to: null, amount: 0n} as any;2061 result.result.events.forEach(({event: {data, method, section}}) => {2062 if ((section === 'balances') && (method === 'Transfer')) {2063 transfer = {2064 from: this.helper.address.normalizeSubstrate(data[0]),2065 to: this.helper.address.normalizeSubstrate(data[1]),2066 amount: BigInt(data[2]),2067 };2068 }2069 });2070 const isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from 2071 && this.helper.address.normalizeSubstrate(address) === transfer.to 2072 && BigInt(amount) === transfer.amount;2073 return isSuccess;2074 }2075}207620772078class AddressGroup extends HelperGroup {2079 2080208120822083208420852086 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {2087 return CrossAccountId.normalizeSubstrateAddress(address, ss58Format);2088 }20892090 209120922093209420952096 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {2097 const info = this.helper.chain.getChainProperties();2098 return encodeAddress(decodeAddress(address), info.ss58Format);2099 }21002101 2102210321042105210621072108 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {2109 if(!toChainFormat) return evmToAddress(ethAddress);2110 const info = this.helper.chain.getChainProperties();2111 return evmToAddress(ethAddress, info.ss58Format);2112 }21132114 211521162117211821192120 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {2121 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));2122 }2123}21242125class StakingGroup extends HelperGroup {2126 2127212821292130213121322133 async stake(signer: TSigner, amountToStake: bigint, label?: string): Promise<boolean> {2134 if(typeof label === 'undefined') label = `${signer.address} amount: ${amountToStake}`;2135 const stakeResult = await this.helper.executeExtrinsic(2136 signer, 'api.tx.appPromotion.stake',2137 [amountToStake], true,2138 );2139 2140 return true;2141 }21422143 2144214521462147214821492150 async unstake(signer: TSigner, label?: string): Promise<number> {2151 if(typeof label === 'undefined') label = `${signer.address}`;2152 const unstakeResult = await this.helper.executeExtrinsic(2153 signer, 'api.tx.appPromotion.unstake',2154 [], true,2155 );2156 2157 return 1;2158 }21592160 21612162216321642165 async getTotalStaked(address?: ICrossAccountId): Promise<bigint> {2166 if (address) return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked', [address])).toBigInt();2167 return (await this.helper.callRpc('api.rpc.appPromotion.totalStaked')).toBigInt();2168 }21692170 21712172217321742175 async getTotalStakedPerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2176 const rawTotalStakerdPerBlock = await this.helper.callRpc('api.rpc.appPromotion.totalStakedPerBlock', [address]);2177 return rawTotalStakerdPerBlock.map(([block, amount]: any[]) => {2178 return { 2179 block: block.toBigInt(),2180 amount: amount.toBigInt(),2181 };2182 });2183 }21842185 21862187218821892190 async getPendingUnstake(address: ICrossAccountId): Promise<bigint> {2191 return (await this.helper.callRpc('api.rpc.appPromotion.pendingUnstake', [address])).toBigInt();2192 }21932194 21952196219721982199 async getPendingUnstakePerBlock(address: ICrossAccountId): Promise<IStakingInfo[]> {2200 const rawUnstakedPerBlock = await this.helper.callRpc('api.rpc.appPromotion.pendingUnstakePerBlock', [address]);2201 const result = rawUnstakedPerBlock.map(([block, amount]: any[]) => {2202 return {2203 block: block.toBigInt(),2204 amount: amount.toBigInt(),2205 };2206 });2207 return result;2208 }2209}22102211export class UniqueHelper extends ChainHelperBase {2212 chain: ChainGroup;2213 balance: BalanceGroup;2214 address: AddressGroup;2215 collection: CollectionGroup;2216 nft: NFTGroup;2217 rft: RFTGroup;2218 ft: FTGroup;2219 staking: StakingGroup;22202221 constructor(logger?: ILogger) {2222 super(logger);2223 this.chain = new ChainGroup(this);2224 this.balance = new BalanceGroup(this);2225 this.address = new AddressGroup(this);2226 this.collection = new CollectionGroup(this);2227 this.nft = new NFTGroup(this);2228 this.rft = new RFTGroup(this);2229 this.ft = new FTGroup(this);2230 this.staking = new StakingGroup(this);2231 }2232}223322342235export class UniqueBaseCollection {2236 helper: UniqueHelper;2237 collectionId: number;22382239 constructor(collectionId: number, uniqueHelper: UniqueHelper) {2240 this.collectionId = collectionId;2241 this.helper = uniqueHelper;2242 }22432244 async getData() {2245 return await this.helper.collection.getData(this.collectionId);2246 }22472248 async getLastTokenId() {2249 return await this.helper.collection.getLastTokenId(this.collectionId);2250 }22512252 async isTokenExists(tokenId: number) {2253 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);2254 }22552256 async getAdmins() {2257 return await this.helper.collection.getAdmins(this.collectionId);2258 }22592260 async getAllowList() {2261 return await this.helper.collection.getAllowList(this.collectionId);2262 }22632264 async getEffectiveLimits() {2265 return await this.helper.collection.getEffectiveLimits(this.collectionId);2266 }22672268 async getProperties(propertyKeys: string[] | null = null) {2269 return await this.helper.collection.getProperties(this.collectionId, propertyKeys);2270 }22712272 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2273 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2274 }22752276 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {2277 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);2278 }22792280 async confirmSponsorship(signer: TSigner) {2281 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2282 }22832284 async removeSponsor(signer: TSigner) {2285 return await this.helper.collection.removeSponsor(signer, this.collectionId);2286 }22872288 async setLimits(signer: TSigner, limits: ICollectionLimits) {2289 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2290 }22912292 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2293 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2294 }22952296 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2297 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2298 }22992300 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2301 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2302 }23032304 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2305 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2306 }23072308 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2309 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2310 }23112312 async setProperties(signer: TSigner, properties: IProperty[]) {2313 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2314 }23152316 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2317 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2318 }23192320 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2321 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2322 }23232324 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2325 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2326 }23272328 async disableNesting(signer: TSigner) {2329 return await this.helper.collection.disableNesting(signer, this.collectionId);2330 }23312332 async burn(signer: TSigner) {2333 return await this.helper.collection.burn(signer, this.collectionId);2334 }2335}233623372338export class UniqueNFTCollection extends UniqueBaseCollection {2339 getTokenObject(tokenId: number) {2340 return new UniqueNFToken(tokenId, this);2341 }23422343 async getTokensByAddress(addressObj: ICrossAccountId) {2344 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2345 }23462347 async getToken(tokenId: number, blockHashAt?: string) {2348 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2349 }23502351 async getTokenOwner(tokenId: number, blockHashAt?: string) {2352 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2353 }23542355 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2356 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2357 }23582359 async getTokenChildren(tokenId: number, blockHashAt?: string) {2360 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2361 }23622363 async getPropertyPermissions(propertyKeys: string[] | null = null) {2364 return await this.helper.nft.getPropertyPermissions(this.collectionId, propertyKeys);2365 }23662367 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2368 return await this.helper.nft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2369 }23702371 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2372 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2373 }23742375 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2376 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2377 }23782379 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2380 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2381 }23822383 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2384 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2385 }23862387 async mintToken(signer: TSigner, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2388 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2389 }23902391 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2392 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2393 }23942395 async burnToken(signer: TSigner, tokenId: number) {2396 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2397 }23982399 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId) {2400 return await this.helper.nft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj);2401 }24022403 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2404 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2405 }24062407 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2408 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2409 }24102411 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2412 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2413 }24142415 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2416 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2417 }24182419 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2420 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2421 }2422}242324242425export class UniqueRFTCollection extends UniqueBaseCollection {2426 getTokenObject(tokenId: number) {2427 return new UniqueRFToken(tokenId, this);2428 }24292430 async getToken(tokenId: number, blockHashAt?: string) {2431 return await this.helper.rft.getToken(this.collectionId, tokenId, [], blockHashAt);2432 }24332434 async getTokensByAddress(addressObj: ICrossAccountId) {2435 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2436 }24372438 async getTop10TokenOwners(tokenId: number) {2439 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2440 }24412442 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2443 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2444 }24452446 async getTokenTotalPieces(tokenId: number) {2447 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2448 }24492450 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2451 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2452 }24532454 async getPropertyPermissions(propertyKeys: string[] | null = null) {2455 return await this.helper.rft.getPropertyPermissions(this.collectionId, propertyKeys);2456 }24572458 async getTokenProperties(tokenId: number, propertyKeys: string[] | null = null) {2459 return await this.helper.rft.getTokenProperties(this.collectionId, tokenId, propertyKeys);2460 }24612462 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2463 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2464 }24652466 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2467 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2468 }24692470 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2471 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2472 }24732474 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2475 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2476 }24772478 async mintToken(signer: TSigner, pieces=1n, owner: ICrossAccountId = {Substrate: signer.address}, properties?: IProperty[]) {2479 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2480 }24812482 async mintMultipleTokens(signer: TSigner, tokens: {pieces: bigint, owner: ICrossAccountId, properties?: IProperty[]}[]) {2483 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2484 }24852486 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2487 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2488 }24892490 async burnTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, amount=1n) {2491 return await this.helper.rft.burnTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, amount);2492 }24932494 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2495 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2496 }24972498 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2499 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2500 }25012502 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2503 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2504 }2505}250625072508export class UniqueFTCollection extends UniqueBaseCollection {2509 async getBalance(addressObj: ICrossAccountId) {2510 return await this.helper.ft.getBalance(this.collectionId, addressObj);2511 }25122513 async getTotalPieces() {2514 return await this.helper.ft.getTotalPieces(this.collectionId);2515 }25162517 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2518 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2519 }25202521 async getTop10Owners() {2522 return await this.helper.ft.getTop10Owners(this.collectionId);2523 }25242525 async mint(signer: TSigner, amount=1n, owner: ICrossAccountId = {Substrate: signer.address}) {2526 return await this.helper.ft.mintTokens(signer, this.collectionId, amount, owner);2527 }25282529 async mintWithOneOwner(signer: TSigner, tokens: {value: bigint}[], owner: ICrossAccountId = {Substrate: signer.address}) {2530 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, tokens, owner);2531 }25322533 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2534 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2535 }25362537 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2538 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2539 }25402541 async burnTokens(signer: TSigner, amount=1n) {2542 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2543 }25442545 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2546 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2547 }25482549 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2550 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2551 }2552}255325542555export class UniqueBaseToken {2556 collection: UniqueNFTCollection | UniqueRFTCollection;2557 collectionId: number;2558 tokenId: number;25592560 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2561 this.collection = collection;2562 this.collectionId = collection.collectionId;2563 this.tokenId = tokenId;2564 }25652566 async getNextSponsored(addressObj: ICrossAccountId) {2567 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2568 }25692570 async getProperties(propertyKeys: string[] | null = null) {2571 return await this.collection.getTokenProperties(this.tokenId, propertyKeys);2572 }25732574 async setProperties(signer: TSigner, properties: IProperty[]) {2575 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2576 }25772578 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2579 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2580 }25812582 nestingAccount() {2583 return this.collection.helper.util.getTokenAccount(this);2584 }2585}258625872588export class UniqueNFToken extends UniqueBaseToken {2589 collection: UniqueNFTCollection;25902591 constructor(tokenId: number, collection: UniqueNFTCollection) {2592 super(tokenId, collection);2593 this.collection = collection;2594 }25952596 async getData(blockHashAt?: string) {2597 return await this.collection.getToken(this.tokenId, blockHashAt);2598 }25992600 async getOwner(blockHashAt?: string) {2601 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2602 }26032604 async getTopmostOwner(blockHashAt?: string) {2605 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2606 }26072608 async getChildren(blockHashAt?: string) {2609 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2610 }26112612 async nest(signer: TSigner, toTokenObj: IToken) {2613 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2614 }26152616 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2617 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2618 }26192620 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2621 return await this.collection.transferToken(signer, this.tokenId, addressObj);2622 }26232624 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2625 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2626 }26272628 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2629 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2630 }26312632 async isApproved(toAddressObj: ICrossAccountId) {2633 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2634 }26352636 async burn(signer: TSigner) {2637 return await this.collection.burnToken(signer, this.tokenId);2638 }26392640 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId) {2641 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj);2642 }2643}26442645export class UniqueRFToken extends UniqueBaseToken {2646 collection: UniqueRFTCollection;26472648 constructor(tokenId: number, collection: UniqueRFTCollection) {2649 super(tokenId, collection);2650 this.collection = collection;2651 }26522653 async getData(blockHashAt?: string) {2654 return await this.collection.getToken(this.tokenId, blockHashAt);2655 }26562657 async getTop10Owners() {2658 return await this.collection.getTop10TokenOwners(this.tokenId);2659 }26602661 async getBalance(addressObj: ICrossAccountId) {2662 return await this.collection.getTokenBalance(this.tokenId, addressObj);2663 }26642665 async getTotalPieces() {2666 return await this.collection.getTokenTotalPieces(this.tokenId);2667 }26682669 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2670 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2671 }26722673 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2674 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2675 }26762677 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2678 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2679 }26802681 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2682 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2683 }26842685 async repartition(signer: TSigner, amount: bigint) {2686 return await this.collection.repartitionToken(signer, this.tokenId, amount);2687 }26882689 async burn(signer: TSigner, amount=1n) {2690 return await this.collection.burnToken(signer, this.tokenId, amount);2691 }26922693 async burnFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2694 return await this.collection.burnTokenFrom(signer, this.tokenId, fromAddressObj, amount);2695 }2696}