difftreelog
feat(tests) handling of generic data from events
in: master
1 file changed
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {alicesPublicKey} from '../accounts';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};4142export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {43 if (typeof input === 'string') {44 if (input.length === 48 || input.length === 47) {45 return {Substrate: input};46 } else if (input.length === 42 && input.startsWith('0x')) {47 return {Ethereum: input.toLowerCase()};48 } else if (input.length === 40 && !input.startsWith('0x')) {49 return {Ethereum: '0x' + input.toLowerCase()};50 } else {51 throw new Error(`Unknown address format: "${input}"`);52 }53 }54 if ('address' in input) {55 return {Substrate: input.address};56 }57 if ('Ethereum' in input) {58 return {59 Ethereum: input.Ethereum.toLowerCase(),60 };61 } else if ('ethereum' in input) {62 return {63 Ethereum: (input as any).ethereum.toLowerCase(),64 };65 } else if ('Substrate' in input) {66 return input;67 } else if ('substrate' in input) {68 return {69 Substrate: (input as any).substrate,70 };71 }7273 // AccountId74 return {Substrate: input.toString()};75}76export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {77 input = normalizeAccountId(input);78 if ('Substrate' in input) {79 return input.Substrate;80 } else {81 return evmToAddress(input.Ethereum);82 }83}8485export const U128_MAX = (1n << 128n) - 1n;8687const MICROUNIQUE = 1_000_000_000_000n;88const MILLIUNIQUE = 1_000n * MICROUNIQUE;89const CENTIUNIQUE = 10n * MILLIUNIQUE;90export const UNIQUE = 100n * CENTIUNIQUE;9192interface GenericResult<T> {93 success: boolean;94 data: T | null;95}9697interface CreateCollectionResult {98 success: boolean;99 collectionId: number;100}101102interface CreateItemResult {103 success: boolean;104 collectionId: number;105 itemId: number;106 recipient?: CrossAccountId;107}108109interface TransferResult {110 collectionId: number;111 itemId: number;112 sender?: CrossAccountId;113 recipient?: CrossAccountId;114 value: bigint;115}116117interface IReFungibleOwner {118 fraction: BN;119 owner: number[];120}121122interface IGetMessage {123 checkMsgUnqMethod: string;124 checkMsgTrsMethod: string;125 checkMsgSysMethod: string;126}127128export interface IFungibleTokenDataType {129 value: number;130}131132export interface IChainLimits {133 collectionNumbersLimit: number;134 accountTokenOwnershipLimit: number;135 collectionsAdminsLimit: number;136 customDataLimit: number;137 nftSponsorTransferTimeout: number;138 fungibleSponsorTransferTimeout: number;139 refungibleSponsorTransferTimeout: number;140 //offchainSchemaLimit: number;141 //constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult<T>(176 events: EventRecord[],177 expectSection?: string,178 expectMethod?: string,179 extractAction?: (data: GenericEventData) => T,180): GenericResult<T> {181 let success = false;182 let successData = null;183 events.forEach(({event: {data, method, section}}) => {184 if (method === 'ExtrinsicSuccess') {185 success = true;186 } else if ((expectSection == section) && (expectMethod == method)) {187 successData = extractAction!(data);188 }189 });190 const result: GenericResult<T> = {191 success,192 data: successData,193 };194 return result;195}196197export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {198 let success = false;199 let collectionId = 0;200 events.forEach(({event: {data, method, section}}) => {201 // console.log(` ${phase}: ${section}.${method}:: ${data}`);202 if (method == 'ExtrinsicSuccess') {203 success = true;204 } else if ((section == 'common') && (method == 'CollectionCreated')) {205 collectionId = parseInt(data[0].toString(), 10);206 }207 });208 const result: CreateCollectionResult = {209 success,210 collectionId,211 };212 return result;213}214215export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {216 let success = false;217 let collectionId = 0;218 let itemId = 0;219 let recipient;220221 const results : CreateItemResult[] = [];222223 events.forEach(({event: {data, method, section}}) => {224 // console.log(` ${phase}: ${section}.${method}:: ${data}`);225 if (method == 'ExtrinsicSuccess') {226 success = true;227 } else if ((section == 'common') && (method == 'ItemCreated')) {228 collectionId = parseInt(data[0].toString(), 10);229 itemId = parseInt(data[1].toString(), 10);230 recipient = normalizeAccountId(data[2].toJSON() as any);231232 const itemRes: CreateItemResult = {233 success,234 collectionId,235 itemId,236 recipient,237 };238239 results.push(itemRes);240 }241 });242243 return results;244}245246export function getCreateItemResult(events: EventRecord[]): CreateItemResult {247 let success = false;248 let collectionId = 0;249 let itemId = 0;250 let recipient;251 events.forEach(({event: {data, method, section}}) => {252 // console.log(` ${phase}: ${section}.${method}:: ${data}`);253 if (method == 'ExtrinsicSuccess') {254 success = true;255 } else if ((section == 'common') && (method == 'ItemCreated')) {256 collectionId = parseInt(data[0].toString(), 10);257 itemId = parseInt(data[1].toString(), 10);258 recipient = normalizeAccountId(data[2].toJSON() as any);259 }260 });261 const result: CreateItemResult = {262 success,263 collectionId,264 itemId,265 recipient,266 };267 return result;268}269270export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {271 for (const {event} of events) {272 if (api.events.common.Transfer.is(event)) {273 const [collection, token, sender, recipient, value] = event.data;274 return {275 collectionId: collection.toNumber(),276 itemId: token.toNumber(),277 sender: normalizeAccountId(sender.toJSON() as any),278 recipient: normalizeAccountId(recipient.toJSON() as any),279 value: value.toBigInt(),280 };281 }282 }283 throw new Error('no transfer event');284}285286interface Nft {287 type: 'NFT';288}289290interface Fungible {291 type: 'Fungible';292 decimalPoints: number;293}294295interface ReFungible {296 type: 'ReFungible';297}298299type CollectionMode = Nft | Fungible | ReFungible;300301export type Property = {302 key: any,303 value: any,304};305306type Permission = {307 mutable: boolean;308 collectionAdmin: boolean;309 tokenOwner: boolean;310}311312type PropertyPermission = {313 key: any;314 permission: Permission;315}316317export type CreateCollectionParams = {318 mode: CollectionMode,319 name: string,320 description: string,321 tokenPrefix: string,322 properties?: Array<Property>,323 propPerm?: Array<PropertyPermission>324};325326const defaultCreateCollectionParams: CreateCollectionParams = {327 description: 'description',328 mode: {type: 'NFT'},329 name: 'name',330 tokenPrefix: 'prefix',331};332333export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {334 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};335336 let collectionId = 0;337 await usingApi(async (api, privateKeyWrapper) => {338 // Get number of collections before the transaction339 const collectionCountBefore = await getCreatedCollectionCount(api);340341 // Run the CreateCollection transaction342 const alicePrivateKey = privateKeyWrapper('//Alice');343344 let modeprm = {};345 if (mode.type === 'NFT') {346 modeprm = {nft: null};347 } else if (mode.type === 'Fungible') {348 modeprm = {fungible: mode.decimalPoints};349 } else if (mode.type === 'ReFungible') {350 modeprm = {refungible: null};351 }352353 const tx = api.tx.unique.createCollectionEx({354 name: strToUTF16(name),355 description: strToUTF16(description),356 tokenPrefix: strToUTF16(tokenPrefix),357 mode: modeprm as any,358 });359 const events = await submitTransactionAsync(alicePrivateKey, tx);360 const result = getCreateCollectionResult(events);361362 // Get number of collections after the transaction363 const collectionCountAfter = await getCreatedCollectionCount(api);364365 // Get the collection366 const collection = await queryCollectionExpectSuccess(api, result.collectionId);367368 // What to expect369 // tslint:disable-next-line:no-unused-expression370 expect(result.success).to.be.true;371 expect(result.collectionId).to.be.equal(collectionCountAfter);372 // tslint:disable-next-line:no-unused-expression373 expect(collection).to.be.not.null;374 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');375 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));376 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);377 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);378 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);379380 collectionId = result.collectionId;381 });382383 return collectionId;384}385386export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {387 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};388389 let collectionId = 0;390 await usingApi(async (api, privateKeyWrapper) => {391 // Get number of collections before the transaction392 const collectionCountBefore = await getCreatedCollectionCount(api);393394 // Run the CreateCollection transaction395 const alicePrivateKey = privateKeyWrapper('//Alice');396397 let modeprm = {};398 if (mode.type === 'NFT') {399 modeprm = {nft: null};400 } else if (mode.type === 'Fungible') {401 modeprm = {fungible: mode.decimalPoints};402 } else if (mode.type === 'ReFungible') {403 modeprm = {refungible: null};404 }405406 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});407 const events = await submitTransactionAsync(alicePrivateKey, tx);408 const result = getCreateCollectionResult(events);409410 // Get number of collections after the transaction411 const collectionCountAfter = await getCreatedCollectionCount(api);412413 // Get the collection414 const collection = await queryCollectionExpectSuccess(api, result.collectionId);415416 // What to expect417 // tslint:disable-next-line:no-unused-expression418 expect(result.success).to.be.true;419 expect(result.collectionId).to.be.equal(collectionCountAfter);420 // tslint:disable-next-line:no-unused-expression421 expect(collection).to.be.not.null;422 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');423 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));424 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);425 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);426 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);427428429 collectionId = result.collectionId;430 });431432 return collectionId;433}434435export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {436 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};437438 await usingApi(async (api, privateKeyWrapper) => {439 // Get number of collections before the transaction440 const collectionCountBefore = await getCreatedCollectionCount(api);441442 // Run the CreateCollection transaction443 const alicePrivateKey = privateKeyWrapper('//Alice');444445 let modeprm = {};446 if (mode.type === 'NFT') {447 modeprm = {nft: null};448 } else if (mode.type === 'Fungible') {449 modeprm = {fungible: mode.decimalPoints};450 } else if (mode.type === 'ReFungible') {451 modeprm = {refungible: null};452 }453454 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});455 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;456457458 // Get number of collections after the transaction459 const collectionCountAfter = await getCreatedCollectionCount(api);460461 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');462 });463}464465export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {466 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};467468 let modeprm = {};469 if (mode.type === 'NFT') {470 modeprm = {nft: null};471 } else if (mode.type === 'Fungible') {472 modeprm = {fungible: mode.decimalPoints};473 } else if (mode.type === 'ReFungible') {474 modeprm = {refungible: null};475 }476477 await usingApi(async (api, privateKeyWrapper) => {478 // Get number of collections before the transaction479 const collectionCountBefore = await getCreatedCollectionCount(api);480481 // Run the CreateCollection transaction482 const alicePrivateKey = privateKeyWrapper('//Alice');483 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});484 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;485486 // Get number of collections after the transaction487 const collectionCountAfter = await getCreatedCollectionCount(api);488489 // What to expect490 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');491 });492}493494export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {495 let bal = 0n;496 let unused;497 do {498 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;499 const keyring = new Keyring({type: 'sr25519'});500 unused = keyring.addFromUri(`//${randomSeed}`);501 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();502 } while (bal !== 0n);503 return unused;504}505506export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {507 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();508}509510export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {511 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));512}513514export async function findNotExistingCollection(api: ApiPromise): Promise<number> {515 const totalNumber = await getCreatedCollectionCount(api);516 const newCollection: number = totalNumber + 1;517 return newCollection;518}519520function getDestroyResult(events: EventRecord[]): boolean {521 let success = false;522 events.forEach(({event: {method}}) => {523 if (method == 'ExtrinsicSuccess') {524 success = true;525 }526 });527 return success;528}529530export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {531 await usingApi(async (api, privateKeyWrapper) => {532 // Run the DestroyCollection transaction533 const alicePrivateKey = privateKeyWrapper(senderSeed);534 const tx = api.tx.unique.destroyCollection(collectionId);535 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;536 });537}538539export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {540 await usingApi(async (api, privateKeyWrapper) => {541 // Run the DestroyCollection transaction542 const alicePrivateKey = privateKeyWrapper(senderSeed);543 const tx = api.tx.unique.destroyCollection(collectionId);544 const events = await submitTransactionAsync(alicePrivateKey, tx);545 const result = getDestroyResult(events);546 expect(result).to.be.true;547548 // What to expect549 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;550 });551}552553export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {554 await usingApi(async (api) => {555 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {564 await usingApi(async(api) => {565 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);566 const events = await submitTransactionAsync(sender, tx);567 const result = getGenericResult(events);568569 expect(result.success).to.be.true;570 });571};572573export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {574 await usingApi(async (api) => {575 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);576 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;577 const result = getGenericResult(events);578579 expect(result.success).to.be.false;580 });581}582583export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {584 await usingApi(async (api, privateKeyWrapper) => {585586 // Run the transaction587 const senderPrivateKey = privateKeyWrapper(sender);588 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);589 const events = await submitTransactionAsync(senderPrivateKey, tx);590 const result = getGenericResult(events);591592 // Get the collection593 const collection = await queryCollectionExpectSuccess(api, collectionId);594595 // What to expect596 expect(result.success).to.be.true;597 expect(collection.sponsorship.toJSON()).to.deep.equal({598 unconfirmed: sponsor,599 });600 });601}602603export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {604 await usingApi(async (api, privateKeyWrapper) => {605606 // Run the transaction607 const alicePrivateKey = privateKeyWrapper(sender);608 const tx = api.tx.unique.removeCollectionSponsor(collectionId);609 const events = await submitTransactionAsync(alicePrivateKey, tx);610 const result = getGenericResult(events);611612 // Get the collection613 const collection = await queryCollectionExpectSuccess(api, collectionId);614615 // What to expect616 expect(result.success).to.be.true;617 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});618 });619}620621export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {622 await usingApi(async (api, privateKeyWrapper) => {623624 // Run the transaction625 const alicePrivateKey = privateKeyWrapper(senderSeed);626 const tx = api.tx.unique.removeCollectionSponsor(collectionId);627 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;628 });629}630631export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {632 await usingApi(async (api, privateKeyWrapper) => {633634 // Run the transaction635 const alicePrivateKey = privateKeyWrapper(senderSeed);636 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);637 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638 });639}640641export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {642 await usingApi(async (api, privateKeyWrapper) => {643644 // Run the transaction645 const sender = privateKeyWrapper(senderSeed);646 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);647 });648}649650export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {651 await usingApi(async (api, privateKeyWrapper) => {652653 // Run the transaction654 const tx = api.tx.unique.confirmSponsorship(collectionId);655 const events = await submitTransactionAsync(sender, tx);656 const result = getGenericResult(events);657658 // Get the collection659 const collection = await queryCollectionExpectSuccess(api, collectionId);660661 // What to expect662 expect(result.success).to.be.true;663 expect(collection.sponsorship.toJSON()).to.be.deep.equal({664 confirmed: sender.address,665 });666 });667}668669670export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {671 await usingApi(async (api, privateKeyWrapper) => {672673 // Run the transaction674 const sender = privateKeyWrapper(senderSeed);675 const tx = api.tx.unique.confirmSponsorship(collectionId);676 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 });678}679680export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683 const events = await submitTransactionAsync(sender, tx);684 const result = getGenericResult(events);685686 expect(result.success).to.be.true;687 });688}689690export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {691 await usingApi(async (api) => {692 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);693 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;694 const result = getGenericResult(events);695696 expect(result.success).to.be.false;697 });698}699700export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {701702 await usingApi(async (api) => {703704 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);705 const events = await submitTransactionAsync(sender, tx);706 const result = getGenericResult(events);707708 expect(result.success).to.be.true;709 });710}711712export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {713714 await usingApi(async (api) => {715716 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);717 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;718 const result = getGenericResult(events);719720 expect(result.success).to.be.false;721 });722}723724export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725 await usingApi(async (api) => {726 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727 const events = await submitTransactionAsync(sender, tx);728 const result = getGenericResult(events);729730 expect(result.success).to.be.true;731 });732}733734export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {735 await usingApi(async (api) => {736 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);737 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;738 const result = getGenericResult(events);739740 expect(result.success).to.be.false;741 });742}743744export async function getNextSponsored(745 api: ApiPromise,746 collectionId: number,747 account: string | CrossAccountId,748 tokenId: number,749): Promise<number> {750 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));751}752753export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {754 await usingApi(async (api) => {755 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);756 const events = await submitTransactionAsync(sender, tx);757 const result = getGenericResult(events);758759 expect(result.success).to.be.true;760 });761}762763export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {764 let allowlisted = false;765 await usingApi(async (api) => {766 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;767 });768 return allowlisted;769}770771export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772 await usingApi(async (api) => {773 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());774 const events = await submitTransactionAsync(sender, tx);775 const result = getGenericResult(events);776777 expect(result.success).to.be.true;778 });779}780781export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782 await usingApi(async (api) => {783 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784 const events = await submitTransactionAsync(sender, tx);785 const result = getGenericResult(events);786787 expect(result.success).to.be.true;788 });789}790791export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {792 await usingApi(async (api) => {793 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());794 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795 const result = getGenericResult(events);796797 expect(result.success).to.be.false;798 });799}800801export interface CreateFungibleData {802 readonly Value: bigint;803}804805export interface CreateReFungibleData { }806export interface CreateNftData { }807808export type CreateItemData = {809 NFT: CreateNftData;810} | {811 Fungible: CreateFungibleData;812} | {813 ReFungible: CreateReFungibleData;814};815816export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {817 await usingApi(async (api) => {818 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);819 // if burning token by admin - use adminButnItemExpectSuccess820 expect(balanceBefore >= BigInt(value)).to.be.true;821822 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);823 const events = await submitTransactionAsync(sender, tx);824 const result = getGenericResult(events);825 expect(result.success).to.be.true;826827 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);828 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);829 });830}831832export async function833approveExpectSuccess(834 collectionId: number,835 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,836) {837 await usingApi(async (api: ApiPromise) => {838 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);839 const events = await submitTransactionAsync(owner, approveUniqueTx);840 const result = getGenericResult(events);841 expect(result.success).to.be.true;842843 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));844 });845}846847export async function adminApproveFromExpectSuccess(848 collectionId: number,849 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,850) {851 await usingApi(async (api: ApiPromise) => {852 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);853 const events = await submitTransactionAsync(admin, approveUniqueTx);854 const result = getGenericResult(events);855 expect(result.success).to.be.true;856857 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));858 });859}860861export async function862transferFromExpectSuccess(863 collectionId: number,864 tokenId: number,865 accountApproved: IKeyringPair,866 accountFrom: IKeyringPair | CrossAccountId,867 accountTo: IKeyringPair | CrossAccountId,868 value: number | bigint = 1,869 type = 'NFT',870) {871 await usingApi(async (api: ApiPromise) => {872 const from = normalizeAccountId(accountFrom);873 const to = normalizeAccountId(accountTo);874 let balanceBefore = 0n;875 if (type === 'Fungible' || type === 'ReFungible') {876 balanceBefore = await getBalance(api, collectionId, to, tokenId);877 }878 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);879 const events = await submitTransactionAsync(accountApproved, transferFromTx);880 const result = getCreateItemResult(events);881 // tslint:disable-next-line:no-unused-expression882 expect(result.success).to.be.true;883 if (type === 'NFT') {884 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);885 }886 if (type === 'Fungible') {887 const balanceAfter = await getBalance(api, collectionId, to, tokenId);888 if (JSON.stringify(to) !== JSON.stringify(from)) {889 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890 } else {891 expect(balanceAfter).to.be.equal(balanceBefore);892 }893 }894 if (type === 'ReFungible') {895 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));896 }897 });898}899900export async function901transferFromExpectFail(902 collectionId: number,903 tokenId: number,904 accountApproved: IKeyringPair,905 accountFrom: IKeyringPair,906 accountTo: IKeyringPair,907 value: number | bigint = 1,908) {909 await usingApi(async (api: ApiPromise) => {910 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);911 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;912 const result = getCreateCollectionResult(events);913 // tslint:disable-next-line:no-unused-expression914 expect(result.success).to.be.false;915 });916}917918/* eslint no-async-promise-executor: "off" */919export async function getBlockNumber(api: ApiPromise): Promise<number> {920 return new Promise<number>(async (resolve) => {921 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {922 unsubscribe();923 resolve(head.number.toNumber());924 });925 });926}927928export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {929 await usingApi(async (api) => {930 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));931 const events = await submitTransactionAsync(sender, changeAdminTx);932 const result = getCreateCollectionResult(events);933 expect(result.success).to.be.true;934 });935}936937export async function938getFreeBalance(account: IKeyringPair): Promise<bigint> {939 let balance = 0n;940 await usingApi(async (api) => {941 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());942 });943944 return balance;945}946947export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {948 const tx = api.tx.balances.transfer(target, amount);949 const events = await submitTransactionAsync(source, tx);950 const result = getGenericResult(events);951 expect(result.success).to.be.true;952}953954export async function955scheduleExpectSuccess(956 operationTx: any,957 sender: IKeyringPair,958 blockSchedule: number,959 scheduledId: string,960 period = 1,961 repetitions = 1,962) {963 await usingApi(async (api: ApiPromise) => {964 const blockNumber: number | undefined = await getBlockNumber(api);965 const expectedBlockNumber = blockNumber + blockSchedule;966967 expect(blockNumber).to.be.greaterThan(0);968 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule969 scheduledId,970 expectedBlockNumber, 971 repetitions > 1 ? [period, repetitions] : null, 972 0, 973 {value: operationTx as any},974 );975976 const events = await submitTransactionAsync(sender, scheduleTx);977 expect(getGenericResult(events).success).to.be.true;978 });979}980981export async function982scheduleExpectFailure(983 operationTx: any,984 sender: IKeyringPair,985 blockSchedule: number,986 scheduledId: string,987 period = 1,988 repetitions = 1,989) {990 await usingApi(async (api: ApiPromise) => {991 const blockNumber: number | undefined = await getBlockNumber(api);992 const expectedBlockNumber = blockNumber + blockSchedule;993994 expect(blockNumber).to.be.greaterThan(0);995 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule996 scheduledId,997 expectedBlockNumber, 998 repetitions <= 1 ? null : [period, repetitions], 999 0, 1000 {value: operationTx as any},1001 );10021003 //const events = 1004 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1005 //expect(getGenericResult(events).success).to.be.false;1006 });1007}10081009export async function1010scheduleTransferAndWaitExpectSuccess(1011 collectionId: number,1012 tokenId: number,1013 sender: IKeyringPair,1014 recipient: IKeyringPair,1015 value: number | bigint = 1,1016 blockSchedule: number,1017 scheduledId: string,1018) {1019 await usingApi(async (api: ApiPromise) => {1020 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10211022 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10231024 // sleep for n + 1 blocks1025 await waitNewBlocks(blockSchedule + 1);10261027 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10281029 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1030 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1031 });1032}10331034export async function1035scheduleTransferExpectSuccess(1036 collectionId: number,1037 tokenId: number,1038 sender: IKeyringPair,1039 recipient: IKeyringPair,1040 value: number | bigint = 1,1041 blockSchedule: number,1042 scheduledId: string,1043) {1044 await usingApi(async (api: ApiPromise) => {1045 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10461047 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10481049 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1050 });1051}10521053export async function1054scheduleTransferFundsPeriodicExpectSuccess(1055 amount: bigint,1056 sender: IKeyringPair,1057 recipient: IKeyringPair,1058 blockSchedule: number,1059 scheduledId: string,1060 period: number,1061 repetitions: number,1062) {1063 await usingApi(async (api: ApiPromise) => {1064 const transferTx = api.tx.balances.transfer(recipient.address, amount);10651066 const balanceBefore = await getFreeBalance(recipient);1067 1068 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10691070 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1071 });1072}10731074export async function1075transferExpectSuccess(1076 collectionId: number,1077 tokenId: number,1078 sender: IKeyringPair,1079 recipient: IKeyringPair | CrossAccountId,1080 value: number | bigint = 1,1081 type = 'NFT',1082) {1083 await usingApi(async (api: ApiPromise) => {1084 const from = normalizeAccountId(sender);1085 const to = normalizeAccountId(recipient);10861087 let balanceBefore = 0n;1088 if (type === 'Fungible') {1089 balanceBefore = await getBalance(api, collectionId, to, tokenId);1090 }1091 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1092 const events = await executeTransaction(api, sender, transferTx);10931094 const result = getTransferResult(api, events);1095 expect(result.collectionId).to.be.equal(collectionId);1096 expect(result.itemId).to.be.equal(tokenId);1097 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1098 expect(result.recipient).to.be.deep.equal(to);1099 expect(result.value).to.be.equal(BigInt(value));11001101 if (type === 'NFT') {1102 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1103 }1104 if (type === 'Fungible') {1105 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1106 if (JSON.stringify(to) !== JSON.stringify(from)) {1107 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1108 } else {1109 expect(balanceAfter).to.be.equal(balanceBefore);1110 }1111 }1112 if (type === 'ReFungible') {1113 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1114 }1115 });1116}11171118export async function1119transferExpectFailure(1120 collectionId: number,1121 tokenId: number,1122 sender: IKeyringPair,1123 recipient: IKeyringPair | CrossAccountId,1124 value: number | bigint = 1,1125) {1126 await usingApi(async (api: ApiPromise) => {1127 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1128 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1129 const result = getGenericResult(events);1130 // if (events && Array.isArray(events)) {1131 // const result = getCreateCollectionResult(events);1132 // tslint:disable-next-line:no-unused-expression1133 expect(result.success).to.be.false;1134 //}1135 });1136}11371138export async function1139approveExpectFail(1140 collectionId: number,1141 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1142) {1143 await usingApi(async (api: ApiPromise) => {1144 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1145 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1146 const result = getCreateCollectionResult(events);1147 // tslint:disable-next-line:no-unused-expression1148 expect(result.success).to.be.false;1149 });1150}11511152export async function getBalance(1153 api: ApiPromise,1154 collectionId: number,1155 owner: string | CrossAccountId,1156 token: number,1157): Promise<bigint> {1158 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1159}1160export async function getTokenOwner(1161 api: ApiPromise,1162 collectionId: number,1163 token: number,1164): Promise<CrossAccountId> {1165 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1166 if (owner == null) throw new Error('owner == null');1167 return normalizeAccountId(owner);1168}1169export async function getTopmostTokenOwner(1170 api: ApiPromise,1171 collectionId: number,1172 token: number,1173): Promise<CrossAccountId> {1174 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1175 if (owner == null) throw new Error('owner == null');1176 return normalizeAccountId(owner);1177}1178export async function getTokenChildren(1179 api: ApiPromise,1180 collectionId: number,1181 tokenId: number,1182): Promise<UpDataStructsTokenChild[]> {1183 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1184}1185export async function isTokenExists(1186 api: ApiPromise,1187 collectionId: number,1188 token: number,1189): Promise<boolean> {1190 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1191}1192export async function getLastTokenId(1193 api: ApiPromise,1194 collectionId: number,1195): Promise<number> {1196 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1197}1198export async function getAdminList(1199 api: ApiPromise,1200 collectionId: number,1201): Promise<string[]> {1202 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1203}1204export async function getTokenProperties(1205 api: ApiPromise,1206 collectionId: number,1207 tokenId: number,1208 propertyKeys: string[],1209): Promise<UpDataStructsProperty[]> {1210 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1211}12121213export async function createFungibleItemExpectSuccess(1214 sender: IKeyringPair,1215 collectionId: number,1216 data: CreateFungibleData,1217 owner: CrossAccountId | string = sender.address,1218) {1219 return await usingApi(async (api) => {1220 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12211222 const events = await submitTransactionAsync(sender, tx);1223 const result = getCreateItemResult(events);12241225 expect(result.success).to.be.true;1226 return result.itemId;1227 });1228}12291230export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1231 await usingApi(async (api) => {1232 const to = normalizeAccountId(owner);1233 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12341235 const events = await submitTransactionAsync(sender, tx);1236 const result = getCreateItemsResult(events);12371238 for (const res of result) {1239 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1240 }1241 });1242}12431244export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1245 await usingApi(async (api) => {1246 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12471248 const events = await submitTransactionAsync(sender, tx);1249 const result = getCreateItemsResult(events);12501251 for (const res of result) {1252 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1253 }1254 });1255}12561257export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1258 let newItemId = 0;1259 await usingApi(async (api) => {1260 const to = normalizeAccountId(owner);1261 const itemCountBefore = await getLastTokenId(api, collectionId);1262 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12631264 let tx;1265 if (createMode === 'Fungible') {1266 const createData = {fungible: {value: 10}};1267 tx = api.tx.unique.createItem(collectionId, to, createData as any);1268 } else if (createMode === 'ReFungible') {1269 const createData = {refungible: {pieces: 100}};1270 tx = api.tx.unique.createItem(collectionId, to, createData as any);1271 } else {1272 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1273 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1274 }12751276 const events = await submitTransactionAsync(sender, tx);1277 const result = getCreateItemResult(events);12781279 const itemCountAfter = await getLastTokenId(api, collectionId);1280 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12811282 if (createMode === 'NFT') {1283 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1284 }12851286 // What to expect1287 // tslint:disable-next-line:no-unused-expression1288 expect(result.success).to.be.true;1289 if (createMode === 'Fungible') {1290 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1291 } else {1292 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1293 }1294 expect(collectionId).to.be.equal(result.collectionId);1295 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1296 expect(to).to.be.deep.equal(result.recipient);1297 newItemId = result.itemId;1298 });1299 return newItemId;1300}13011302export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1303 await usingApi(async (api) => {13041305 let tx;1306 if (createMode === 'NFT') {1307 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1308 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1309 } else {1310 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1311 }131213131314 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1315 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1316 const result = getCreateItemResult(events);13171318 expect(result.success).to.be.false;1319 });1320}13211322export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1323 let newItemId = 0;1324 await usingApi(async (api) => {1325 const to = normalizeAccountId(owner);1326 const itemCountBefore = await getLastTokenId(api, collectionId);1327 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13281329 let tx;1330 if (createMode === 'Fungible') {1331 const createData = {fungible: {value: 10}};1332 tx = api.tx.unique.createItem(collectionId, to, createData as any);1333 } else if (createMode === 'ReFungible') {1334 const createData = {refungible: {pieces: 100}};1335 tx = api.tx.unique.createItem(collectionId, to, createData as any);1336 } else {1337 const createData = {nft: {}};1338 tx = api.tx.unique.createItem(collectionId, to, createData as any);1339 }13401341 const events = await submitTransactionAsync(sender, tx);1342 const result = getCreateItemResult(events);13431344 const itemCountAfter = await getLastTokenId(api, collectionId);1345 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13461347 // What to expect1348 // tslint:disable-next-line:no-unused-expression1349 expect(result.success).to.be.true;1350 if (createMode === 'Fungible') {1351 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1352 } else {1353 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1354 }1355 expect(collectionId).to.be.equal(result.collectionId);1356 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1357 expect(to).to.be.deep.equal(result.recipient);1358 newItemId = result.itemId;1359 });1360 return newItemId;1361}13621363export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1364 await usingApi(async (api) => {1365 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13661367 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1368 const result = getCreateItemResult(events);13691370 expect(result.success).to.be.false;1371 });1372}13731374export async function setPublicAccessModeExpectSuccess(1375 sender: IKeyringPair, collectionId: number,1376 accessMode: 'Normal' | 'AllowList',1377) {1378 await usingApi(async (api) => {13791380 // Run the transaction1381 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1382 const events = await submitTransactionAsync(sender, tx);1383 const result = getGenericResult(events);13841385 // Get the collection1386 const collection = await queryCollectionExpectSuccess(api, collectionId);13871388 // What to expect1389 // tslint:disable-next-line:no-unused-expression1390 expect(result.success).to.be.true;1391 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1392 });1393}13941395export async function setPublicAccessModeExpectFail(1396 sender: IKeyringPair, collectionId: number,1397 accessMode: 'Normal' | 'AllowList',1398) {1399 await usingApi(async (api) => {14001401 // Run the transaction1402 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1403 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1404 const result = getGenericResult(events);14051406 // What to expect1407 // tslint:disable-next-line:no-unused-expression1408 expect(result.success).to.be.false;1409 });1410}14111412export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1413 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1414}14151416export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1417 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1418}14191420export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1421 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1422}14231424export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1425 await usingApi(async (api) => {14261427 // Run the transaction1428 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1429 const events = await submitTransactionAsync(sender, tx);1430 const result = getGenericResult(events);1431 expect(result.success).to.be.true;14321433 // Get the collection1434 const collection = await queryCollectionExpectSuccess(api, collectionId);14351436 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1437 });1438}14391440export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1441 await setMintPermissionExpectSuccess(sender, collectionId, true);1442}14431444export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1445 await usingApi(async (api) => {1446 // Run the transaction1447 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1448 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1449 const result = getCreateCollectionResult(events);1450 // tslint:disable-next-line:no-unused-expression1451 expect(result.success).to.be.false;1452 });1453}14541455export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1456 await usingApi(async (api) => {1457 // Run the transaction1458 const tx = api.tx.unique.setChainLimits(limits);1459 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1460 const result = getCreateCollectionResult(events);1461 // tslint:disable-next-line:no-unused-expression1462 expect(result.success).to.be.false;1463 });1464}14651466export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1467 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1468}14691470export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1471 await usingApi(async (api) => {1472 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14731474 // Run the transaction1475 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1476 const events = await submitTransactionAsync(sender, tx);1477 const result = getGenericResult(events);1478 expect(result.success).to.be.true;14791480 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1481 });1482}14831484export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1485 await usingApi(async (api) => {14861487 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14881489 // Run the transaction1490 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1491 const events = await submitTransactionAsync(sender, tx);1492 const result = getGenericResult(events);1493 expect(result.success).to.be.true;14941495 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1496 });1497}14981499export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1500 await usingApi(async (api) => {15011502 // Run the transaction1503 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1504 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1505 const result = getGenericResult(events);15061507 // What to expect1508 // tslint:disable-next-line:no-unused-expression1509 expect(result.success).to.be.false;1510 });1511}15121513export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1514 await usingApi(async (api) => {1515 // Run the transaction1516 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1517 const events = await submitTransactionAsync(sender, tx);1518 const result = getGenericResult(events);15191520 // What to expect1521 // tslint:disable-next-line:no-unused-expression1522 expect(result.success).to.be.true;1523 });1524}15251526export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1527 await usingApi(async (api) => {1528 // Run the transaction1529 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1530 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1531 const result = getGenericResult(events);15321533 // What to expect1534 // tslint:disable-next-line:no-unused-expression1535 expect(result.success).to.be.false;1536 });1537}15381539export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1540 : Promise<UpDataStructsRpcCollection | null> => {1541 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1542};15431544export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1545 // set global object - collectionsCount1546 return (await api.rpc.unique.collectionStats()).created.toNumber();1547};15481549export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1550 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1551}15521553export async function waitNewBlocks(blocksCount = 1): Promise<void> {1554 await usingApi(async (api) => {1555 const promise = new Promise<void>(async (resolve) => {1556 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1557 if (blocksCount > 0) {1558 blocksCount--;1559 } else {1560 unsubscribe();1561 resolve();1562 }1563 });1564 });1565 return promise;1566 });1567}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {alicesPublicKey} from '../accounts';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};4142export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {43 if (typeof input === 'string') {44 if (input.length === 48 || input.length === 47) {45 return {Substrate: input};46 } else if (input.length === 42 && input.startsWith('0x')) {47 return {Ethereum: input.toLowerCase()};48 } else if (input.length === 40 && !input.startsWith('0x')) {49 return {Ethereum: '0x' + input.toLowerCase()};50 } else {51 throw new Error(`Unknown address format: "${input}"`);52 }53 }54 if ('address' in input) {55 return {Substrate: input.address};56 }57 if ('Ethereum' in input) {58 return {59 Ethereum: input.Ethereum.toLowerCase(),60 };61 } else if ('ethereum' in input) {62 return {63 Ethereum: (input as any).ethereum.toLowerCase(),64 };65 } else if ('Substrate' in input) {66 return input;67 } else if ('substrate' in input) {68 return {69 Substrate: (input as any).substrate,70 };71 }7273 // AccountId74 return {Substrate: input.toString()};75}76export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {77 input = normalizeAccountId(input);78 if ('Substrate' in input) {79 return input.Substrate;80 } else {81 return evmToAddress(input.Ethereum);82 }83}8485export const U128_MAX = (1n << 128n) - 1n;8687const MICROUNIQUE = 1_000_000_000_000n;88const MILLIUNIQUE = 1_000n * MICROUNIQUE;89const CENTIUNIQUE = 10n * MILLIUNIQUE;90export const UNIQUE = 100n * CENTIUNIQUE;9192interface GenericResult<T> {93 success: boolean;94 data: T | null;95}9697interface CreateCollectionResult {98 success: boolean;99 collectionId: number;100}101102interface CreateItemResult {103 success: boolean;104 collectionId: number;105 itemId: number;106 recipient?: CrossAccountId;107}108109interface TransferResult {110 collectionId: number;111 itemId: number;112 sender?: CrossAccountId;113 recipient?: CrossAccountId;114 value: bigint;115}116117interface IReFungibleOwner {118 fraction: BN;119 owner: number[];120}121122interface IGetMessage {123 checkMsgUnqMethod: string;124 checkMsgTrsMethod: string;125 checkMsgSysMethod: string;126}127128export interface IFungibleTokenDataType {129 value: number;130}131132export interface IChainLimits {133 collectionNumbersLimit: number;134 accountTokenOwnershipLimit: number;135 collectionsAdminsLimit: number;136 customDataLimit: number;137 nftSponsorTransferTimeout: number;138 fungibleSponsorTransferTimeout: number;139 refungibleSponsorTransferTimeout: number;140 //offchainSchemaLimit: number;141 //constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;176export function getGenericResult<T>(177 events: EventRecord[],178 expectSection: string,179 expectMethod: string,180 extractAction: (data: GenericEventData) => T181): GenericResult<T>;182183export function getGenericResult<T>(184 events: EventRecord[],185 expectSection?: string,186 expectMethod?: string,187 extractAction?: (data: GenericEventData) => T,188): GenericResult<T> {189 let success = false;190 let successData = null;191192 events.forEach(({event: {data, method, section}}) => {193 // console.log(` ${phase}: ${section}.${method}:: ${data}`);194 if (method === 'ExtrinsicSuccess') {195 success = true;196 } else if ((expectSection == section) && (expectMethod == method)) {197 successData = extractAction!(data);198 }199 });200201 const result: GenericResult<T> = {202 success,203 data: successData,204 };205 return result;206}207208export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {209 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));210 const result: CreateCollectionResult = {211 success: genericResult.success,212 collectionId: genericResult.data ?? 0,213 };214 return result;215}216217export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {218 const results: CreateItemResult[] = [];219 220 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {221 const collectionId = parseInt(data[0].toString(), 10);222 const itemId = parseInt(data[1].toString(), 10);223 const recipient = normalizeAccountId(data[2].toJSON() as any);224225 const itemRes: CreateItemResult = {226 success: true,227 collectionId,228 itemId,229 recipient,230 };231232 results.push(itemRes);233 return results;234 });235236 if (!genericResult.success) return [];237 return results;238}239240export function getCreateItemResult(events: EventRecord[]): CreateItemResult {241 const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [242 parseInt(data[0].toString(), 10),243 parseInt(data[1].toString(), 10),244 normalizeAccountId(data[2].toJSON() as any),245 ]);246247 if (genericResult.data == null) genericResult.data = [0, 0];248249 const result: CreateItemResult = {250 success: genericResult.success,251 collectionId: genericResult.data[0],252 itemId: genericResult.data[1],253 recipient: genericResult.data![2],254 };255 256 return result;257}258259export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {260 for (const {event} of events) {261 if (api.events.common.Transfer.is(event)) {262 const [collection, token, sender, recipient, value] = event.data;263 return {264 collectionId: collection.toNumber(),265 itemId: token.toNumber(),266 sender: normalizeAccountId(sender.toJSON() as any),267 recipient: normalizeAccountId(recipient.toJSON() as any),268 value: value.toBigInt(),269 };270 }271 }272 throw new Error('no transfer event');273}274275interface Nft {276 type: 'NFT';277}278279interface Fungible {280 type: 'Fungible';281 decimalPoints: number;282}283284interface ReFungible {285 type: 'ReFungible';286}287288type CollectionMode = Nft | Fungible | ReFungible;289290export type Property = {291 key: any,292 value: any,293};294295type Permission = {296 mutable: boolean;297 collectionAdmin: boolean;298 tokenOwner: boolean;299}300301type PropertyPermission = {302 key: any;303 permission: Permission;304}305306export type CreateCollectionParams = {307 mode: CollectionMode,308 name: string,309 description: string,310 tokenPrefix: string,311 properties?: Array<Property>,312 propPerm?: Array<PropertyPermission>313};314315const defaultCreateCollectionParams: CreateCollectionParams = {316 description: 'description',317 mode: {type: 'NFT'},318 name: 'name',319 tokenPrefix: 'prefix',320};321322export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {323 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};324325 let collectionId = 0;326 await usingApi(async (api, privateKeyWrapper) => {327 // Get number of collections before the transaction328 const collectionCountBefore = await getCreatedCollectionCount(api);329330 // Run the CreateCollection transaction331 const alicePrivateKey = privateKeyWrapper('//Alice');332333 let modeprm = {};334 if (mode.type === 'NFT') {335 modeprm = {nft: null};336 } else if (mode.type === 'Fungible') {337 modeprm = {fungible: mode.decimalPoints};338 } else if (mode.type === 'ReFungible') {339 modeprm = {refungible: null};340 }341342 const tx = api.tx.unique.createCollectionEx({343 name: strToUTF16(name),344 description: strToUTF16(description),345 tokenPrefix: strToUTF16(tokenPrefix),346 mode: modeprm as any,347 });348 const events = await submitTransactionAsync(alicePrivateKey, tx);349 const result = getCreateCollectionResult(events);350351 // Get number of collections after the transaction352 const collectionCountAfter = await getCreatedCollectionCount(api);353354 // Get the collection355 const collection = await queryCollectionExpectSuccess(api, result.collectionId);356357 // What to expect358 // tslint:disable-next-line:no-unused-expression359 expect(result.success).to.be.true;360 expect(result.collectionId).to.be.equal(collectionCountAfter);361 // tslint:disable-next-line:no-unused-expression362 expect(collection).to.be.not.null;363 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');364 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));365 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);366 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);367 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);368369 collectionId = result.collectionId;370 });371372 return collectionId;373}374375export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {376 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};377378 let collectionId = 0;379 await usingApi(async (api, privateKeyWrapper) => {380 // Get number of collections before the transaction381 const collectionCountBefore = await getCreatedCollectionCount(api);382383 // Run the CreateCollection transaction384 const alicePrivateKey = privateKeyWrapper('//Alice');385386 let modeprm = {};387 if (mode.type === 'NFT') {388 modeprm = {nft: null};389 } else if (mode.type === 'Fungible') {390 modeprm = {fungible: mode.decimalPoints};391 } else if (mode.type === 'ReFungible') {392 modeprm = {refungible: null};393 }394395 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});396 const events = await submitTransactionAsync(alicePrivateKey, tx);397 const result = getCreateCollectionResult(events);398399 // Get number of collections after the transaction400 const collectionCountAfter = await getCreatedCollectionCount(api);401402 // Get the collection403 const collection = await queryCollectionExpectSuccess(api, result.collectionId);404405 // What to expect406 // tslint:disable-next-line:no-unused-expression407 expect(result.success).to.be.true;408 expect(result.collectionId).to.be.equal(collectionCountAfter);409 // tslint:disable-next-line:no-unused-expression410 expect(collection).to.be.not.null;411 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');412 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));413 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);414 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);415 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);416417418 collectionId = result.collectionId;419 });420421 return collectionId;422}423424export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {425 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};426427 await usingApi(async (api, privateKeyWrapper) => {428 // Get number of collections before the transaction429 const collectionCountBefore = await getCreatedCollectionCount(api);430431 // Run the CreateCollection transaction432 const alicePrivateKey = privateKeyWrapper('//Alice');433434 let modeprm = {};435 if (mode.type === 'NFT') {436 modeprm = {nft: null};437 } else if (mode.type === 'Fungible') {438 modeprm = {fungible: mode.decimalPoints};439 } else if (mode.type === 'ReFungible') {440 modeprm = {refungible: null};441 }442443 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});444 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;445446447 // Get number of collections after the transaction448 const collectionCountAfter = await getCreatedCollectionCount(api);449450 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');451 });452}453454export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {455 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};456457 let modeprm = {};458 if (mode.type === 'NFT') {459 modeprm = {nft: null};460 } else if (mode.type === 'Fungible') {461 modeprm = {fungible: mode.decimalPoints};462 } else if (mode.type === 'ReFungible') {463 modeprm = {refungible: null};464 }465466 await usingApi(async (api, privateKeyWrapper) => {467 // Get number of collections before the transaction468 const collectionCountBefore = await getCreatedCollectionCount(api);469470 // Run the CreateCollection transaction471 const alicePrivateKey = privateKeyWrapper('//Alice');472 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});473 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;474475 // Get number of collections after the transaction476 const collectionCountAfter = await getCreatedCollectionCount(api);477478 // What to expect479 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');480 });481}482483export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {484 let bal = 0n;485 let unused;486 do {487 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;488 const keyring = new Keyring({type: 'sr25519'});489 unused = keyring.addFromUri(`//${randomSeed}`);490 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();491 } while (bal !== 0n);492 return unused;493}494495export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {496 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();497}498499export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {500 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));501}502503export async function findNotExistingCollection(api: ApiPromise): Promise<number> {504 const totalNumber = await getCreatedCollectionCount(api);505 const newCollection: number = totalNumber + 1;506 return newCollection;507}508509function getDestroyResult(events: EventRecord[]): boolean {510 let success = false;511 events.forEach(({event: {method}}) => {512 if (method == 'ExtrinsicSuccess') {513 success = true;514 }515 });516 return success;517}518519export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {520 await usingApi(async (api, privateKeyWrapper) => {521 // Run the DestroyCollection transaction522 const alicePrivateKey = privateKeyWrapper(senderSeed);523 const tx = api.tx.unique.destroyCollection(collectionId);524 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;525 });526}527528export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {529 await usingApi(async (api, privateKeyWrapper) => {530 // Run the DestroyCollection transaction531 const alicePrivateKey = privateKeyWrapper(senderSeed);532 const tx = api.tx.unique.destroyCollection(collectionId);533 const events = await submitTransactionAsync(alicePrivateKey, tx);534 const result = getDestroyResult(events);535 expect(result).to.be.true;536537 // What to expect538 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;539 });540}541542export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {543 await usingApi(async (api) => {544 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);545 const events = await submitTransactionAsync(sender, tx);546 const result = getGenericResult(events);547548 expect(result.success).to.be.true;549 });550}551552export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {553 await usingApi(async(api) => {554 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);555 const events = await submitTransactionAsync(sender, tx);556 const result = getGenericResult(events);557558 expect(result.success).to.be.true;559 });560};561562export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {563 await usingApi(async (api) => {564 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);565 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;566 const result = getGenericResult(events);567568 expect(result.success).to.be.false;569 });570}571572export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {573 await usingApi(async (api, privateKeyWrapper) => {574575 // Run the transaction576 const senderPrivateKey = privateKeyWrapper(sender);577 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);578 const events = await submitTransactionAsync(senderPrivateKey, tx);579 const result = getGenericResult(events);580581 // Get the collection582 const collection = await queryCollectionExpectSuccess(api, collectionId);583584 // What to expect585 expect(result.success).to.be.true;586 expect(collection.sponsorship.toJSON()).to.deep.equal({587 unconfirmed: sponsor,588 });589 });590}591592export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {593 await usingApi(async (api, privateKeyWrapper) => {594595 // Run the transaction596 const alicePrivateKey = privateKeyWrapper(sender);597 const tx = api.tx.unique.removeCollectionSponsor(collectionId);598 const events = await submitTransactionAsync(alicePrivateKey, tx);599 const result = getGenericResult(events);600601 // Get the collection602 const collection = await queryCollectionExpectSuccess(api, collectionId);603604 // What to expect605 expect(result.success).to.be.true;606 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});607 });608}609610export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {611 await usingApi(async (api, privateKeyWrapper) => {612613 // Run the transaction614 const alicePrivateKey = privateKeyWrapper(senderSeed);615 const tx = api.tx.unique.removeCollectionSponsor(collectionId);616 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;617 });618}619620export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {621 await usingApi(async (api, privateKeyWrapper) => {622623 // Run the transaction624 const alicePrivateKey = privateKeyWrapper(senderSeed);625 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);626 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;627 });628}629630export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {631 await usingApi(async (api, privateKeyWrapper) => {632633 // Run the transaction634 const sender = privateKeyWrapper(senderSeed);635 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);636 });637}638639export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {640 await usingApi(async (api, privateKeyWrapper) => {641642 // Run the transaction643 const tx = api.tx.unique.confirmSponsorship(collectionId);644 const events = await submitTransactionAsync(sender, tx);645 const result = getGenericResult(events);646647 // Get the collection648 const collection = await queryCollectionExpectSuccess(api, collectionId);649650 // What to expect651 expect(result.success).to.be.true;652 expect(collection.sponsorship.toJSON()).to.be.deep.equal({653 confirmed: sender.address,654 });655 });656}657658659export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {660 await usingApi(async (api, privateKeyWrapper) => {661662 // Run the transaction663 const sender = privateKeyWrapper(senderSeed);664 const tx = api.tx.unique.confirmSponsorship(collectionId);665 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;666 });667}668669export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {670 await usingApi(async (api) => {671 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);672 const events = await submitTransactionAsync(sender, tx);673 const result = getGenericResult(events);674675 expect(result.success).to.be.true;676 });677}678679export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {680 await usingApi(async (api) => {681 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);682 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;683 const result = getGenericResult(events);684685 expect(result.success).to.be.false;686 });687}688689export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {690691 await usingApi(async (api) => {692693 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);694 const events = await submitTransactionAsync(sender, tx);695 const result = getGenericResult(events);696697 expect(result.success).to.be.true;698 });699}700701export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {702703 await usingApi(async (api) => {704705 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);706 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;707 const result = getGenericResult(events);708709 expect(result.success).to.be.false;710 });711}712713export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {714 await usingApi(async (api) => {715 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);716 const events = await submitTransactionAsync(sender, tx);717 const result = getGenericResult(events);718719 expect(result.success).to.be.true;720 });721}722723export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {724 await usingApi(async (api) => {725 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);726 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;727 const result = getGenericResult(events);728729 expect(result.success).to.be.false;730 });731}732733export async function getNextSponsored(734 api: ApiPromise,735 collectionId: number,736 account: string | CrossAccountId,737 tokenId: number,738): Promise<number> {739 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));740}741742export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {743 await usingApi(async (api) => {744 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);745 const events = await submitTransactionAsync(sender, tx);746 const result = getGenericResult(events);747748 expect(result.success).to.be.true;749 });750}751752export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {753 let allowlisted = false;754 await usingApi(async (api) => {755 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;756 });757 return allowlisted;758}759760export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {761 await usingApi(async (api) => {762 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());763 const events = await submitTransactionAsync(sender, tx);764 const result = getGenericResult(events);765766 expect(result.success).to.be.true;767 });768}769770export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {771 await usingApi(async (api) => {772 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());773 const events = await submitTransactionAsync(sender, tx);774 const result = getGenericResult(events);775776 expect(result.success).to.be.true;777 });778}779780export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {781 await usingApi(async (api) => {782 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());783 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;784 const result = getGenericResult(events);785786 expect(result.success).to.be.false;787 });788}789790export interface CreateFungibleData {791 readonly Value: bigint;792}793794export interface CreateReFungibleData { }795export interface CreateNftData { }796797export type CreateItemData = {798 NFT: CreateNftData;799} | {800 Fungible: CreateFungibleData;801} | {802 ReFungible: CreateReFungibleData;803};804805export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {806 await usingApi(async (api) => {807 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);808 // if burning token by admin - use adminButnItemExpectSuccess809 expect(balanceBefore >= BigInt(value)).to.be.true;810811 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);812 const events = await submitTransactionAsync(sender, tx);813 const result = getGenericResult(events);814 expect(result.success).to.be.true;815816 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);817 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);818 });819}820821export async function822approveExpectSuccess(823 collectionId: number,824 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,825) {826 await usingApi(async (api: ApiPromise) => {827 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);828 const events = await submitTransactionAsync(owner, approveUniqueTx);829 const result = getGenericResult(events);830 expect(result.success).to.be.true;831832 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));833 });834}835836export async function adminApproveFromExpectSuccess(837 collectionId: number,838 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,839) {840 await usingApi(async (api: ApiPromise) => {841 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);842 const events = await submitTransactionAsync(admin, approveUniqueTx);843 const result = getGenericResult(events);844 expect(result.success).to.be.true;845846 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));847 });848}849850export async function851transferFromExpectSuccess(852 collectionId: number,853 tokenId: number,854 accountApproved: IKeyringPair,855 accountFrom: IKeyringPair | CrossAccountId,856 accountTo: IKeyringPair | CrossAccountId,857 value: number | bigint = 1,858 type = 'NFT',859) {860 await usingApi(async (api: ApiPromise) => {861 const from = normalizeAccountId(accountFrom);862 const to = normalizeAccountId(accountTo);863 let balanceBefore = 0n;864 if (type === 'Fungible' || type === 'ReFungible') {865 balanceBefore = await getBalance(api, collectionId, to, tokenId);866 }867 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);868 const events = await submitTransactionAsync(accountApproved, transferFromTx);869 const result = getGenericResult(events);870 // tslint:disable-next-line:no-unused-expression871 expect(result.success).to.be.true;872 if (type === 'NFT') {873 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);874 }875 if (type === 'Fungible') {876 const balanceAfter = await getBalance(api, collectionId, to, tokenId);877 if (JSON.stringify(to) !== JSON.stringify(from)) {878 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));879 } else {880 expect(balanceAfter).to.be.equal(balanceBefore);881 }882 }883 if (type === 'ReFungible') {884 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));885 }886 });887}888889export async function890transferFromExpectFail(891 collectionId: number,892 tokenId: number,893 accountApproved: IKeyringPair,894 accountFrom: IKeyringPair,895 accountTo: IKeyringPair,896 value: number | bigint = 1,897) {898 await usingApi(async (api: ApiPromise) => {899 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);900 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;901 const result = getCreateCollectionResult(events);902 // tslint:disable-next-line:no-unused-expression903 expect(result.success).to.be.false;904 });905}906907/* eslint no-async-promise-executor: "off" */908export async function getBlockNumber(api: ApiPromise): Promise<number> {909 return new Promise<number>(async (resolve) => {910 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {911 unsubscribe();912 resolve(head.number.toNumber());913 });914 });915}916917export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {918 await usingApi(async (api) => {919 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));920 const events = await submitTransactionAsync(sender, changeAdminTx);921 const result = getCreateCollectionResult(events);922 expect(result.success).to.be.true;923 });924}925926export async function927getFreeBalance(account: IKeyringPair): Promise<bigint> {928 let balance = 0n;929 await usingApi(async (api) => {930 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());931 });932933 return balance;934}935936export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {937 const tx = api.tx.balances.transfer(target, amount);938 const events = await submitTransactionAsync(source, tx);939 const result = getGenericResult(events);940 expect(result.success).to.be.true;941}942943export async function944scheduleExpectSuccess(945 operationTx: any,946 sender: IKeyringPair,947 blockSchedule: number,948 scheduledId: string,949 period = 1,950 repetitions = 1,951) {952 await usingApi(async (api: ApiPromise) => {953 const blockNumber: number | undefined = await getBlockNumber(api);954 const expectedBlockNumber = blockNumber + blockSchedule;955956 expect(blockNumber).to.be.greaterThan(0);957 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule958 scheduledId,959 expectedBlockNumber, 960 repetitions > 1 ? [period, repetitions] : null, 961 0, 962 {value: operationTx as any},963 );964965 const events = await submitTransactionAsync(sender, scheduleTx);966 expect(getGenericResult(events).success).to.be.true;967 });968}969970export async function971scheduleExpectFailure(972 operationTx: any,973 sender: IKeyringPair,974 blockSchedule: number,975 scheduledId: string,976 period = 1,977 repetitions = 1,978) {979 await usingApi(async (api: ApiPromise) => {980 const blockNumber: number | undefined = await getBlockNumber(api);981 const expectedBlockNumber = blockNumber + blockSchedule;982983 expect(blockNumber).to.be.greaterThan(0);984 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule985 scheduledId,986 expectedBlockNumber, 987 repetitions <= 1 ? null : [period, repetitions], 988 0, 989 {value: operationTx as any},990 );991992 //const events = 993 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;994 //expect(getGenericResult(events).success).to.be.false;995 });996}997998export async function999scheduleTransferAndWaitExpectSuccess(1000 collectionId: number,1001 tokenId: number,1002 sender: IKeyringPair,1003 recipient: IKeyringPair,1004 value: number | bigint = 1,1005 blockSchedule: number,1006 scheduledId: string,1007) {1008 await usingApi(async (api: ApiPromise) => {1009 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10101011 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10121013 // sleep for n + 1 blocks1014 await waitNewBlocks(blockSchedule + 1);10151016 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10171018 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1019 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1020 });1021}10221023export async function1024scheduleTransferExpectSuccess(1025 collectionId: number,1026 tokenId: number,1027 sender: IKeyringPair,1028 recipient: IKeyringPair,1029 value: number | bigint = 1,1030 blockSchedule: number,1031 scheduledId: string,1032) {1033 await usingApi(async (api: ApiPromise) => {1034 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10351036 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10371038 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1039 });1040}10411042export async function1043scheduleTransferFundsPeriodicExpectSuccess(1044 amount: bigint,1045 sender: IKeyringPair,1046 recipient: IKeyringPair,1047 blockSchedule: number,1048 scheduledId: string,1049 period: number,1050 repetitions: number,1051) {1052 await usingApi(async (api: ApiPromise) => {1053 const transferTx = api.tx.balances.transfer(recipient.address, amount);10541055 const balanceBefore = await getFreeBalance(recipient);1056 1057 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10581059 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1060 });1061}10621063export async function1064transferExpectSuccess(1065 collectionId: number,1066 tokenId: number,1067 sender: IKeyringPair,1068 recipient: IKeyringPair | CrossAccountId,1069 value: number | bigint = 1,1070 type = 'NFT',1071) {1072 await usingApi(async (api: ApiPromise) => {1073 const from = normalizeAccountId(sender);1074 const to = normalizeAccountId(recipient);10751076 let balanceBefore = 0n;1077 if (type === 'Fungible') {1078 balanceBefore = await getBalance(api, collectionId, to, tokenId);1079 }1080 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1081 const events = await executeTransaction(api, sender, transferTx);10821083 const result = getTransferResult(api, events);1084 expect(result.collectionId).to.be.equal(collectionId);1085 expect(result.itemId).to.be.equal(tokenId);1086 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1087 expect(result.recipient).to.be.deep.equal(to);1088 expect(result.value).to.be.equal(BigInt(value));10891090 if (type === 'NFT') {1091 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1092 }1093 if (type === 'Fungible') {1094 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1095 if (JSON.stringify(to) !== JSON.stringify(from)) {1096 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1097 } else {1098 expect(balanceAfter).to.be.equal(balanceBefore);1099 }1100 }1101 if (type === 'ReFungible') {1102 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1103 }1104 });1105}11061107export async function1108transferExpectFailure(1109 collectionId: number,1110 tokenId: number,1111 sender: IKeyringPair,1112 recipient: IKeyringPair | CrossAccountId,1113 value: number | bigint = 1,1114) {1115 await usingApi(async (api: ApiPromise) => {1116 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1117 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1118 const result = getGenericResult(events);1119 // if (events && Array.isArray(events)) {1120 // const result = getCreateCollectionResult(events);1121 // tslint:disable-next-line:no-unused-expression1122 expect(result.success).to.be.false;1123 //}1124 });1125}11261127export async function1128approveExpectFail(1129 collectionId: number,1130 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1131) {1132 await usingApi(async (api: ApiPromise) => {1133 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1134 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1135 const result = getCreateCollectionResult(events);1136 // tslint:disable-next-line:no-unused-expression1137 expect(result.success).to.be.false;1138 });1139}11401141export async function getBalance(1142 api: ApiPromise,1143 collectionId: number,1144 owner: string | CrossAccountId,1145 token: number,1146): Promise<bigint> {1147 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1148}1149export async function getTokenOwner(1150 api: ApiPromise,1151 collectionId: number,1152 token: number,1153): Promise<CrossAccountId> {1154 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1155 if (owner == null) throw new Error('owner == null');1156 return normalizeAccountId(owner);1157}1158export async function getTopmostTokenOwner(1159 api: ApiPromise,1160 collectionId: number,1161 token: number,1162): Promise<CrossAccountId> {1163 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1164 if (owner == null) throw new Error('owner == null');1165 return normalizeAccountId(owner);1166}1167export async function getTokenChildren(1168 api: ApiPromise,1169 collectionId: number,1170 tokenId: number,1171): Promise<UpDataStructsTokenChild[]> {1172 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1173}1174export async function isTokenExists(1175 api: ApiPromise,1176 collectionId: number,1177 token: number,1178): Promise<boolean> {1179 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1180}1181export async function getLastTokenId(1182 api: ApiPromise,1183 collectionId: number,1184): Promise<number> {1185 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1186}1187export async function getAdminList(1188 api: ApiPromise,1189 collectionId: number,1190): Promise<string[]> {1191 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1192}1193export async function getTokenProperties(1194 api: ApiPromise,1195 collectionId: number,1196 tokenId: number,1197 propertyKeys: string[],1198): Promise<UpDataStructsProperty[]> {1199 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1200}12011202export async function createFungibleItemExpectSuccess(1203 sender: IKeyringPair,1204 collectionId: number,1205 data: CreateFungibleData,1206 owner: CrossAccountId | string = sender.address,1207) {1208 return await usingApi(async (api) => {1209 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12101211 const events = await submitTransactionAsync(sender, tx);1212 const result = getCreateItemResult(events);12131214 expect(result.success).to.be.true;1215 return result.itemId;1216 });1217}12181219export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1220 await usingApi(async (api) => {1221 const to = normalizeAccountId(owner);1222 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12231224 const events = await submitTransactionAsync(sender, tx);1225 const result = getCreateItemsResult(events);12261227 for (const res of result) {1228 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1229 }1230 });1231}12321233export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1234 await usingApi(async (api) => {1235 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12361237 const events = await submitTransactionAsync(sender, tx);1238 const result = getCreateItemsResult(events);12391240 for (const res of result) {1241 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1242 }1243 });1244}12451246export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1247 let newItemId = 0;1248 await usingApi(async (api) => {1249 const to = normalizeAccountId(owner);1250 const itemCountBefore = await getLastTokenId(api, collectionId);1251 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12521253 let tx;1254 if (createMode === 'Fungible') {1255 const createData = {fungible: {value: 10}};1256 tx = api.tx.unique.createItem(collectionId, to, createData as any);1257 } else if (createMode === 'ReFungible') {1258 const createData = {refungible: {pieces: 100}};1259 tx = api.tx.unique.createItem(collectionId, to, createData as any);1260 } else {1261 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1262 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1263 }12641265 const events = await submitTransactionAsync(sender, tx);1266 const result = getCreateItemResult(events);12671268 const itemCountAfter = await getLastTokenId(api, collectionId);1269 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12701271 if (createMode === 'NFT') {1272 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1273 }12741275 // What to expect1276 // tslint:disable-next-line:no-unused-expression1277 expect(result.success).to.be.true;1278 if (createMode === 'Fungible') {1279 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1280 } else {1281 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1282 }1283 expect(collectionId).to.be.equal(result.collectionId);1284 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1285 expect(to).to.be.deep.equal(result.recipient);1286 newItemId = result.itemId;1287 });1288 return newItemId;1289}12901291export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1292 await usingApi(async (api) => {12931294 let tx;1295 if (createMode === 'NFT') {1296 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1297 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1298 } else {1299 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1300 }130113021303 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1304 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1305 const result = getCreateItemResult(events);13061307 expect(result.success).to.be.false;1308 });1309}13101311export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1312 let newItemId = 0;1313 await usingApi(async (api) => {1314 const to = normalizeAccountId(owner);1315 const itemCountBefore = await getLastTokenId(api, collectionId);1316 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13171318 let tx;1319 if (createMode === 'Fungible') {1320 const createData = {fungible: {value: 10}};1321 tx = api.tx.unique.createItem(collectionId, to, createData as any);1322 } else if (createMode === 'ReFungible') {1323 const createData = {refungible: {pieces: 100}};1324 tx = api.tx.unique.createItem(collectionId, to, createData as any);1325 } else {1326 const createData = {nft: {}};1327 tx = api.tx.unique.createItem(collectionId, to, createData as any);1328 }13291330 const events = await submitTransactionAsync(sender, tx);1331 const result = getCreateItemResult(events);13321333 const itemCountAfter = await getLastTokenId(api, collectionId);1334 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13351336 // What to expect1337 // tslint:disable-next-line:no-unused-expression1338 expect(result.success).to.be.true;1339 if (createMode === 'Fungible') {1340 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1341 } else {1342 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1343 }1344 expect(collectionId).to.be.equal(result.collectionId);1345 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1346 expect(to).to.be.deep.equal(result.recipient);1347 newItemId = result.itemId;1348 });1349 return newItemId;1350}13511352export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1353 await usingApi(async (api) => {1354 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13551356 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1357 const result = getCreateItemResult(events);13581359 expect(result.success).to.be.false;1360 });1361}13621363export async function setPublicAccessModeExpectSuccess(1364 sender: IKeyringPair, collectionId: number,1365 accessMode: 'Normal' | 'AllowList',1366) {1367 await usingApi(async (api) => {13681369 // Run the transaction1370 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1371 const events = await submitTransactionAsync(sender, tx);1372 const result = getGenericResult(events);13731374 // Get the collection1375 const collection = await queryCollectionExpectSuccess(api, collectionId);13761377 // What to expect1378 // tslint:disable-next-line:no-unused-expression1379 expect(result.success).to.be.true;1380 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1381 });1382}13831384export async function setPublicAccessModeExpectFail(1385 sender: IKeyringPair, collectionId: number,1386 accessMode: 'Normal' | 'AllowList',1387) {1388 await usingApi(async (api) => {13891390 // Run the transaction1391 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1392 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1393 const result = getGenericResult(events);13941395 // What to expect1396 // tslint:disable-next-line:no-unused-expression1397 expect(result.success).to.be.false;1398 });1399}14001401export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1402 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1403}14041405export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1406 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1407}14081409export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1410 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1411}14121413export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1414 await usingApi(async (api) => {14151416 // Run the transaction1417 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1418 const events = await submitTransactionAsync(sender, tx);1419 const result = getGenericResult(events);1420 expect(result.success).to.be.true;14211422 // Get the collection1423 const collection = await queryCollectionExpectSuccess(api, collectionId);14241425 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1426 });1427}14281429export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1430 await setMintPermissionExpectSuccess(sender, collectionId, true);1431}14321433export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1434 await usingApi(async (api) => {1435 // Run the transaction1436 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1437 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1438 const result = getCreateCollectionResult(events);1439 // tslint:disable-next-line:no-unused-expression1440 expect(result.success).to.be.false;1441 });1442}14431444export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1445 await usingApi(async (api) => {1446 // Run the transaction1447 const tx = api.tx.unique.setChainLimits(limits);1448 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1449 const result = getCreateCollectionResult(events);1450 // tslint:disable-next-line:no-unused-expression1451 expect(result.success).to.be.false;1452 });1453}14541455export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1456 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1457}14581459export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1460 await usingApi(async (api) => {1461 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14621463 // Run the transaction1464 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1465 const events = await submitTransactionAsync(sender, tx);1466 const result = getGenericResult(events);1467 expect(result.success).to.be.true;14681469 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1470 });1471}14721473export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1474 await usingApi(async (api) => {14751476 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14771478 // Run the transaction1479 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1480 const events = await submitTransactionAsync(sender, tx);1481 const result = getGenericResult(events);1482 expect(result.success).to.be.true;14831484 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1485 });1486}14871488export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1489 await usingApi(async (api) => {14901491 // Run the transaction1492 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1493 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1494 const result = getGenericResult(events);14951496 // What to expect1497 // tslint:disable-next-line:no-unused-expression1498 expect(result.success).to.be.false;1499 });1500}15011502export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1503 await usingApi(async (api) => {1504 // Run the transaction1505 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1506 const events = await submitTransactionAsync(sender, tx);1507 const result = getGenericResult(events);15081509 // What to expect1510 // tslint:disable-next-line:no-unused-expression1511 expect(result.success).to.be.true;1512 });1513}15141515export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1516 await usingApi(async (api) => {1517 // Run the transaction1518 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1519 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1520 const result = getGenericResult(events);15211522 // What to expect1523 // tslint:disable-next-line:no-unused-expression1524 expect(result.success).to.be.false;1525 });1526}15271528export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1529 : Promise<UpDataStructsRpcCollection | null> => {1530 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1531};15321533export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1534 // set global object - collectionsCount1535 return (await api.rpc.unique.collectionStats()).created.toNumber();1536};15371538export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1539 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1540}15411542export async function waitNewBlocks(blocksCount = 1): Promise<void> {1543 await usingApi(async (api) => {1544 const promise = new Promise<void>(async (resolve) => {1545 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1546 if (blocksCount > 0) {1547 blocksCount--;1548 } else {1549 unsubscribe();1550 resolve();1551 }1552 });1553 });1554 return promise;1555 });1556}