12345678import {ApiPromise, WsProvider, Keyring} from '@polkadot/api';9import {ApiInterfaceEvents} from '@polkadot/api/types';10import {encodeAddress, decodeAddress, keccakAsHex, evmToAddress, addressToEvm} from '@polkadot/util-crypto';11import {IKeyringPair} from '@polkadot/types/types';12import {IApiListeners, IChainEvent, IChainProperties, ICollectionCreationOptions, ICollectionLimits, ICollectionPermissions, ICrossAccountId, ICrossAccountIdLower, ILogger, INestingPermissions, IProperty, IToken, ITokenPropertyPermission, ITransactionResult, IUniqueHelperLog, TApiAllowedListeners, TEthereumAccount, TSigner, TSubstrateAccount, TUniqueNetworks} from './types';1314const crossAccountIdFromLower = (lowerAddress: ICrossAccountIdLower): ICrossAccountId => {15 const address = {} as ICrossAccountId;16 if(lowerAddress.substrate) address.Substrate = lowerAddress.substrate;17 if(lowerAddress.ethereum) address.Ethereum = lowerAddress.ethereum;18 return address;19};202122const nesting = {23 toChecksumAddress(address: string): string {24 if (typeof address === 'undefined') return '';2526 if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error(`Given address "${address}" is not a valid Ethereum address.`);2728 address = address.toLowerCase().replace(/^0x/i,'');29 const addressHash = keccakAsHex(address).replace(/^0x/i,'');30 const checksumAddress = ['0x'];3132 for (let i = 0; i < address.length; i++) {33 34 if (parseInt(addressHash[i], 16) > 7) {35 checksumAddress.push(address[i].toUpperCase());36 } else {37 checksumAddress.push(address[i]);38 }39 }40 return checksumAddress.join('');41 },42 tokenIdToAddress(collectionId: number, tokenId: number) {43 return this.toChecksumAddress(`0xf8238ccfff8ed887463fd5e0${collectionId.toString(16).padStart(8, '0')}${tokenId.toString(16).padStart(8, '0')}`);44 },45};4647class UniqueUtil {48 static transactionStatus = {49 NOT_READY: 'NotReady',50 FAIL: 'Fail',51 SUCCESS: 'Success',52 };5354 static chainLogType = {55 EXTRINSIC: 'extrinsic',56 RPC: 'rpc',57 };5859 static getNestingTokenAddress(collectionId: number, tokenId: number) {60 return nesting.tokenIdToAddress(collectionId, tokenId);61 }6263 static getDefaultLogger(): ILogger {64 return {65 log(msg: any, level = 'INFO') {66 console[level.toLocaleLowerCase() === 'error' ? 'error' : 'log'](...(Array.isArray(msg) ? msg : [msg]));67 },68 level: {69 ERROR: 'ERROR',70 WARNING: 'WARNING',71 INFO: 'INFO',72 },73 };74 }7576 static vec2str(arr: string[] | number[]) {77 return arr.map(x => String.fromCharCode(parseInt(x.toString()))).join('');78 }7980 static str2vec(string: string) {81 if (typeof string !== 'string') return string;82 return Array.from(string).map(x => x.charCodeAt(0));83 }8485 static fromSeed(seed: string, ss58Format = 42) {86 const keyring = new Keyring({type: 'sr25519', ss58Format});87 return keyring.addFromUri(seed);88 }8990 static normalizeSubstrateAddress(address: string, ss58Format = 42) {91 return encodeAddress(decodeAddress(address), ss58Format);92 }9394 static extractCollectionIdFromCreationResult(creationResult: ITransactionResult) {95 if (creationResult.status !== this.transactionStatus.SUCCESS) {96 throw Error('Unable to create collection!');97 }9899 let collectionId = null;100 creationResult.result.events.forEach(({event: {data, method, section}}) => {101 if ((section === 'common') && (method === 'CollectionCreated')) {102 collectionId = parseInt(data[0].toString(), 10);103 }104 });105106 if (collectionId === null) {107 throw Error('No CollectionCreated event was found!');108 }109110 return collectionId;111 }112113 static extractTokensFromCreationResult(creationResult: ITransactionResult) {114 if (creationResult.status !== this.transactionStatus.SUCCESS) {115 throw Error('Unable to create tokens!');116 }117 let success = false;118 const tokens = [] as any;119 creationResult.result.events.forEach(({event: {data, method, section}}) => {120 if (method === 'ExtrinsicSuccess') {121 success = true;122 } else if ((section === 'common') && (method === 'ItemCreated')) {123 tokens.push({124 collectionId: parseInt(data[0].toString(), 10),125 tokenId: parseInt(data[1].toString(), 10),126 owner: data[2].toJSON(),127 });128 }129 });130 return {success, tokens};131 }132133 static extractTokensFromBurnResult(burnResult: ITransactionResult) {134 if (burnResult.status !== this.transactionStatus.SUCCESS) {135 throw Error('Unable to burn tokens!');136 }137 let success = false;138 const tokens = [] as any;139 burnResult.result.events.forEach(({event: {data, method, section}}) => {140 if (method === 'ExtrinsicSuccess') {141 success = true;142 } else if ((section === 'common') && (method === 'ItemDestroyed')) {143 tokens.push({144 collectionId: parseInt(data[0].toString(), 10),145 tokenId: parseInt(data[1].toString(), 10),146 owner: data[2].toJSON(),147 });148 }149 });150 return {success, tokens};151 }152153 static findCollectionInEvents(events: {event: IChainEvent}[], collectionId: number, expectedSection: string, expectedMethod: string) {154 let eventId = null;155 events.forEach(({event: {data, method, section}}) => {156 if ((section === expectedSection) && (method === expectedMethod)) {157 eventId = parseInt(data[0].toString(), 10);158 }159 });160161 if (eventId === null) {162 throw Error(`No ${expectedMethod} event was found!`);163 }164 return eventId === collectionId;165 }166167 static isTokenTransferSuccess(events: {event: IChainEvent}[], collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {168 const normalizeAddress = (address: string | ICrossAccountId) => {169 if(typeof address === 'string') return address;170 const obj = {} as any;171 Object.keys(address).forEach(k => {172 obj[k.toLocaleLowerCase()] = address[k as 'Substrate' | 'Ethereum'];173 });174 if(obj.substrate) return {Substrate: this.normalizeSubstrateAddress(obj.substrate)};175 if(obj.ethereum) return {Ethereum: obj.ethereum.toLocaleLowerCase()};176 return address;177 };178 let transfer = {collectionId: null, tokenId: null, from: null, to: null, amount: 1} as any;179 events.forEach(({event: {data, method, section}}) => {180 if ((section === 'common') && (method === 'Transfer')) {181 const hData = (data as any).toJSON();182 transfer = {183 collectionId: hData[0],184 tokenId: hData[1],185 from: normalizeAddress(hData[2]),186 to: normalizeAddress(hData[3]),187 amount: BigInt(hData[4]),188 };189 }190 });191 let isSuccess = parseInt(collectionId.toString()) === transfer.collectionId && parseInt(tokenId.toString()) === transfer.tokenId;192 isSuccess = isSuccess && JSON.stringify(normalizeAddress(fromAddressObj)) === JSON.stringify(transfer.from);193 isSuccess = isSuccess && JSON.stringify(normalizeAddress(toAddressObj)) === JSON.stringify(transfer.to);194 isSuccess = isSuccess && amount === transfer.amount;195 return isSuccess;196 }197}198199200class ChainHelperBase {201 transactionStatus = UniqueUtil.transactionStatus;202 chainLogType = UniqueUtil.chainLogType;203 util: typeof UniqueUtil;204 logger: ILogger;205 api: ApiPromise | null;206 forcedNetwork: TUniqueNetworks | null;207 network: TUniqueNetworks | null;208 chainLog: IUniqueHelperLog[];209210 constructor(logger?: ILogger) {211 this.util = UniqueUtil;212 if (typeof logger == 'undefined') logger = this.util.getDefaultLogger();213 this.logger = logger;214 this.api = null;215 this.forcedNetwork = null;216 this.network = null;217 this.chainLog = [];218 }219220 clearChainLog(): void {221 this.chainLog = [];222 }223224 forceNetwork(value: TUniqueNetworks): void {225 this.forcedNetwork = value;226 }227228 async connect(wsEndpoint: string, listeners?: IApiListeners) {229 if (this.api !== null) throw Error('Already connected');230 const {api, network} = await ChainHelperBase.createConnection(wsEndpoint, listeners, this.forcedNetwork);231 this.api = api;232 this.network = network;233 }234235 async disconnect() {236 if (this.api === null) return;237 await this.api.disconnect();238 this.api = null;239 this.network = null;240 }241242 static async detectNetwork(api: ApiPromise): Promise<TUniqueNetworks> {243 const spec = (await api.query.system.lastRuntimeUpgrade()).toJSON() as any;244 if(['quartz', 'unique'].indexOf(spec.specName) > -1) return spec.specName;245 return 'opal';246 }247248 static async detectNetworkByWsEndpoint(wsEndpoint: string): Promise<TUniqueNetworks> {249 const api = new ApiPromise({provider: new WsProvider(wsEndpoint)});250 await api.isReady;251252 const network = await this.detectNetwork(api);253254 await api.disconnect();255256 return network;257 }258259 static async createConnection(wsEndpoint: string, listeners?: IApiListeners, network?: TUniqueNetworks | null): Promise<{ 260 api: ApiPromise; 261 network: TUniqueNetworks; 262 }> {263 if(typeof network === 'undefined' || network === null) network = 'opal';264 const supportedRPC = {265 opal: {266 unique: require('@unique-nft/opal-testnet-types/definitions').unique.rpc,267 },268 quartz: {269 unique: require('@unique-nft/quartz-mainnet-types/definitions').unique.rpc,270 },271 unique: {272 unique: require('@unique-nft/unique-mainnet-types/definitions').unique.rpc,273 },274 };275 if(!supportedRPC.hasOwnProperty(network)) network = await this.detectNetworkByWsEndpoint(wsEndpoint);276 const rpc = supportedRPC[network];277278 279 280281 const api = new ApiPromise({provider: new WsProvider(wsEndpoint), rpc});282283 await api.isReadyOrError;284285 if (typeof listeners === 'undefined') listeners = {};286 for (const event of ['connected', 'disconnected', 'error', 'ready', 'decorated']) {287 if (!listeners.hasOwnProperty(event) || typeof listeners[event as TApiAllowedListeners] === 'undefined') continue;288 api.on(event as ApiInterfaceEvents, listeners[event as TApiAllowedListeners] as (...args: any[]) => any);289 }290291 return {api, network};292 }293294 getTransactionStatus(data: {events: {event: IChainEvent}[], status: any}) {295 const {events, status} = data;296 if (status.isReady) {297 return this.transactionStatus.NOT_READY;298 }299 if (status.isBroadcast) {300 return this.transactionStatus.NOT_READY;301 }302 if (status.isInBlock || status.isFinalized) {303 const errors = events.filter(e => e.event.data.method === 'ExtrinsicFailed');304 if (errors.length > 0) {305 return this.transactionStatus.FAIL;306 }307 if (events.filter(e => e.event.data.method === 'ExtrinsicSuccess').length > 0) {308 return this.transactionStatus.SUCCESS;309 }310 }311312 return this.transactionStatus.FAIL;313 }314315 signTransaction(sender: TSigner, transaction: any, label = 'transaction', options: any = null) {316 const sign = (callback: any) => {317 if(options !== null) return transaction.signAndSend(sender, options, callback);318 return transaction.signAndSend(sender, callback);319 };320 return new Promise(async (resolve, reject) => {321 try {322 const unsub = await sign((result: any) => {323 const status = this.getTransactionStatus(result);324325 if (status === this.transactionStatus.SUCCESS) {326 this.logger.log(`${label} successful`);327 unsub();328 resolve({result, status});329 } else if (status === this.transactionStatus.FAIL) {330 let moduleError = null;331332 if (result.hasOwnProperty('dispatchError')) {333 const dispatchError = result['dispatchError'];334335 if (dispatchError && dispatchError.isModule) {336 const modErr = dispatchError.asModule;337 const errorMeta = dispatchError.registry.findMetaError(modErr);338339 moduleError = `${errorMeta.section}.${errorMeta.name}`;340 }341 else {342 this.logger.log(result, this.logger.level.ERROR);343 }344 }345346 this.logger.log(`Something went wrong with ${label}. Status: ${status}`, this.logger.level.ERROR);347 unsub();348 reject({status, moduleError, result});349 }350 });351 } catch (e) {352 this.logger.log(e, this.logger.level.ERROR);353 reject(e);354 }355 });356 }357358 constructApiCall(apiCall: string, params: any[]) {359 if(!apiCall.startsWith('api.')) throw Error(`Invalid api call: ${apiCall}`);360 let call = this.api as any;361 for(const part of apiCall.slice(4).split('.')) {362 call = call[part];363 }364 return call(...params);365 }366367 async executeExtrinsic(sender: TSigner, extrinsic: string, params: any[], expectSuccess=false) {368 if(this.api === null) throw Error('API not initialized');369 if(!extrinsic.startsWith('api.tx.')) throw Error(`${extrinsic} is not transaction`);370371 const startTime = (new Date()).getTime();372 let result: ITransactionResult;373 let events = [];374 try {375 result = await this.signTransaction(sender, this.constructApiCall(extrinsic, params), extrinsic) as ITransactionResult;376 events = result.result.events.map((x: any) => x.toHuman());377 }378 catch(e) {379 if(!(e as object).hasOwnProperty('status')) throw e;380 result = e as ITransactionResult;381 }382383 const endTime = (new Date()).getTime();384385 const log = {386 executedAt: endTime,387 executionTime: endTime - startTime,388 type: this.chainLogType.EXTRINSIC,389 status: result.status,390 call: extrinsic,391 params,392 } as IUniqueHelperLog;393394 if(result.status !== this.transactionStatus.SUCCESS && result.moduleError) log.moduleError = result.moduleError;395 if(events.length > 0) log.events = events;396397 this.chainLog.push(log);398399 if(expectSuccess && result.status !== this.transactionStatus.SUCCESS) throw Error(`${result.moduleError}`);400 return result;401 }402403 async callRpc(rpc: string, params?: any[]) {404 if(typeof params === 'undefined') params = [];405 if(this.api === null) throw Error('API not initialized');406 if(!rpc.startsWith('api.rpc.') && !rpc.startsWith('api.query.')) throw Error(`${rpc} is not RPC call`);407408 const startTime = (new Date()).getTime();409 let result;410 let error = null;411 const log = {412 type: this.chainLogType.RPC,413 call: rpc,414 params,415 } as IUniqueHelperLog;416417 try {418 result = await this.constructApiCall(rpc, params);419 }420 catch(e) {421 error = e;422 }423424 const endTime = (new Date()).getTime();425426 log.executedAt = endTime;427 log.status = (error === null ? this.transactionStatus.SUCCESS : this.transactionStatus.FAIL) as 'Fail' | 'Success';428 log.executionTime = endTime - startTime;429430 this.chainLog.push(log);431432 if(error !== null) throw error;433434 return result;435 }436437 getSignerAddress(signer: IKeyringPair | string): string {438 if(typeof signer === 'string') return signer;439 return signer.address;440 }441}442443444class HelperGroup {445 helper: UniqueHelper;446447 constructor(uniqueHelper: UniqueHelper) {448 this.helper = uniqueHelper;449 }450}451452453class CollectionGroup extends HelperGroup {454 455456457458459460461462463 async getTokenNextSponsored(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<number | null> {464 return (await this.helper.callRpc('api.rpc.unique.nextSponsored', [collectionId, addressObj, tokenId])).toJSON();465 }466467 468469470471472 async getTotalCount(): Promise<number> {473 return (await this.helper.callRpc('api.rpc.unique.collectionStats')).created.toNumber();474 }475476 477478479480481482483 async getData(collectionId: number): Promise<{484 id: number;485 name: string;486 description: string;487 tokensCount: number;488 admins: ICrossAccountId[];489 normalizedOwner: TSubstrateAccount;490 raw: any491 } | null> {492 const collection = await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId]);493 const humanCollection = collection.toHuman(), collectionData = {494 id: collectionId, name: null, description: null, tokensCount: 0, admins: [],495 raw: humanCollection,496 } as any, jsonCollection = collection.toJSON();497 if (humanCollection === null) return null;498 collectionData.raw.limits = jsonCollection.limits;499 collectionData.raw.permissions = jsonCollection.permissions;500 collectionData.normalizedOwner = this.helper.address.normalizeSubstrate(collectionData.raw.owner);501 for (const key of ['name', 'description']) {502 collectionData[key] = this.helper.util.vec2str(humanCollection[key]);503 }504505 collectionData.tokensCount = (['RFT', 'NFT'].includes(humanCollection.mode)) ? await this.helper[humanCollection.mode.toLocaleLowerCase() as 'nft' | 'rft'].getLastTokenId(collectionId) : 0;506 collectionData.admins = await this.getAdmins(collectionId);507508 return collectionData;509 }510511 512513514515516517518 async getAdmins(collectionId: number): Promise<ICrossAccountId[]> {519 const normalized = [];520 for(const admin of (await this.helper.callRpc('api.rpc.unique.adminlist', [collectionId])).toHuman()) {521 if(admin.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(admin.Substrate)});522 else normalized.push(admin);523 }524 return normalized;525 }526527 528529530531532533 async getAllowList(collectionId: number): Promise<ICrossAccountId[]> {534 const normalized = [];535 const allowListed = (await this.helper.callRpc('api.rpc.unique.allowlist', [collectionId])).toHuman();536 for (const address of allowListed) {537 if (address.Substrate) normalized.push({Substrate: this.helper.address.normalizeSubstrate(address.Substrate)});538 else normalized.push(address);539 }540 return normalized;541 }542543 544545546547548549550 async getEffectiveLimits(collectionId: number): Promise<ICollectionLimits> {551 return (await this.helper.callRpc('api.rpc.unique.effectiveCollectionLimits', [collectionId])).toJSON();552 }553554 555556557558559560561562 async burn(signer: TSigner, collectionId: number): Promise<boolean> {563 const result = await this.helper.executeExtrinsic(564 signer,565 'api.tx.unique.destroyCollection', [collectionId],566 true,567 );568569 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionDestroyed');570 }571572 573574575576577578579580581 async setSponsor(signer: TSigner, collectionId: number, sponsorAddress: TSubstrateAccount): Promise<boolean> {582 const result = await this.helper.executeExtrinsic(583 signer,584 'api.tx.unique.setCollectionSponsor', [collectionId, sponsorAddress],585 true,586 );587588 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionSponsorSet');589 }590591 592593594595596597598599 async confirmSponsorship(signer: TSigner, collectionId: number): Promise<boolean> {600 const result = await this.helper.executeExtrinsic(601 signer,602 'api.tx.unique.confirmSponsorship', [collectionId],603 true,604 );605606 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'SponsorshipConfirmed');607 }608609 610611612613614615616617618619620621622623624625626 async setLimits(signer: TSigner, collectionId: number, limits: ICollectionLimits): Promise<boolean> {627 const result = await this.helper.executeExtrinsic(628 signer,629 'api.tx.unique.setCollectionLimits', [collectionId, limits],630 true,631 );632633 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionLimitSet');634 }635636 637638639640641642643644645 async changeOwner(signer: TSigner, collectionId: number, ownerAddress: TSubstrateAccount): Promise<boolean> {646 const result = await this.helper.executeExtrinsic(647 signer,648 'api.tx.unique.changeCollectionOwner', [collectionId, ownerAddress],649 true,650 );651652 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionOwnedChanged');653 }654655 656657658659660661662663664 async addAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {665 const result = await this.helper.executeExtrinsic(666 signer,667 'api.tx.unique.addCollectionAdmin', [collectionId, adminAddressObj],668 true,669 );670671 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminAdded');672 }673674 675676677678679680681682683 async removeAdmin(signer: TSigner, collectionId: number, adminAddressObj: ICrossAccountId): Promise<boolean> {684 const result = await this.helper.executeExtrinsic(685 signer,686 'api.tx.unique.removeCollectionAdmin', [collectionId, adminAddressObj],687 true,688 );689690 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionAdminRemoved');691 }692693 694695696697698699700 async addToAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {701 const result = await this.helper.executeExtrinsic(702 signer,703 'api.tx.unique.addToAllowList', [collectionId, addressObj],704 true,705 );706707 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressAdded');708 }709710 711712713714715716717718 async removeFromAllowList(signer: TSigner, collectionId: number, addressObj: ICrossAccountId): Promise<boolean> {719 const result = await this.helper.executeExtrinsic(720 signer,721 'api.tx.unique.removeFromAllowList', [collectionId, addressObj],722 true,723 );724725 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'AllowListAddressRemoved');726 }727728 729730731732733734735736737 async setPermissions(signer: TSigner, collectionId: number, permissions: ICollectionPermissions): Promise<boolean> {738 const result = await this.helper.executeExtrinsic(739 signer,740 'api.tx.unique.setCollectionPermissions', [collectionId, permissions],741 true,742 );743744 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'unique', 'CollectionPermissionSet');745 }746747 748749750751752753754755756 async enableNesting(signer: TSigner, collectionId: number, permissions: INestingPermissions): Promise<boolean> {757 return await this.setPermissions(signer, collectionId, {nesting: permissions});758 }759760 761762763764765766767768 async disableNesting(signer: TSigner, collectionId: number): Promise<boolean> {769 return await this.setPermissions(signer, collectionId, {nesting: {tokenOwner: false, collectionAdmin: false}});770 }771772 773774775776777778779780781 async setProperties(signer: TSigner, collectionId: number, properties: IProperty[]): Promise<boolean> {782 const result = await this.helper.executeExtrinsic(783 signer,784 'api.tx.unique.setCollectionProperties', [collectionId, properties],785 true,786 );787788 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertySet');789 }790791 792793794795796797798799800 async deleteProperties(signer: TSigner, collectionId: number, propertyKeys: string[]): Promise<boolean> {801 const result = await this.helper.executeExtrinsic(802 signer,803 'api.tx.unique.deleteCollectionProperties', [collectionId, propertyKeys],804 true,805 );806807 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'CollectionPropertyDeleted');808 }809810 811812813814815816817818819820821 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {822 const result = await this.helper.executeExtrinsic(823 signer,824 'api.tx.unique.transfer', [addressObj, collectionId, tokenId, amount],825 true, 826 );827828 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, {Substrate: typeof signer === 'string' ? signer : signer.address}, addressObj, amount);829 }830831 832833834835836837838839840841842843844 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {845 const result = await this.helper.executeExtrinsic(846 signer,847 'api.tx.unique.transferFrom', [fromAddressObj, toAddressObj, collectionId, tokenId, amount],848 true, 849 );850 return this.helper.util.isTokenTransferSuccess(result.result.events, collectionId, tokenId, fromAddressObj, toAddressObj, amount);851 }852853 854855856857858859860861862863864 async burnToken(signer: TSigner, collectionId: number, tokenId: number, amount=1n): Promise<{865 success: boolean,866 token: number | null867 }> {868 const burnResult = await this.helper.executeExtrinsic(869 signer,870 'api.tx.unique.burnItem', [collectionId, tokenId, amount],871 true, 872 );873 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);874 if (burnedTokens.tokens.length > 1) throw Error('Burned multiple tokens');875 return {success: burnedTokens.success, token: burnedTokens.tokens.length > 0 ? burnedTokens.tokens[0] : null};876 }877878 879880881882883884885886887888889 async burnTokenFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, tokenId: number, amount=1n): Promise<boolean> {890 const burnResult = await this.helper.executeExtrinsic(891 signer,892 'api.tx.unique.burnFrom', [collectionId, fromAddressObj, tokenId, amount],893 true, 894 );895 const burnedTokens = this.helper.util.extractTokensFromBurnResult(burnResult);896 return burnedTokens.success && burnedTokens.tokens.length > 0;897 }898899 900901902903904905906907908909 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {910 const approveResult = await this.helper.executeExtrinsic(911 signer, 912 'api.tx.unique.approve', [toAddressObj, collectionId, tokenId, amount],913 true, 914 );915916 return this.helper.util.findCollectionInEvents(approveResult.result.events, collectionId, 'common', 'Approved');917 }918919 920921922923924925926927928929 async getTokenApprovedPieces(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId, fromAccountObj: ICrossAccountId): Promise<bigint> {930 return (await this.helper.callRpc('api.rpc.unique.allowance', [collectionId, fromAccountObj, toAccountObj, tokenId])).toBigInt();931 }932933 934935936937938939940 async getLastTokenId(collectionId: number): Promise<number> {941 return (await this.helper.callRpc('api.rpc.unique.lastTokenId', [collectionId])).toNumber();942 }943944 945946947948949950951952 async isTokenExists(collectionId: number, tokenId: number): Promise<boolean> {953 return (await this.helper.callRpc('api.rpc.unique.tokenExists', [collectionId, tokenId])).toJSON();954 }955}956957class NFTnRFT extends CollectionGroup {958 959960961962963964965966 async getTokensByAddress(collectionId: number, addressObj: ICrossAccountId): Promise<number[]> {967 return (await this.helper.callRpc('api.rpc.unique.accountTokens', [collectionId, addressObj])).toJSON();968 }969970 971972973974975976977978979980 async getToken(collectionId: number, tokenId: number, propertyKeys: string[] = [], blockHashAt?: string): Promise<{981 properties: IProperty[];982 owner: ICrossAccountId;983 normalizedOwner: ICrossAccountId;984 }| null> {985 let tokenData;986 if(typeof blockHashAt === 'undefined') {987 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId]);988 }989 else {990 if(propertyKeys.length == 0) {991 const collection = (await this.helper.callRpc('api.rpc.unique.collectionById', [collectionId])).toHuman();992 if(!collection) return null;993 propertyKeys = collection.tokenPropertyPermissions.map((x: ITokenPropertyPermission) => x.key);994 }995 tokenData = await this.helper.callRpc('api.rpc.unique.tokenData', [collectionId, tokenId, propertyKeys, blockHashAt]);996 }997 tokenData = tokenData.toHuman();998 if (tokenData === null || tokenData.owner === null) return null;999 const owner = {} as any;1000 for (const key of Object.keys(tokenData.owner)) {1001 owner[key.toLocaleLowerCase()] = key.toLocaleLowerCase() === 'substrate' ? this.helper.address.normalizeSubstrate(tokenData.owner[key]) : tokenData.owner[key];1002 }1003 tokenData.normalizedOwner = crossAccountIdFromLower(owner);1004 return tokenData;1005 }10061007 10081009101010111012101310141015101610171018 async setTokenPropertyPermissions(signer: TSigner, collectionId: number, permissions: ITokenPropertyPermission[]): Promise<boolean> {1019 const result = await this.helper.executeExtrinsic(1020 signer,1021 'api.tx.unique.setTokenPropertyPermissions', [collectionId, permissions],1022 true,1023 );10241025 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'PropertyPermissionSet');1026 }10271028 1029103010311032103310341035103610371038 async setTokenProperties(signer: TSigner, collectionId: number, tokenId: number, properties: IProperty[]): Promise<boolean> {1039 const result = await this.helper.executeExtrinsic(1040 signer,1041 'api.tx.unique.setTokenProperties', [collectionId, tokenId, properties],1042 true,1043 );10441045 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertySet');1046 }10471048 104910501051105210531054105510561057 async deleteTokenProperties(signer: TSigner, collectionId: number, tokenId: number, propertyKeys: string[]): Promise<boolean> {1058 const result = await this.helper.executeExtrinsic(1059 signer,1060 'api.tx.unique.deleteTokenProperties', [collectionId, tokenId, propertyKeys],1061 true,1062 );10631064 return this.helper.util.findCollectionInEvents(result.result.events, collectionId, 'common', 'TokenPropertyDeleted');1065 }10661067 106810691070107110721073107410751076 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, mode: 'NFT' | 'RFT'): Promise<UniqueCollectionBase> {1077 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1078 collectionOptions.mode = (mode === 'NFT') ? {nft: null} : {refungible: null};1079 for (const key of ['name', 'description', 'tokenPrefix']) {1080 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);1081 }1082 const creationResult = await this.helper.executeExtrinsic(1083 signer,1084 'api.tx.unique.createCollectionEx', [collectionOptions],1085 true, 1086 );1087 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1088 }10891090 getCollectionObject(collectionId: number): any {1091 return null;1092 }10931094 getTokenObject(collectionId: number, tokenId: number): any {1095 return null;1096 }1097}109810991100class NFTGroup extends NFTnRFT {1101 110211031104110511061107 getCollectionObject(collectionId: number): UniqueNFTCollection {1108 return new UniqueNFTCollection(collectionId, this.helper);1109 }11101111 1112111311141115111611171118 getTokenObject(collectionId: number, tokenId: number): UniqueNFTToken {1119 return new UniqueNFTToken(tokenId, this.getCollectionObject(collectionId));1120 }11211122 11231124112511261127112811291130 async getTokenOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId> {1131 let owner;1132 if (typeof blockHashAt === 'undefined') {1133 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId]);1134 } else {1135 owner = await this.helper.callRpc('api.rpc.unique.tokenOwner', [collectionId, tokenId, blockHashAt]);1136 }1137 return crossAccountIdFromLower(owner.toJSON());1138 }11391140 1141114211431144114511461147 async isTokenApproved(collectionId: number, tokenId: number, toAccountObj: ICrossAccountId): Promise<boolean> {1148 return (await this.getTokenApprovedPieces(collectionId, tokenId, toAccountObj, await this.getTokenOwner(collectionId, tokenId))) === 1n;1149 }11501151 1152115311541155115611571158115911601161 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<boolean> {1162 return await super.transferToken(signer, collectionId, tokenId, addressObj, 1n);1163 }11641165 116611671168116911701171117211731174117511761177 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId): Promise<boolean> {1178 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, 1n);1179 }11801181 11821183118411851186118711881189 async getTokenTopmostOwner(collectionId: number, tokenId: number, blockHashAt?: string): Promise<ICrossAccountId | null> {1190 let owner;1191 if (typeof blockHashAt === 'undefined') {1192 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId]);1193 } else {1194 owner = await this.helper.callRpc('api.rpc.unique.topmostTokenOwner', [collectionId, tokenId, blockHashAt]);1195 }11961197 if (owner === null) return null;11981199 owner = owner.toHuman();12001201 return owner.Substrate ? {Substrate: this.helper.address.normalizeSubstrate(owner.Substrate)} : owner;1202 }12031204 12051206120712081209121012111212 async getTokenChildren(collectionId: number, tokenId: number, blockHashAt?: string): Promise<IToken[]> {1213 let children;1214 if(typeof blockHashAt === 'undefined') {1215 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId]);1216 } else {1217 children = await this.helper.callRpc('api.rpc.unique.tokenChildren', [collectionId, tokenId, blockHashAt]);1218 }12191220 return children.toJSON().map((x: any) => {1221 return {collectionId: x.collection, tokenId: x.token};1222 });1223 }12241225 12261227122812291230123112321233 async nestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken): Promise<boolean> {1234 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1235 const result = await this.transferToken(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress);1236 if(!result) {1237 throw Error('Unable to nest token!');1238 }1239 return result;1240 }12411242 124312441245124612471248124912501251 async unnestToken(signer: TSigner, tokenObj: IToken, rootTokenObj: IToken, toAddressObj: ICrossAccountId): Promise<boolean> {1252 const rootTokenAddress = {Ethereum: this.helper.util.getNestingTokenAddress(rootTokenObj.collectionId, rootTokenObj.tokenId)};1253 const result = await this.transferTokenFrom(signer, tokenObj.collectionId, tokenObj.tokenId, rootTokenAddress, toAddressObj);1254 if(!result) {1255 throw Error('Unable to unnest token!');1256 }1257 return result;1258 }12591260 126112621263126412651266126712681269127012711272 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueNFTCollection> {1273 return await super.mintCollection(signer, collectionOptions, 'NFT') as UniqueNFTCollection;1274 }12751276 127712781279128012811282 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; properties?: IProperty[]; }): Promise<UniqueNFTToken> {1283 const creationResult = await this.helper.executeExtrinsic(1284 signer,1285 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1286 nft: {1287 properties: data.properties,1288 },1289 }],1290 true,1291 );1292 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1293 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1294 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1295 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1296 }12971298 129913001301130213031304130513061307130813091310131113121313 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1314 const creationResult = await this.helper.executeExtrinsic(1315 signer,1316 'api.tx.unique.createMultipleItemsEx', [collectionId, {NFT: tokens}],1317 true,1318 );1319 const collection = this.getCollectionObject(collectionId);1320 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1321 }13221323 132413251326132713281329133013311332133313341335133613371338133913401341 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {properties?: IProperty[]}[]): Promise<UniqueNFTToken[]> {1342 const rawTokens = [];1343 for (const token of tokens) {1344 const raw = {NFT: {properties: token.properties}};1345 rawTokens.push(raw);1346 }1347 const creationResult = await this.helper.executeExtrinsic(1348 signer,1349 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1350 true,1351 );1352 const collection = this.getCollectionObject(collectionId);1353 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1354 }13551356 13571358135913601361136213631364 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number): Promise<{ success: boolean; token: number | null; }> {1365 return await super.burnToken(signer, collectionId, tokenId, 1n);1366 }13671368 1369137013711372137313741375137613771378 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId) {1379 return super.approveToken(signer, collectionId, tokenId, toAddressObj, 1n);1380 }1381}138213831384class RFTGroup extends NFTnRFT {1385 138613871388138913901391 getCollectionObject(collectionId: number): UniqueRFTCollection {1392 return new UniqueRFTCollection(collectionId, this.helper);1393 }13941395 1396139713981399140014011402 getTokenObject(collectionId: number, tokenId: number): UniqueRFTToken {1403 return new UniqueRFTToken(tokenId, this.getCollectionObject(collectionId));1404 }14051406 1407140814091410141114121413 async getTokenTop10Owners(collectionId: number, tokenId: number): Promise<ICrossAccountId[]> {1414 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, tokenId])).toJSON().map(crossAccountIdFromLower);1415 }14161417 14181419142014211422142314241425 async getTokenBalance(collectionId: number, tokenId: number, addressObj: ICrossAccountId): Promise<bigint> {1426 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, tokenId])).toBigInt();1427 }14281429 1430143114321433143414351436143714381439 async transferToken(signer: TSigner, collectionId: number, tokenId: number, addressObj: ICrossAccountId, amount=1n): Promise<boolean> {1440 return await super.transferToken(signer, collectionId, tokenId, addressObj, amount);1441 }14421443 14441445144614471448144914501451145214531454 async transferTokenFrom(signer: TSigner, collectionId: number, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1455 return await super.transferTokenFrom(signer, collectionId, tokenId, fromAddressObj, toAddressObj, amount);1456 }14571458 145914601461146214631464146514661467146814691470 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions): Promise<UniqueRFTCollection> {1471 return await super.mintCollection(signer, collectionOptions, 'RFT') as UniqueRFTCollection;1472 }14731474 1475147614771478147914801481 async mintToken(signer: TSigner, data: { collectionId: number; owner: ICrossAccountId | string; pieces: bigint; properties?: IProperty[]; }): Promise<UniqueRFTToken> {1482 const creationResult = await this.helper.executeExtrinsic(1483 signer,1484 'api.tx.unique.createItem', [data.collectionId, (typeof data.owner === 'string') ? {Substrate: data.owner} : data.owner, {1485 refungible: {1486 pieces: data.pieces,1487 properties: data.properties,1488 },1489 }],1490 true,1491 );1492 const createdTokens = this.helper.util.extractTokensFromCreationResult(creationResult);1493 if (createdTokens.tokens.length > 1) throw Error('Minted multiple tokens');1494 if (createdTokens.tokens.length < 1) throw Error('No tokens minted');1495 return this.getTokenObject(data.collectionId, createdTokens.tokens[0].tokenId);1496 }14971498 async mintMultipleTokens(signer: TSigner, collectionId: number, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1499 throw Error('Not implemented');1500 const creationResult = await this.helper.executeExtrinsic(1501 signer,1502 'api.tx.unique.createMultipleItemsEx', [collectionId, {RefungibleMultipleOwners: tokens}],1503 true, 1504 );1505 const collection = this.getCollectionObject(collectionId);1506 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1507 }15081509 151015111512151315141515151615171518 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {pieces: bigint, properties?: IProperty[]}[]): Promise<UniqueRFTToken[]> {1519 const rawTokens = [];1520 for (const token of tokens) {1521 const raw = {ReFungible: {pieces: token.pieces, properties: token.properties}};1522 rawTokens.push(raw);1523 }1524 const creationResult = await this.helper.executeExtrinsic(1525 signer,1526 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1527 true,1528 );1529 const collection = this.getCollectionObject(collectionId);1530 return this.helper.util.extractTokensFromCreationResult(creationResult).tokens.map((x: IToken) => collection.getTokenObject(x.tokenId));1531 }15321533 153415351536153715381539154015411542 async burnToken(signer: IKeyringPair, collectionId: number, tokenId: number, amount=1n): Promise<{ success: boolean; token: number | null; }> {1543 return await super.burnToken(signer, collectionId, tokenId, amount);1544 }15451546 15471548154915501551155215531554155515561557 async approveToken(signer: IKeyringPair, collectionId: number, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {1558 return super.approveToken(signer, collectionId, tokenId, toAddressObj, amount);1559 }15601561 1562156315641565156615671568 async getTokenTotalPieces(collectionId: number, tokenId: number): Promise<bigint> {1569 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, tokenId])).unwrap().toBigInt();1570 }15711572 157315741575157615771578157915801581 async repartitionToken(signer: TSigner, collectionId: number, tokenId: number, amount: bigint): Promise<boolean> {1582 const currentAmount = await this.getTokenTotalPieces(collectionId, tokenId);1583 const repartitionResult = await this.helper.executeExtrinsic(1584 signer,1585 'api.tx.unique.repartition', [collectionId, tokenId, amount],1586 true,1587 );1588 if(currentAmount < amount) return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemCreated');1589 return this.helper.util.findCollectionInEvents(repartitionResult.result.events, collectionId, 'common', 'ItemDestroyed');1590 }1591}159215931594class FTGroup extends CollectionGroup {1595 159615971598159916001601 getCollectionObject(collectionId: number): UniqueFTCollection {1602 return new UniqueFTCollection(collectionId, this.helper);1603 }16041605 1606160716081609161016111612161316141615161616171618 async mintCollection(signer: TSigner, collectionOptions: ICollectionCreationOptions, decimalPoints = 0): Promise<UniqueFTCollection> {1619 collectionOptions = JSON.parse(JSON.stringify(collectionOptions)) as ICollectionCreationOptions; 1620 if(collectionOptions.tokenPropertyPermissions) throw Error('Fungible collections has no tokenPropertyPermissions');1621 collectionOptions.mode = {fungible: decimalPoints};1622 for (const key of ['name', 'description', 'tokenPrefix']) {1623 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);1624 }1625 const creationResult = await this.helper.executeExtrinsic(1626 signer,1627 'api.tx.unique.createCollectionEx', [collectionOptions],1628 true,1629 );1630 return this.getCollectionObject(this.helper.util.extractCollectionIdFromCreationResult(creationResult));1631 }16321633 163416351636163716381639164016411642 async mintTokens(signer: TSigner, collectionId: number, owner: ICrossAccountId | string, amount: bigint): Promise<boolean> {1643 const creationResult = await this.helper.executeExtrinsic(1644 signer,1645 'api.tx.unique.createItem', [collectionId, (typeof owner === 'string') ? {Substrate: owner} : owner, {1646 fungible: {1647 value: amount,1648 },1649 }],1650 true, 1651 );1652 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1653 }16541655 16561657165816591660166116621663 async mintMultipleTokensWithOneOwner(signer: TSigner, collectionId: number, owner: ICrossAccountId, tokens: {value: bigint}[]): Promise<boolean> {1664 const rawTokens = [];1665 for (const token of tokens) {1666 const raw = {Fungible: {Value: token.value}};1667 rawTokens.push(raw);1668 }1669 const creationResult = await this.helper.executeExtrinsic(1670 signer,1671 'api.tx.unique.createMultipleItems', [collectionId, owner, rawTokens],1672 true,1673 );1674 return this.helper.util.findCollectionInEvents(creationResult.result.events, collectionId, 'common', 'ItemCreated');1675 }16761677 167816791680168116821683 async getTop10Owners(collectionId: number): Promise<ICrossAccountId[]> {1684 return (await this.helper.callRpc('api.rpc.unique.tokenOwners', [collectionId, 0])).toJSON().map(crossAccountIdFromLower);1685 }16861687 1688168916901691169216931694 async getBalance(collectionId: number, addressObj: ICrossAccountId): Promise<bigint> {1695 return (await this.helper.callRpc('api.rpc.unique.balance', [collectionId, addressObj, 0])).toBigInt();1696 }16971698 169917001701170217031704170517061707 async transfer(signer: TSigner, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1708 return await super.transferToken(signer, collectionId, 0, toAddressObj, amount);1709 }17101711 1712171317141715171617171718171917201721 async transferFrom(signer: TSigner, collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {1722 return await super.transferTokenFrom(signer, collectionId, 0, fromAddressObj, toAddressObj, amount);1723 }17241725 17261727172817291730173117321733 async burnTokens(signer: IKeyringPair, collectionId: number, amount=1n): Promise<boolean> {1734 return (await super.burnToken(signer, collectionId, 0, amount)).success;1735 }17361737 173817391740174117421743174417451746 async burnTokensFrom(signer: IKeyringPair, collectionId: number, fromAddressObj: ICrossAccountId, amount=1n): Promise<boolean> {1747 return await super.burnTokenFrom(signer, collectionId, fromAddressObj, 0, amount);1748 }17491750 17511752175317541755 async getTotalPieces(collectionId: number): Promise<bigint> {1756 return (await this.helper.callRpc('api.rpc.unique.totalPieces', [collectionId, 0])).unwrap().toBigInt();1757 }17581759 1760176117621763176417651766176717681769 async approveTokens(signer: IKeyringPair, collectionId: number, toAddressObj: ICrossAccountId, amount=1n) {1770 return super.approveToken(signer, collectionId, 0, toAddressObj, amount);1771 }17721773 1774177517761777177817791780 async getApprovedTokens(collectionId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {1781 return super.getTokenApprovedPieces(collectionId, 0, toAddressObj, fromAddressObj);1782 }1783}178417851786class ChainGroup extends HelperGroup {1787 17881789179017911792 getChainProperties(): IChainProperties {1793 const properties = (this.helper.api as any).registry.getChainProperties().toJSON();1794 return {1795 ss58Format: properties.ss58Format.toJSON(),1796 tokenDecimals: properties.tokenDecimals.toJSON(),1797 tokenSymbol: properties.tokenSymbol.toJSON(),1798 };1799 }18001801 18021803180418051806 async getLatestBlockNumber(): Promise<number> {1807 return (await this.helper.callRpc('api.rpc.chain.getHeader')).number.toNumber();1808 }18091810 181118121813181418151816 async getBlockHashByNumber(blockNumber: number): Promise<string | null> {1817 const blockHash = (await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockNumber])).toJSON();1818 if(blockHash === '0x0000000000000000000000000000000000000000000000000000000000000000') return null;1819 return blockHash;1820 }18211822 182318241825182618271828 async getNonce(address: TSubstrateAccount): Promise<number> {1829 return (await (this.helper.api as any).query.system.account(address)).nonce.toNumber();1830 }1831}183218331834class BalanceGroup extends HelperGroup {1835 18361837183818391840 getOneTokenNominal(): bigint {1841 const chainProperties = this.helper.chain.getChainProperties();1842 return 10n ** BigInt((chainProperties.tokenDecimals || [18])[0]);1843 }18441845 184618471848184918501851 async getSubstrate(address: TSubstrateAccount): Promise<bigint> {1852 return (await this.helper.callRpc('api.query.system.account', [address])).data.free.toBigInt();1853 }18541855 185618571858185918601861 async getEthereum(address: TEthereumAccount): Promise<bigint> {1862 return (await this.helper.callRpc('api.rpc.eth.getBalance', [address])).toBigInt();1863 }18641865 18661867186818691870187118721873 async transferToSubstrate(signer: TSigner, address: TSubstrateAccount, amount: bigint | string): Promise<boolean> {1874 const result = await this.helper.executeExtrinsic(signer, 'api.tx.balances.transfer', [address, amount], true);18751876 let transfer = {from: null, to: null, amount: 0n} as any;1877 result.result.events.forEach(({event: {data, method, section}}) => {1878 if ((section === 'balances') && (method === 'Transfer')) {1879 transfer = {1880 from: this.helper.address.normalizeSubstrate(data[0]),1881 to: this.helper.address.normalizeSubstrate(data[1]),1882 amount: BigInt(data[2]),1883 };1884 }1885 });1886 let isSuccess = this.helper.address.normalizeSubstrate(typeof signer === 'string' ? signer : signer.address) === transfer.from;1887 isSuccess = isSuccess && this.helper.address.normalizeSubstrate(address) === transfer.to;1888 isSuccess = isSuccess && BigInt(amount) === transfer.amount;1889 return isSuccess;1890 }1891}189218931894class AddressGroup extends HelperGroup {1895 1896189718981899190019011902 normalizeSubstrate(address: TSubstrateAccount, ss58Format = 42): TSubstrateAccount {1903 return this.helper.util.normalizeSubstrateAddress(address, ss58Format);1904 }19051906 190719081909191019111912 async normalizeSubstrateToChainFormat(address: TSubstrateAccount): Promise<TSubstrateAccount> {1913 const info = this.helper.chain.getChainProperties();1914 return encodeAddress(decodeAddress(address), info.ss58Format);1915 }19161917 1918191919201921192219231924 async ethToSubstrate(ethAddress: TEthereumAccount, toChainFormat=false): Promise<TSubstrateAccount> {1925 if(!toChainFormat) return evmToAddress(ethAddress);1926 const info = this.helper.chain.getChainProperties();1927 return evmToAddress(ethAddress, info.ss58Format);1928 }19291930 193119321933193419351936 substrateToEth(subAddress: TSubstrateAccount): TEthereumAccount {1937 return nesting.toChecksumAddress('0x' + Array.from(addressToEvm(subAddress), i => i.toString(16).padStart(2, '0')).join(''));1938 }1939}194019411942export class UniqueHelper extends ChainHelperBase {1943 chain: ChainGroup;1944 balance: BalanceGroup;1945 address: AddressGroup;1946 collection: CollectionGroup;1947 nft: NFTGroup;1948 rft: RFTGroup;1949 ft: FTGroup;19501951 constructor(logger?: ILogger) {1952 super(logger);1953 this.chain = new ChainGroup(this);1954 this.balance = new BalanceGroup(this);1955 this.address = new AddressGroup(this);1956 this.collection = new CollectionGroup(this);1957 this.nft = new NFTGroup(this);1958 this.rft = new RFTGroup(this);1959 this.ft = new FTGroup(this);1960 } 1961}196219631964class UniqueCollectionBase {1965 helper: UniqueHelper;1966 collectionId: number;19671968 constructor(collectionId: number, uniqueHelper: UniqueHelper) {1969 this.collectionId = collectionId;1970 this.helper = uniqueHelper;1971 }19721973 async getData() {1974 return await this.helper.collection.getData(this.collectionId);1975 }19761977 async getLastTokenId() {1978 return await this.helper.collection.getLastTokenId(this.collectionId);1979 }19801981 async isTokenExists(tokenId: number) {1982 return await this.helper.collection.isTokenExists(this.collectionId, tokenId);1983 }19841985 async getAdmins() {1986 return await this.helper.collection.getAdmins(this.collectionId);1987 }19881989 async getAllowList() {1990 return await this.helper.collection.getAllowList(this.collectionId);1991 }19921993 async getEffectiveLimits() {1994 return await this.helper.collection.getEffectiveLimits(this.collectionId);1995 }19961997 async setSponsor(signer: TSigner, sponsorAddress: TSubstrateAccount) {1998 return await this.helper.collection.setSponsor(signer, this.collectionId, sponsorAddress);1999 }20002001 async confirmSponsorship(signer: TSigner) {2002 return await this.helper.collection.confirmSponsorship(signer, this.collectionId);2003 }20042005 async setLimits(signer: TSigner, limits: ICollectionLimits) {2006 return await this.helper.collection.setLimits(signer, this.collectionId, limits);2007 }20082009 async changeOwner(signer: TSigner, ownerAddress: TSubstrateAccount) {2010 return await this.helper.collection.changeOwner(signer, this.collectionId, ownerAddress);2011 }20122013 async addAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2014 return await this.helper.collection.addAdmin(signer, this.collectionId, adminAddressObj);2015 }20162017 async enableAllowList(signer: TSigner, value = true) {2018 return await this.setPermissions(signer, value ? {access: 'AllowList', mintMode: true} : {access: 'Normal'});2019 }20202021 async addToAllowList(signer: TSigner, addressObj: ICrossAccountId) {2022 return await this.helper.collection.addToAllowList(signer, this.collectionId, addressObj);2023 }20242025 async removeFromAllowList(signer: TSigner, addressObj: ICrossAccountId) {2026 return await this.helper.collection.removeFromAllowList(signer, this.collectionId, addressObj);2027 }20282029 async removeAdmin(signer: TSigner, adminAddressObj: ICrossAccountId) {2030 return await this.helper.collection.removeAdmin(signer, this.collectionId, adminAddressObj);2031 }20322033 async setProperties(signer: TSigner, properties: IProperty[]) {2034 return await this.helper.collection.setProperties(signer, this.collectionId, properties);2035 }20362037 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2038 return await this.helper.collection.deleteProperties(signer, this.collectionId, propertyKeys);2039 }20402041 async getTokenNextSponsored(tokenId: number, addressObj: ICrossAccountId) {2042 return await this.helper.collection.getTokenNextSponsored(this.collectionId, tokenId, addressObj);2043 }20442045 async setPermissions(signer: TSigner, permissions: ICollectionPermissions) {2046 return await this.helper.collection.setPermissions(signer, this.collectionId, permissions);2047 }20482049 async enableNesting(signer: TSigner, permissions: INestingPermissions) {2050 return await this.helper.collection.enableNesting(signer, this.collectionId, permissions);2051 }20522053 async disableNesting(signer: TSigner) {2054 return await this.helper.collection.disableNesting(signer, this.collectionId);2055 }20562057 async burn(signer: TSigner) {2058 return await this.helper.collection.burn(signer, this.collectionId);2059 }2060}206120622063class UniqueNFTCollection extends UniqueCollectionBase {2064 getTokenObject(tokenId: number) {2065 return new UniqueNFTToken(tokenId, this);2066 }20672068 async getTokensByAddress(addressObj: ICrossAccountId) {2069 return await this.helper.nft.getTokensByAddress(this.collectionId, addressObj);2070 }20712072 async getToken(tokenId: number, blockHashAt?: string) {2073 return await this.helper.nft.getToken(this.collectionId, tokenId, [], blockHashAt);2074 }20752076 async getTokenOwner(tokenId: number, blockHashAt?: string) {2077 return await this.helper.nft.getTokenOwner(this.collectionId, tokenId, blockHashAt);2078 }20792080 async getTokenTopmostOwner(tokenId: number, blockHashAt?: string) {2081 return await this.helper.nft.getTokenTopmostOwner(this.collectionId, tokenId, blockHashAt);2082 }20832084 async getTokenChildren(tokenId: number, blockHashAt?: string) {2085 return await this.helper.nft.getTokenChildren(this.collectionId, tokenId, blockHashAt);2086 }20872088 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId) {2089 return await this.helper.nft.transferToken(signer, this.collectionId, tokenId, addressObj);2090 }20912092 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2093 return await this.helper.nft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj);2094 }20952096 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId) {2097 return await this.helper.nft.approveToken(signer, this.collectionId, tokenId, toAddressObj);2098 }20992100 async isTokenApproved(tokenId: number, toAddressObj: ICrossAccountId) {2101 return await this.helper.nft.isTokenApproved(this.collectionId, tokenId, toAddressObj);2102 }21032104 async mintToken(signer: TSigner, owner: ICrossAccountId, properties?: IProperty[]) {2105 return await this.helper.nft.mintToken(signer, {collectionId: this.collectionId, owner, properties});2106 }21072108 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, properties?: IProperty[]}[]) {2109 return await this.helper.nft.mintMultipleTokens(signer, this.collectionId, tokens);2110 }21112112 async burnToken(signer: TSigner, tokenId: number) {2113 return await this.helper.nft.burnToken(signer, this.collectionId, tokenId);2114 }21152116 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2117 return await this.helper.nft.setTokenProperties(signer, this.collectionId, tokenId, properties);2118 }21192120 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2121 return await this.helper.nft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2122 }21232124 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2125 return await this.helper.nft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2126 }21272128 async nestToken(signer: TSigner, tokenId: number, toTokenObj: IToken) {2129 return await this.helper.nft.nestToken(signer, {collectionId: this.collectionId, tokenId}, toTokenObj);2130 }21312132 async unnestToken(signer: TSigner, tokenId: number, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2133 return await this.helper.nft.unnestToken(signer, {collectionId: this.collectionId, tokenId}, fromTokenObj, toAddressObj);2134 }2135}213621372138class UniqueRFTCollection extends UniqueCollectionBase {2139 getTokenObject(tokenId: number) {2140 return new UniqueRFTToken(tokenId, this);2141 }21422143 async getTokensByAddress(addressObj: ICrossAccountId) {2144 return await this.helper.rft.getTokensByAddress(this.collectionId, addressObj);2145 }21462147 async getTop10TokenOwners(tokenId: number) {2148 return await this.helper.rft.getTokenTop10Owners(this.collectionId, tokenId);2149 }21502151 async getTokenBalance(tokenId: number, addressObj: ICrossAccountId) {2152 return await this.helper.rft.getTokenBalance(this.collectionId, tokenId, addressObj);2153 }21542155 async getTokenTotalPieces(tokenId: number) {2156 return await this.helper.rft.getTokenTotalPieces(this.collectionId, tokenId);2157 }21582159 async transferToken(signer: TSigner, tokenId: number, addressObj: ICrossAccountId, amount=1n) {2160 return await this.helper.rft.transferToken(signer, this.collectionId, tokenId, addressObj, amount);2161 }21622163 async transferTokenFrom(signer: TSigner, tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2164 return await this.helper.rft.transferTokenFrom(signer, this.collectionId, tokenId, fromAddressObj, toAddressObj, amount);2165 }21662167 async approveToken(signer: TSigner, tokenId: number, toAddressObj: ICrossAccountId, amount=1n) {2168 return await this.helper.rft.approveToken(signer, this.collectionId, tokenId, toAddressObj, amount);2169 }21702171 async getTokenApprovedPieces(tokenId: number, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2172 return await this.helper.rft.getTokenApprovedPieces(this.collectionId, tokenId, toAddressObj, fromAddressObj);2173 }21742175 async repartitionToken(signer: TSigner, tokenId: number, amount: bigint) {2176 return await this.helper.rft.repartitionToken(signer, this.collectionId, tokenId, amount);2177 }21782179 async mintToken(signer: TSigner, owner: ICrossAccountId, pieces=100n, properties?: IProperty[]) {2180 return await this.helper.rft.mintToken(signer, {collectionId: this.collectionId, owner, pieces, properties});2181 }21822183 async mintMultipleTokens(signer: TSigner, tokens: {owner: ICrossAccountId, pieces: bigint, properties?: IProperty[]}[]) {2184 return await this.helper.rft.mintMultipleTokens(signer, this.collectionId, tokens);2185 }21862187 async burnToken(signer: TSigner, tokenId: number, amount=1n) {2188 return await this.helper.rft.burnToken(signer, this.collectionId, tokenId, amount);2189 }21902191 async setTokenProperties(signer: TSigner, tokenId: number, properties: IProperty[]) {2192 return await this.helper.rft.setTokenProperties(signer, this.collectionId, tokenId, properties);2193 }21942195 async deleteTokenProperties(signer: TSigner, tokenId: number, propertyKeys: string[]) {2196 return await this.helper.rft.deleteTokenProperties(signer, this.collectionId, tokenId, propertyKeys);2197 }21982199 async setTokenPropertyPermissions(signer: TSigner, permissions: ITokenPropertyPermission[]) {2200 return await this.helper.rft.setTokenPropertyPermissions(signer, this.collectionId, permissions);2201 }2202}220322042205class UniqueFTCollection extends UniqueCollectionBase {2206 async mint(signer: TSigner, owner: ICrossAccountId, amount: bigint) {2207 return await this.helper.ft.mintTokens(signer, this.collectionId, owner, amount);2208 }22092210 async mintWithOneOwner(signer: TSigner, owner: ICrossAccountId, tokens: {value: bigint}[]) {2211 return await this.helper.ft.mintMultipleTokensWithOneOwner(signer, this.collectionId, owner, tokens);2212 }22132214 async getBalance(addressObj: ICrossAccountId) {2215 return await this.helper.ft.getBalance(this.collectionId, addressObj);2216 }22172218 async getTop10Owners() {2219 return await this.helper.ft.getTop10Owners(this.collectionId);2220 }22212222 async transfer(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2223 return await this.helper.ft.transfer(signer, this.collectionId, toAddressObj, amount);2224 }22252226 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2227 return await this.helper.ft.transferFrom(signer, this.collectionId, fromAddressObj, toAddressObj, amount);2228 }22292230 async burnTokens(signer: TSigner, amount=1n) {2231 return await this.helper.ft.burnTokens(signer, this.collectionId, amount);2232 }22332234 async burnTokensFrom(signer: TSigner, fromAddressObj: ICrossAccountId, amount=1n) {2235 return await this.helper.ft.burnTokensFrom(signer, this.collectionId, fromAddressObj, amount);2236 }22372238 async getTotalPieces() {2239 return await this.helper.ft.getTotalPieces(this.collectionId);2240 }22412242 async approveTokens(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2243 return await this.helper.ft.approveTokens(signer, this.collectionId, toAddressObj, amount);2244 }22452246 async getApprovedTokens(fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2247 return await this.helper.ft.getApprovedTokens(this.collectionId, fromAddressObj, toAddressObj);2248 }2249}225022512252class UniqueTokenBase implements IToken {2253 collection: UniqueNFTCollection | UniqueRFTCollection;2254 collectionId: number;2255 tokenId: number;22562257 constructor(tokenId: number, collection: UniqueNFTCollection | UniqueRFTCollection) {2258 this.collection = collection;2259 this.collectionId = collection.collectionId;2260 this.tokenId = tokenId;2261 }22622263 async getNextSponsored(addressObj: ICrossAccountId) {2264 return await this.collection.getTokenNextSponsored(this.tokenId, addressObj);2265 }22662267 async setProperties(signer: TSigner, properties: IProperty[]) {2268 return await this.collection.setTokenProperties(signer, this.tokenId, properties);2269 }22702271 async deleteProperties(signer: TSigner, propertyKeys: string[]) {2272 return await this.collection.deleteTokenProperties(signer, this.tokenId, propertyKeys);2273 }2274}227522762277class UniqueNFTToken extends UniqueTokenBase {2278 collection: UniqueNFTCollection;22792280 constructor(tokenId: number, collection: UniqueNFTCollection) {2281 super(tokenId, collection);2282 this.collection = collection;2283 }22842285 async getData(blockHashAt?: string) {2286 return await this.collection.getToken(this.tokenId, blockHashAt);2287 }22882289 async getOwner(blockHashAt?: string) {2290 return await this.collection.getTokenOwner(this.tokenId, blockHashAt);2291 }22922293 async getTopmostOwner(blockHashAt?: string) {2294 return await this.collection.getTokenTopmostOwner(this.tokenId, blockHashAt);2295 }22962297 async getChildren(blockHashAt?: string) {2298 return await this.collection.getTokenChildren(this.tokenId, blockHashAt);2299 }23002301 async nest(signer: TSigner, toTokenObj: IToken) {2302 return await this.collection.nestToken(signer, this.tokenId, toTokenObj);2303 }23042305 async unnest(signer: TSigner, fromTokenObj: IToken, toAddressObj: ICrossAccountId) {2306 return await this.collection.unnestToken(signer, this.tokenId, fromTokenObj, toAddressObj);2307 }23082309 async transfer(signer: TSigner, addressObj: ICrossAccountId) {2310 return await this.collection.transferToken(signer, this.tokenId, addressObj);2311 }23122313 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId) {2314 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj);2315 }23162317 async approve(signer: TSigner, toAddressObj: ICrossAccountId) {2318 return await this.collection.approveToken(signer, this.tokenId, toAddressObj);2319 }23202321 async isApproved(toAddressObj: ICrossAccountId) {2322 return await this.collection.isTokenApproved(this.tokenId, toAddressObj);2323 }23242325 async burn(signer: TSigner) {2326 return await this.collection.burnToken(signer, this.tokenId);2327 }2328}23292330class UniqueRFTToken extends UniqueTokenBase {2331 collection: UniqueRFTCollection;23322333 constructor(tokenId: number, collection: UniqueRFTCollection) {2334 super(tokenId, collection);2335 this.collection = collection;2336 }23372338 async getTop10Owners() {2339 return await this.collection.getTop10TokenOwners(this.tokenId);2340 }23412342 async getBalance(addressObj: ICrossAccountId) {2343 return await this.collection.getTokenBalance(this.tokenId, addressObj);2344 }23452346 async getTotalPieces() {2347 return await this.collection.getTokenTotalPieces(this.tokenId);2348 }23492350 async transfer(signer: TSigner, addressObj: ICrossAccountId, amount=1n) {2351 return await this.collection.transferToken(signer, this.tokenId, addressObj, amount);2352 }23532354 async transferFrom(signer: TSigner, fromAddressObj: ICrossAccountId, toAddressObj: ICrossAccountId, amount=1n) {2355 return await this.collection.transferTokenFrom(signer, this.tokenId, fromAddressObj, toAddressObj, amount);2356 }23572358 async approve(signer: TSigner, toAddressObj: ICrossAccountId, amount=1n) {2359 return await this.collection.approveToken(signer, this.tokenId, toAddressObj, amount);2360 }23612362 async getApprovedPieces(fromAddressObj: ICrossAccountId, toAccountObj: ICrossAccountId) {2363 return await this.collection.getTokenApprovedPieces(this.tokenId, fromAddressObj, toAccountObj);2364 }23652366 async repartition(signer: TSigner, amount: bigint) {2367 return await this.collection.repartitionToken(signer, this.tokenId, amount);2368 }23692370 async burn(signer: TSigner, amount=1n) {2371 return await this.collection.burnToken(signer, this.tokenId, amount);2372 }2373}