difftreelog
fix for test helpers
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} 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 {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length >= 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92 success: boolean;93 data: T | null;94}9596interface CreateCollectionResult {97 success: boolean;98 collectionId: number;99}100101interface CreateItemResult {102 success: boolean;103 collectionId: number;104 itemId: number;105 recipient?: CrossAccountId;106}107108interface TransferResult {109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 //offchainSchemaLimit: number;140 //constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144 owner: IReFungibleOwner[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;175export function getGenericResult<T>(176 events: EventRecord[],177 expectSection: string,178 expectMethod: string,179 extractAction: (data: GenericEventData) => T180): GenericResult<T>;181182export function getGenericResult<T>(183 events: EventRecord[],184 expectSection?: string,185 expectMethod?: string,186 extractAction?: (data: GenericEventData) => T,187): GenericResult<T> {188 let success = false;189 let successData = null;190191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method === 'ExtrinsicSuccess') {194 success = true;195 } else if ((expectSection == section) && (expectMethod == method)) {196 successData = extractAction!(data as any);197 }198 });199200 const result: GenericResult<T> = {201 success,202 data: successData,203 };204 return result;205}206207export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {208 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));209 const result: CreateCollectionResult = {210 success: genericResult.success,211 collectionId: genericResult.data ?? 0,212 };213 return result;214}215216export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {217 const results: CreateItemResult[] = [];218 219 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {220 const collectionId = parseInt(data[0].toString(), 10);221 const itemId = parseInt(data[1].toString(), 10);222 const recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success: true,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 return results;233 });234235 if (!genericResult.success) return [];236 return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240 const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [241 parseInt(data[0].toString(), 10),242 parseInt(data[1].toString(), 10),243 normalizeAccountId(data[2].toJSON() as any),244 ]);245246 if (genericResult.data == null) genericResult.data = [0, 0];247248 const result: CreateItemResult = {249 success: genericResult.success,250 collectionId: genericResult.data[0],251 itemId: genericResult.data[1],252 recipient: genericResult.data![2],253 };254 255 return result;256}257258export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {259 for (const {event} of events) {260 if (api.events.common.Transfer.is(event)) {261 const [collection, token, sender, recipient, value] = event.data;262 return {263 collectionId: collection.toNumber(),264 itemId: token.toNumber(),265 sender: normalizeAccountId(sender.toJSON() as any),266 recipient: normalizeAccountId(recipient.toJSON() as any),267 value: value.toBigInt(),268 };269 }270 }271 throw new Error('no transfer event');272}273274interface Nft {275 type: 'NFT';276}277278interface Fungible {279 type: 'Fungible';280 decimalPoints: number;281}282283interface ReFungible {284 type: 'ReFungible';285}286287type CollectionMode = Nft | Fungible | ReFungible;288289export type Property = {290 key: any,291 value: any,292};293294type Permission = {295 mutable: boolean;296 collectionAdmin: boolean;297 tokenOwner: boolean;298}299300type PropertyPermission = {301 key: any;302 permission: Permission;303}304305export type CreateCollectionParams = {306 mode: CollectionMode,307 name: string,308 description: string,309 tokenPrefix: string,310 properties?: Array<Property>,311 propPerm?: Array<PropertyPermission>312};313314const defaultCreateCollectionParams: CreateCollectionParams = {315 description: 'description',316 mode: {type: 'NFT'},317 name: 'name',318 tokenPrefix: 'prefix',319};320321export async function322createCollection(323 api: ApiPromise,324 sender: IKeyringPair,325 params: Partial<CreateCollectionParams> = {},326): Promise<CreateCollectionResult> {327 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};328329 let modeprm = {};330 if (mode.type === 'NFT') {331 modeprm = {nft: null};332 } else if (mode.type === 'Fungible') {333 modeprm = {fungible: mode.decimalPoints};334 } else if (mode.type === 'ReFungible') {335 modeprm = {refungible: null};336 }337338 const tx = api.tx.unique.createCollectionEx({339 name: strToUTF16(name),340 description: strToUTF16(description),341 tokenPrefix: strToUTF16(tokenPrefix),342 mode: modeprm as any,343 });344 const events = await submitTransactionAsync(sender, tx);345 return getCreateCollectionResult(events);346}347348export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {349 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};350351 let collectionId = 0;352 await usingApi(async (api, privateKeyWrapper) => {353 // Get number of collections before the transaction354 const collectionCountBefore = await getCreatedCollectionCount(api);355356 // Run the CreateCollection transaction357 const alicePrivateKey = privateKeyWrapper('//Alice');358359 const result = await createCollection(api, alicePrivateKey, params);360361 // Get number of collections after the transaction362 const collectionCountAfter = await getCreatedCollectionCount(api);363364 // Get the collection365 const collection = await queryCollectionExpectSuccess(api, result.collectionId);366367 // What to expect368 // tslint:disable-next-line:no-unused-expression369 expect(result.success).to.be.true;370 expect(result.collectionId).to.be.equal(collectionCountAfter);371 // tslint:disable-next-line:no-unused-expression372 expect(collection).to.be.not.null;373 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');374 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));375 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);376 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);377 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);378379 collectionId = result.collectionId;380 });381382 return collectionId;383}384385export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {386 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};387388 let collectionId = 0;389 await usingApi(async (api, privateKeyWrapper) => {390 // Get number of collections before the transaction391 const collectionCountBefore = await getCreatedCollectionCount(api);392393 // Run the CreateCollection transaction394 const alicePrivateKey = privateKeyWrapper('//Alice');395396 let modeprm = {};397 if (mode.type === 'NFT') {398 modeprm = {nft: null};399 } else if (mode.type === 'Fungible') {400 modeprm = {fungible: mode.decimalPoints};401 } else if (mode.type === 'ReFungible') {402 modeprm = {refungible: null};403 }404405 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});406 const events = await submitTransactionAsync(alicePrivateKey, tx);407 const result = getCreateCollectionResult(events);408409 // Get number of collections after the transaction410 const collectionCountAfter = await getCreatedCollectionCount(api);411412 // Get the collection413 const collection = await queryCollectionExpectSuccess(api, result.collectionId);414415 // What to expect416 // tslint:disable-next-line:no-unused-expression417 expect(result.success).to.be.true;418 expect(result.collectionId).to.be.equal(collectionCountAfter);419 // tslint:disable-next-line:no-unused-expression420 expect(collection).to.be.not.null;421 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');422 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));423 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);424 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);425 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);426427428 collectionId = result.collectionId;429 });430431 return collectionId;432}433434export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {435 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};436437 await usingApi(async (api, privateKeyWrapper) => {438 // Get number of collections before the transaction439 const collectionCountBefore = await getCreatedCollectionCount(api);440441 // Run the CreateCollection transaction442 const alicePrivateKey = privateKeyWrapper('//Alice');443444 let modeprm = {};445 if (mode.type === 'NFT') {446 modeprm = {nft: null};447 } else if (mode.type === 'Fungible') {448 modeprm = {fungible: mode.decimalPoints};449 } else if (mode.type === 'ReFungible') {450 modeprm = {refungible: null};451 }452453 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});454 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;455456457 // Get number of collections after the transaction458 const collectionCountAfter = await getCreatedCollectionCount(api);459460 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');461 });462}463464export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {465 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};466467 let modeprm = {};468 if (mode.type === 'NFT') {469 modeprm = {nft: null};470 } else if (mode.type === 'Fungible') {471 modeprm = {fungible: mode.decimalPoints};472 } else if (mode.type === 'ReFungible') {473 modeprm = {refungible: null};474 }475476 await usingApi(async (api, privateKeyWrapper) => {477 // Get number of collections before the transaction478 const collectionCountBefore = await getCreatedCollectionCount(api);479480 // Run the CreateCollection transaction481 const alicePrivateKey = privateKeyWrapper('//Alice');482 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484485 // Get number of collections after the transaction486 const collectionCountAfter = await getCreatedCollectionCount(api);487488 // What to expect489 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');490 });491}492493export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {494 let bal = 0n;495 let unused;496 do {497 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;498 unused = privateKeyWrapper(`//${randomSeed}`);499 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();500 } while (bal !== 0n);501 return unused;502}503504export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {505 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();506}507508export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {509 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));510}511512export async function findNotExistingCollection(api: ApiPromise): Promise<number> {513 const totalNumber = await getCreatedCollectionCount(api);514 const newCollection: number = totalNumber + 1;515 return newCollection;516}517518function getDestroyResult(events: EventRecord[]): boolean {519 let success = false;520 events.forEach(({event: {method}}) => {521 if (method == 'ExtrinsicSuccess') {522 success = true;523 }524 });525 return success;526}527528export async function destroyCollectionExpectFailure(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 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;534 });535}536537export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {538 await usingApi(async (api, privateKeyWrapper) => {539 // Run the DestroyCollection transaction540 const alicePrivateKey = privateKeyWrapper(senderSeed);541 const tx = api.tx.unique.destroyCollection(collectionId);542 const events = await submitTransactionAsync(alicePrivateKey, tx);543 const result = getDestroyResult(events);544 expect(result).to.be.true;545546 // What to expect547 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;548 });549}550551export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {552 await usingApi(async (api) => {553 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);554 const events = await submitTransactionAsync(sender, tx);555 const result = getGenericResult(events);556557 expect(result.success).to.be.true;558 });559}560561export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {562 await usingApi(async(api) => {563 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);564 const events = await submitTransactionAsync(sender, tx);565 const result = getGenericResult(events);566567 expect(result.success).to.be.true;568 });569};570571export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {572 await usingApi(async (api) => {573 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);574 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;575 const result = getGenericResult(events);576577 expect(result.success).to.be.false;578 });579}580581export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {582 await usingApi(async (api, privateKeyWrapper) => {583584 // Run the transaction585 const senderPrivateKey = privateKeyWrapper(sender);586 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);587 const events = await submitTransactionAsync(senderPrivateKey, tx);588 const result = getGenericResult(events);589590 // Get the collection591 const collection = await queryCollectionExpectSuccess(api, collectionId);592593 // What to expect594 expect(result.success).to.be.true;595 expect(collection.sponsorship.toJSON()).to.deep.equal({596 unconfirmed: sponsor,597 });598 });599}600601export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {602 await usingApi(async (api, privateKeyWrapper) => {603604 // Run the transaction605 const alicePrivateKey = privateKeyWrapper(sender);606 const tx = api.tx.unique.removeCollectionSponsor(collectionId);607 const events = await submitTransactionAsync(alicePrivateKey, tx);608 const result = getGenericResult(events);609610 // Get the collection611 const collection = await queryCollectionExpectSuccess(api, collectionId);612613 // What to expect614 expect(result.success).to.be.true;615 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});616 });617}618619export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {620 await usingApi(async (api, privateKeyWrapper) => {621622 // Run the transaction623 const alicePrivateKey = privateKeyWrapper(senderSeed);624 const tx = api.tx.unique.removeCollectionSponsor(collectionId);625 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;626 });627}628629export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {630 await usingApi(async (api, privateKeyWrapper) => {631632 // Run the transaction633 const alicePrivateKey = privateKeyWrapper(senderSeed);634 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);635 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;636 });637}638639export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {640 await usingApi(async (api, privateKeyWrapper) => {641642 // Run the transaction643 const sender = privateKeyWrapper(senderSeed);644 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);645 });646}647648export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {649 await usingApi(async (api, privateKeyWrapper) => {650651 // Run the transaction652 const tx = api.tx.unique.confirmSponsorship(collectionId);653 const events = await submitTransactionAsync(sender, tx);654 const result = getGenericResult(events);655656 // Get the collection657 const collection = await queryCollectionExpectSuccess(api, collectionId);658659 // What to expect660 expect(result.success).to.be.true;661 expect(collection.sponsorship.toJSON()).to.be.deep.equal({662 confirmed: sender.address,663 });664 });665}666667668export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {669 await usingApi(async (api, privateKeyWrapper) => {670671 // Run the transaction672 const sender = privateKeyWrapper(senderSeed);673 const tx = api.tx.unique.confirmSponsorship(collectionId);674 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;675 });676}677678export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {679 await usingApi(async (api) => {680 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686}687688export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);691 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 const result = getGenericResult(events);693694 expect(result.success).to.be.false;695 });696}697698export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700 await usingApi(async (api) => {701702 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703 const events = await submitTransactionAsync(sender, tx);704 const result = getGenericResult(events);705706 expect(result.success).to.be.true;707 });708}709710export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {711712 await usingApi(async (api) => {713714 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);715 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;716 const result = getGenericResult(events);717718 expect(result.success).to.be.false;719 });720}721722export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {723 await usingApi(async (api) => {724 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);725 const events = await submitTransactionAsync(sender, tx);726 const result = getGenericResult(events);727728 expect(result.success).to.be.true;729 });730}731732export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {733 await usingApi(async (api) => {734 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);735 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;736 const result = getGenericResult(events);737738 expect(result.success).to.be.false;739 });740}741742export async function getNextSponsored(743 api: ApiPromise,744 collectionId: number,745 account: string | CrossAccountId,746 tokenId: number,747): Promise<number> {748 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));749}750751export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {752 await usingApi(async (api) => {753 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);754 const events = await submitTransactionAsync(sender, tx);755 const result = getGenericResult(events);756757 expect(result.success).to.be.true;758 });759}760761export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {762 let allowlisted = false;763 await usingApi(async (api) => {764 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;765 });766 return allowlisted;767}768769export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {770 await usingApi(async (api) => {771 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 expect(result.success).to.be.true;776 });777}778779export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {780 await usingApi(async (api) => {781 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());782 const events = await submitTransactionAsync(sender, tx);783 const result = getGenericResult(events);784785 expect(result.success).to.be.true;786 });787}788789export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {790 await usingApi(async (api) => {791 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());792 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793 const result = getGenericResult(events);794795 expect(result.success).to.be.false;796 });797}798799export interface CreateFungibleData {800 readonly Value: bigint;801}802803export interface CreateReFungibleData { }804export interface CreateNftData { }805806export type CreateItemData = {807 NFT: CreateNftData;808} | {809 Fungible: CreateFungibleData;810} | {811 ReFungible: CreateReFungibleData;812};813814export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {815 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);816 const events = await submitTransactionAsync(sender, tx);817 return getGenericResult(events).success;818}819820export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {821 await usingApi(async (api) => {822 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);823 // if burning token by admin - use adminButnItemExpectSuccess824 expect(balanceBefore >= BigInt(value)).to.be.true;825826 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;827828 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);829 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);830 });831}832833export async function834approve(835 api: ApiPromise,836 collectionId: number,837 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint = 1,838) {839 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);840 const events = await submitTransactionAsync(owner, approveUniqueTx);841 return getGenericResult(events).success;842}843844export async function845approveExpectSuccess(846 collectionId: number,847 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,848) {849 await usingApi(async (api: ApiPromise) => {850 const result = approve(api, collectionId, tokenId, owner, approved);851 expect(result).to.be.true;852853 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));854 });855}856857export async function adminApproveFromExpectSuccess(858 collectionId: number,859 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,860) {861 await usingApi(async (api: ApiPromise) => {862 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);863 const events = await submitTransactionAsync(admin, approveUniqueTx);864 const result = getGenericResult(events);865 expect(result.success).to.be.true;866867 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));868 });869}870871export async function872transferFrom(873 api: ApiPromise,874 collectionId: number,875 tokenId: number,876 accountApproved: IKeyringPair,877 accountFrom: IKeyringPair | CrossAccountId,878 accountTo: IKeyringPair | CrossAccountId,879 value: number | bigint,880) {881 const from = normalizeAccountId(accountFrom);882 const to = normalizeAccountId(accountTo);883 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);884 const events = await submitTransactionAsync(accountApproved, transferFromTx);885 return getGenericResult(events).success;886}887888export async function889transferFromExpectSuccess(890 collectionId: number,891 tokenId: number,892 accountApproved: IKeyringPair,893 accountFrom: IKeyringPair | CrossAccountId,894 accountTo: IKeyringPair | CrossAccountId,895 value: number | bigint = 1,896 type = 'NFT',897) {898 await usingApi(async (api: ApiPromise) => {899 const from = normalizeAccountId(accountFrom);900 const to = normalizeAccountId(accountTo);901 let balanceBefore = 0n;902 if (type === 'Fungible' || type === 'ReFungible') {903 balanceBefore = await getBalance(api, collectionId, to, tokenId);904 }905 expect(transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;906 if (type === 'NFT') {907 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);908 }909 if (type === 'Fungible') {910 const balanceAfter = await getBalance(api, collectionId, to, tokenId);911 if (JSON.stringify(to) !== JSON.stringify(from)) {912 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));913 } else {914 expect(balanceAfter).to.be.equal(balanceBefore);915 }916 }917 if (type === 'ReFungible') {918 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));919 }920 });921}922923export async function924transferFromExpectFail(925 collectionId: number,926 tokenId: number,927 accountApproved: IKeyringPair,928 accountFrom: IKeyringPair,929 accountTo: IKeyringPair,930 value: number | bigint = 1,931) {932 await usingApi(async (api: ApiPromise) => {933 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);934 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;935 const result = getCreateCollectionResult(events);936 // tslint:disable-next-line:no-unused-expression937 expect(result.success).to.be.false;938 });939}940941/* eslint no-async-promise-executor: "off" */942export async function getBlockNumber(api: ApiPromise): Promise<number> {943 return new Promise<number>(async (resolve) => {944 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {945 unsubscribe();946 resolve(head.number.toNumber());947 });948 });949}950951export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {952 await usingApi(async (api) => {953 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));954 const events = await submitTransactionAsync(sender, changeAdminTx);955 const result = getCreateCollectionResult(events);956 expect(result.success).to.be.true;957 });958}959960export async function adminApproveFromExpectFail(961 collectionId: number,962 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,963) {964 await usingApi(async (api: ApiPromise) => {965 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);966 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;967 const result = getGenericResult(events);968 expect(result.success).to.be.false;969 });970}971972export async function973getFreeBalance(account: IKeyringPair): Promise<bigint> {974 let balance = 0n;975 await usingApi(async (api) => {976 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());977 });978979 return balance;980}981982export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {983 const tx = api.tx.balances.transfer(target, amount);984 const events = await submitTransactionAsync(source, tx);985 const result = getGenericResult(events);986 expect(result.success).to.be.true;987}988989export async function990scheduleExpectSuccess(991 operationTx: any,992 sender: IKeyringPair,993 blockSchedule: number,994 scheduledId: string,995 period = 1,996 repetitions = 1,997) {998 await usingApi(async (api: ApiPromise) => {999 const blockNumber: number | undefined = await getBlockNumber(api);1000 const expectedBlockNumber = blockNumber + blockSchedule;10011002 expect(blockNumber).to.be.greaterThan(0);1003 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1004 scheduledId,1005 expectedBlockNumber, 1006 repetitions > 1 ? [period, repetitions] : null, 1007 0, 1008 {value: operationTx as any},1009 );10101011 const events = await submitTransactionAsync(sender, scheduleTx);1012 expect(getGenericResult(events).success).to.be.true;1013 });1014}10151016export async function1017scheduleExpectFailure(1018 operationTx: any,1019 sender: IKeyringPair,1020 blockSchedule: number,1021 scheduledId: string,1022 period = 1,1023 repetitions = 1,1024) {1025 await usingApi(async (api: ApiPromise) => {1026 const blockNumber: number | undefined = await getBlockNumber(api);1027 const expectedBlockNumber = blockNumber + blockSchedule;10281029 expect(blockNumber).to.be.greaterThan(0);1030 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1031 scheduledId,1032 expectedBlockNumber, 1033 repetitions <= 1 ? null : [period, repetitions], 1034 0, 1035 {value: operationTx as any},1036 );10371038 //const events = 1039 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1040 //expect(getGenericResult(events).success).to.be.false;1041 });1042}10431044export async function1045scheduleTransferAndWaitExpectSuccess(1046 collectionId: number,1047 tokenId: number,1048 sender: IKeyringPair,1049 recipient: IKeyringPair,1050 value: number | bigint = 1,1051 blockSchedule: number,1052 scheduledId: string,1053) {1054 await usingApi(async (api: ApiPromise) => {1055 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10561057 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10581059 // sleep for n + 1 blocks1060 await waitNewBlocks(blockSchedule + 1);10611062 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10631064 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1065 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1066 });1067}10681069export async function1070scheduleTransferExpectSuccess(1071 collectionId: number,1072 tokenId: number,1073 sender: IKeyringPair,1074 recipient: IKeyringPair,1075 value: number | bigint = 1,1076 blockSchedule: number,1077 scheduledId: string,1078) {1079 await usingApi(async (api: ApiPromise) => {1080 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10811082 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10831084 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1085 });1086}10871088export async function1089scheduleTransferFundsPeriodicExpectSuccess(1090 amount: bigint,1091 sender: IKeyringPair,1092 recipient: IKeyringPair,1093 blockSchedule: number,1094 scheduledId: string,1095 period: number,1096 repetitions: number,1097) {1098 await usingApi(async (api: ApiPromise) => {1099 const transferTx = api.tx.balances.transfer(recipient.address, amount);11001101 const balanceBefore = await getFreeBalance(recipient);1102 1103 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11041105 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1106 });1107}11081109export async function1110transfer(1111 api: ApiPromise,1112 collectionId: number,1113 tokenId: number,1114 sender: IKeyringPair,1115 recipient: IKeyringPair | CrossAccountId,1116 value: number | bigint,1117) : Promise<boolean> {1118 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1119 const events = await executeTransaction(api, sender, transferTx);1120 return getGenericResult(events).success;1121}11221123export async function1124transferExpectSuccess(1125 collectionId: number,1126 tokenId: number,1127 sender: IKeyringPair,1128 recipient: IKeyringPair | CrossAccountId,1129 value: number | bigint = 1,1130 type = 'NFT',1131) {1132 await usingApi(async (api: ApiPromise) => {1133 const from = normalizeAccountId(sender);1134 const to = normalizeAccountId(recipient);11351136 let balanceBefore = 0n;1137 if (type === 'Fungible' || type === 'ReFungible') {1138 balanceBefore = await getBalance(api, collectionId, to, tokenId);1139 }11401141 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1142 const events = await executeTransaction(api, sender, transferTx);1143 const result = getTransferResult(api, events);11441145 expect(result.collectionId).to.be.equal(collectionId);1146 expect(result.itemId).to.be.equal(tokenId);1147 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1148 expect(result.recipient).to.be.deep.equal(to);1149 expect(result.value).to.be.equal(BigInt(value));11501151 if (type === 'NFT') {1152 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1153 }1154 if (type === 'Fungible' || type === 'ReFungible') {1155 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1156 if (JSON.stringify(to) !== JSON.stringify(from)) {1157 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1158 } else {1159 expect(balanceAfter).to.be.equal(balanceBefore);1160 }1161 }1162 });1163}11641165export async function1166transferExpectFailure(1167 collectionId: number,1168 tokenId: number,1169 sender: IKeyringPair,1170 recipient: IKeyringPair | CrossAccountId,1171 value: number | bigint = 1,1172) {1173 await usingApi(async (api: ApiPromise) => {1174 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1175 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1176 const result = getGenericResult(events);1177 // if (events && Array.isArray(events)) {1178 // const result = getCreateCollectionResult(events);1179 // tslint:disable-next-line:no-unused-expression1180 expect(result.success).to.be.false;1181 //}1182 });1183}11841185export async function1186approveExpectFail(1187 collectionId: number,1188 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1189) {1190 await usingApi(async (api: ApiPromise) => {1191 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1192 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1193 const result = getCreateCollectionResult(events);1194 // tslint:disable-next-line:no-unused-expression1195 expect(result.success).to.be.false;1196 });1197}11981199export async function getBalance(1200 api: ApiPromise,1201 collectionId: number,1202 owner: string | CrossAccountId | IKeyringPair,1203 token: number,1204): Promise<bigint> {1205 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1206}1207export async function getTokenOwner(1208 api: ApiPromise,1209 collectionId: number,1210 token: number,1211): Promise<CrossAccountId> {1212 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1213 if (owner == null) throw new Error('owner == null');1214 return normalizeAccountId(owner);1215}1216export async function getTopmostTokenOwner(1217 api: ApiPromise,1218 collectionId: number,1219 token: number,1220): Promise<CrossAccountId> {1221 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1222 if (owner == null) throw new Error('owner == null');1223 return normalizeAccountId(owner);1224}1225export async function getTokenChildren(1226 api: ApiPromise,1227 collectionId: number,1228 tokenId: number,1229): Promise<UpDataStructsTokenChild[]> {1230 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1231}1232export async function isTokenExists(1233 api: ApiPromise,1234 collectionId: number,1235 token: number,1236): Promise<boolean> {1237 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1238}1239export async function getLastTokenId(1240 api: ApiPromise,1241 collectionId: number,1242): Promise<number> {1243 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1244}1245export async function getAdminList(1246 api: ApiPromise,1247 collectionId: number,1248): Promise<string[]> {1249 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1250}1251export async function getTokenProperties(1252 api: ApiPromise,1253 collectionId: number,1254 tokenId: number,1255 propertyKeys: string[],1256): Promise<UpDataStructsProperty[]> {1257 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1258}12591260export async function createFungibleItemExpectSuccess(1261 sender: IKeyringPair,1262 collectionId: number,1263 data: CreateFungibleData,1264 owner: CrossAccountId | string = sender.address,1265) {1266 return await usingApi(async (api) => {1267 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12681269 const events = await submitTransactionAsync(sender, tx);1270 const result = getCreateItemResult(events);12711272 expect(result.success).to.be.true;1273 return result.itemId;1274 });1275}12761277export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1278 await usingApi(async (api) => {1279 const to = normalizeAccountId(owner);1280 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12811282 const events = await submitTransactionAsync(sender, tx);1283 expect(getGenericResult(events).success).to.be.true;1284 });1285}12861287export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1288 await usingApi(async (api) => {1289 const to = normalizeAccountId(owner);1290 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12911292 const events = await submitTransactionAsync(sender, tx);1293 const result = getCreateItemsResult(events);12941295 for (const res of result) {1296 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1297 }1298 });1299}13001301export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1302 await usingApi(async (api) => {1303 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13041305 const events = await submitTransactionAsync(sender, tx);1306 const result = getCreateItemsResult(events);13071308 for (const res of result) {1309 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1310 }1311 });1312}13131314export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1315 let newItemId = 0;1316 await usingApi(async (api) => {1317 const to = normalizeAccountId(owner);1318 const itemCountBefore = await getLastTokenId(api, collectionId);1319 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13201321 let tx;1322 if (createMode === 'Fungible') {1323 const createData = {fungible: {value: 10}};1324 tx = api.tx.unique.createItem(collectionId, to, createData as any);1325 } else if (createMode === 'ReFungible') {1326 const createData = {refungible: {pieces: 100}};1327 tx = api.tx.unique.createItem(collectionId, to, createData as any);1328 } else {1329 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1330 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1331 }13321333 const events = await submitTransactionAsync(sender, tx);1334 const result = getCreateItemResult(events);13351336 const itemCountAfter = await getLastTokenId(api, collectionId);1337 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13381339 if (createMode === 'NFT') {1340 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1341 }13421343 // What to expect1344 // tslint:disable-next-line:no-unused-expression1345 expect(result.success).to.be.true;1346 if (createMode === 'Fungible') {1347 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1348 } else {1349 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1350 }1351 expect(collectionId).to.be.equal(result.collectionId);1352 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1353 expect(to).to.be.deep.equal(result.recipient);1354 newItemId = result.itemId;1355 });1356 return newItemId;1357}13581359export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1360 await usingApi(async (api) => {13611362 let tx;1363 if (createMode === 'NFT') {1364 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1365 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1366 } else {1367 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1368 }136913701371 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1372 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1373 const result = getCreateItemResult(events);13741375 expect(result.success).to.be.false;1376 });1377}13781379export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1380 let newItemId = 0;1381 await usingApi(async (api) => {1382 const to = normalizeAccountId(owner);1383 const itemCountBefore = await getLastTokenId(api, collectionId);1384 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13851386 let tx;1387 if (createMode === 'Fungible') {1388 const createData = {fungible: {value: 10}};1389 tx = api.tx.unique.createItem(collectionId, to, createData as any);1390 } else if (createMode === 'ReFungible') {1391 const createData = {refungible: {pieces: 100}};1392 tx = api.tx.unique.createItem(collectionId, to, createData as any);1393 } else {1394 const createData = {nft: {}};1395 tx = api.tx.unique.createItem(collectionId, to, createData as any);1396 }13971398 const events = await submitTransactionAsync(sender, tx);1399 const result = getCreateItemResult(events);14001401 const itemCountAfter = await getLastTokenId(api, collectionId);1402 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14031404 // What to expect1405 // tslint:disable-next-line:no-unused-expression1406 expect(result.success).to.be.true;1407 if (createMode === 'Fungible') {1408 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1409 } else {1410 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1411 }1412 expect(collectionId).to.be.equal(result.collectionId);1413 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1414 expect(to).to.be.deep.equal(result.recipient);1415 newItemId = result.itemId;1416 });1417 return newItemId;1418}14191420export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1421 const createData = {refungible: {pieces: amount}};1422 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14231424 const events = await submitTransactionAsync(sender, tx);1425 return getCreateItemResult(events);1426}14271428export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1429 await usingApi(async (api) => {1430 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14311432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1433 const result = getCreateItemResult(events);14341435 expect(result.success).to.be.false;1436 });1437}14381439export async function setPublicAccessModeExpectSuccess(1440 sender: IKeyringPair, collectionId: number,1441 accessMode: 'Normal' | 'AllowList',1442) {1443 await usingApi(async (api) => {14441445 // Run the transaction1446 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1447 const events = await submitTransactionAsync(sender, tx);1448 const result = getGenericResult(events);14491450 // Get the collection1451 const collection = await queryCollectionExpectSuccess(api, collectionId);14521453 // What to expect1454 // tslint:disable-next-line:no-unused-expression1455 expect(result.success).to.be.true;1456 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1457 });1458}14591460export async function setPublicAccessModeExpectFail(1461 sender: IKeyringPair, collectionId: number,1462 accessMode: 'Normal' | 'AllowList',1463) {1464 await usingApi(async (api) => {14651466 // Run the transaction1467 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1468 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1469 const result = getGenericResult(events);14701471 // What to expect1472 // tslint:disable-next-line:no-unused-expression1473 expect(result.success).to.be.false;1474 });1475}14761477export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1478 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1479}14801481export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1482 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1483}14841485export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1486 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1487}14881489export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1490 await usingApi(async (api) => {14911492 // Run the transaction1493 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1494 const events = await submitTransactionAsync(sender, tx);1495 const result = getGenericResult(events);1496 expect(result.success).to.be.true;14971498 // Get the collection1499 const collection = await queryCollectionExpectSuccess(api, collectionId);15001501 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1502 });1503}15041505export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1506 await setMintPermissionExpectSuccess(sender, collectionId, true);1507}15081509export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1510 await usingApi(async (api) => {1511 // Run the transaction1512 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1513 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1514 const result = getCreateCollectionResult(events);1515 // tslint:disable-next-line:no-unused-expression1516 expect(result.success).to.be.false;1517 });1518}15191520export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1521 await usingApi(async (api) => {1522 // Run the transaction1523 const tx = api.tx.unique.setChainLimits(limits);1524 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1525 const result = getCreateCollectionResult(events);1526 // tslint:disable-next-line:no-unused-expression1527 expect(result.success).to.be.false;1528 });1529}15301531export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1532 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1533}15341535export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1536 await usingApi(async (api) => {1537 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15381539 // Run the transaction1540 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1541 const events = await submitTransactionAsync(sender, tx);1542 const result = getGenericResult(events);1543 expect(result.success).to.be.true;15441545 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1546 });1547}15481549export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1550 await usingApi(async (api) => {15511552 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;15531554 // Run the transaction1555 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1556 const events = await submitTransactionAsync(sender, tx);1557 const result = getGenericResult(events);1558 expect(result.success).to.be.true;15591560 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1561 });1562}15631564export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1565 await usingApi(async (api) => {15661567 // Run the transaction1568 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1569 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1570 const result = getGenericResult(events);15711572 // What to expect1573 // tslint:disable-next-line:no-unused-expression1574 expect(result.success).to.be.false;1575 });1576}15771578export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1579 await usingApi(async (api) => {1580 // Run the transaction1581 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1582 const events = await submitTransactionAsync(sender, tx);1583 const result = getGenericResult(events);15841585 // What to expect1586 // tslint:disable-next-line:no-unused-expression1587 expect(result.success).to.be.true;1588 });1589}15901591export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1592 await usingApi(async (api) => {1593 // Run the transaction1594 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1596 const result = getGenericResult(events);15971598 // What to expect1599 // tslint:disable-next-line:no-unused-expression1600 expect(result.success).to.be.false;1601 });1602}16031604export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1605 : Promise<UpDataStructsRpcCollection | null> => {1606 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1607};16081609export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1610 // set global object - collectionsCount1611 return (await api.rpc.unique.collectionStats()).created.toNumber();1612};16131614export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1615 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1616}16171618export async function waitNewBlocks(blocksCount = 1): Promise<void> {1619 await usingApi(async (api) => {1620 const promise = new Promise<void>(async (resolve) => {1621 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1622 if (blocksCount > 0) {1623 blocksCount--;1624 } else {1625 unsubscribe();1626 resolve();1627 }1628 });1629 });1630 return promise;1631 });1632}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} 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 {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';28import {hexToStr, strToUTF16, utf16ToStr} from './util';29import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';30import {UpDataStructsTokenChild} from '../interfaces';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36 Substrate: string,37} | {38 Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42 if (typeof input === 'string') {43 if (input.length >= 47) {44 return {Substrate: input};45 } else if (input.length === 42 && input.startsWith('0x')) {46 return {Ethereum: input.toLowerCase()};47 } else if (input.length === 40 && !input.startsWith('0x')) {48 return {Ethereum: '0x' + input.toLowerCase()};49 } else {50 throw new Error(`Unknown address format: "${input}"`);51 }52 }53 if ('address' in input) {54 return {Substrate: input.address};55 }56 if ('Ethereum' in input) {57 return {58 Ethereum: input.Ethereum.toLowerCase(),59 };60 } else if ('ethereum' in input) {61 return {62 Ethereum: (input as any).ethereum.toLowerCase(),63 };64 } else if ('Substrate' in input) {65 return input;66 } else if ('substrate' in input) {67 return {68 Substrate: (input as any).substrate,69 };70 }7172 // AccountId73 return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76 input = normalizeAccountId(input);77 if ('Substrate' in input) {78 return input.Substrate;79 } else {80 return evmToAddress(input.Ethereum);81 }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091interface GenericResult<T> {92 success: boolean;93 data: T | null;94}9596interface CreateCollectionResult {97 success: boolean;98 collectionId: number;99}100101interface CreateItemResult {102 success: boolean;103 collectionId: number;104 itemId: number;105 recipient?: CrossAccountId;106}107108interface TransferResult {109 collectionId: number;110 itemId: number;111 sender?: CrossAccountId;112 recipient?: CrossAccountId;113 value: bigint;114}115116interface IReFungibleOwner {117 fraction: BN;118 owner: number[];119}120121interface IGetMessage {122 checkMsgUnqMethod: string;123 checkMsgTrsMethod: string;124 checkMsgSysMethod: string;125}126127export interface IFungibleTokenDataType {128 value: number;129}130131export interface IChainLimits {132 collectionNumbersLimit: number;133 accountTokenOwnershipLimit: number;134 collectionsAdminsLimit: number;135 customDataLimit: number;136 nftSponsorTransferTimeout: number;137 fungibleSponsorTransferTimeout: number;138 refungibleSponsorTransferTimeout: number;139 //offchainSchemaLimit: number;140 //constOnChainSchemaLimit: number;141}142143export interface IReFungibleTokenDataType {144 owner: IReFungibleOwner[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult<T>(events: EventRecord[]): GenericResult<T>;175export function getGenericResult<T>(176 events: EventRecord[],177 expectSection: string,178 expectMethod: string,179 extractAction: (data: GenericEventData) => T180): GenericResult<T>;181182export function getGenericResult<T>(183 events: EventRecord[],184 expectSection?: string,185 expectMethod?: string,186 extractAction?: (data: GenericEventData) => T,187): GenericResult<T> {188 let success = false;189 let successData = null;190191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method === 'ExtrinsicSuccess') {194 success = true;195 } else if ((expectSection == section) && (expectMethod == method)) {196 successData = extractAction!(data as any);197 }198 });199200 const result: GenericResult<T> = {201 success,202 data: successData,203 };204 return result;205}206207export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {208 const genericResult = getGenericResult(events, 'common', 'CollectionCreated', (data) => parseInt(data[0].toString(), 10));209 const result: CreateCollectionResult = {210 success: genericResult.success,211 collectionId: genericResult.data ?? 0,212 };213 return result;214}215216export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {217 const results: CreateItemResult[] = [];218 219 const genericResult = getGenericResult<CreateItemResult[]>(events, 'common', 'ItemCreated', (data) => {220 const collectionId = parseInt(data[0].toString(), 10);221 const itemId = parseInt(data[1].toString(), 10);222 const recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success: true,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 return results;233 });234235 if (!genericResult.success) return [];236 return results;237}238239export function getCreateItemResult(events: EventRecord[]): CreateItemResult {240 const genericResult = getGenericResult<[number, number, CrossAccountId?]>(events, 'common', 'ItemCreated', (data) => [241 parseInt(data[0].toString(), 10),242 parseInt(data[1].toString(), 10),243 normalizeAccountId(data[2].toJSON() as any),244 ]);245246 if (genericResult.data == null) genericResult.data = [0, 0];247248 const result: CreateItemResult = {249 success: genericResult.success,250 collectionId: genericResult.data[0],251 itemId: genericResult.data[1],252 recipient: genericResult.data![2],253 };254 255 return result;256}257258export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {259 for (const {event} of events) {260 if (api.events.common.Transfer.is(event)) {261 const [collection, token, sender, recipient, value] = event.data;262 return {263 collectionId: collection.toNumber(),264 itemId: token.toNumber(),265 sender: normalizeAccountId(sender.toJSON() as any),266 recipient: normalizeAccountId(recipient.toJSON() as any),267 value: value.toBigInt(),268 };269 }270 }271 throw new Error('no transfer event');272}273274interface Nft {275 type: 'NFT';276}277278interface Fungible {279 type: 'Fungible';280 decimalPoints: number;281}282283interface ReFungible {284 type: 'ReFungible';285}286287type CollectionMode = Nft | Fungible | ReFungible;288289export type Property = {290 key: any,291 value: any,292};293294type Permission = {295 mutable: boolean;296 collectionAdmin: boolean;297 tokenOwner: boolean;298}299300type PropertyPermission = {301 key: any;302 permission: Permission;303}304305export type CreateCollectionParams = {306 mode: CollectionMode,307 name: string,308 description: string,309 tokenPrefix: string,310 properties?: Array<Property>,311 propPerm?: Array<PropertyPermission>312};313314const defaultCreateCollectionParams: CreateCollectionParams = {315 description: 'description',316 mode: {type: 'NFT'},317 name: 'name',318 tokenPrefix: 'prefix',319};320321export async function322createCollection(323 api: ApiPromise,324 sender: IKeyringPair,325 params: Partial<CreateCollectionParams> = {},326): Promise<CreateCollectionResult> {327 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};328329 let modeprm = {};330 if (mode.type === 'NFT') {331 modeprm = {nft: null};332 } else if (mode.type === 'Fungible') {333 modeprm = {fungible: mode.decimalPoints};334 } else if (mode.type === 'ReFungible') {335 modeprm = {refungible: null};336 }337338 const tx = api.tx.unique.createCollectionEx({339 name: strToUTF16(name),340 description: strToUTF16(description),341 tokenPrefix: strToUTF16(tokenPrefix),342 mode: modeprm as any,343 });344 const events = await submitTransactionAsync(sender, tx);345 return getCreateCollectionResult(events);346}347348export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {349 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};350351 let collectionId = 0;352 await usingApi(async (api, privateKeyWrapper) => {353 // Get number of collections before the transaction354 const collectionCountBefore = await getCreatedCollectionCount(api);355356 // Run the CreateCollection transaction357 const alicePrivateKey = privateKeyWrapper('//Alice');358359 const result = await createCollection(api, alicePrivateKey, params);360361 // Get number of collections after the transaction362 const collectionCountAfter = await getCreatedCollectionCount(api);363364 // Get the collection365 const collection = await queryCollectionExpectSuccess(api, result.collectionId);366367 // What to expect368 // tslint:disable-next-line:no-unused-expression369 expect(result.success).to.be.true;370 expect(result.collectionId).to.be.equal(collectionCountAfter);371 // tslint:disable-next-line:no-unused-expression372 expect(collection).to.be.not.null;373 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');374 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));375 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);376 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);377 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);378379 collectionId = result.collectionId;380 });381382 return collectionId;383}384385export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {386 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};387388 let collectionId = 0;389 await usingApi(async (api, privateKeyWrapper) => {390 // Get number of collections before the transaction391 const collectionCountBefore = await getCreatedCollectionCount(api);392393 // Run the CreateCollection transaction394 const alicePrivateKey = privateKeyWrapper('//Alice');395396 let modeprm = {};397 if (mode.type === 'NFT') {398 modeprm = {nft: null};399 } else if (mode.type === 'Fungible') {400 modeprm = {fungible: mode.decimalPoints};401 } else if (mode.type === 'ReFungible') {402 modeprm = {refungible: null};403 }404405 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});406 const events = await submitTransactionAsync(alicePrivateKey, tx);407 const result = getCreateCollectionResult(events);408409 // Get number of collections after the transaction410 const collectionCountAfter = await getCreatedCollectionCount(api);411412 // Get the collection413 const collection = await queryCollectionExpectSuccess(api, result.collectionId);414415 // What to expect416 // tslint:disable-next-line:no-unused-expression417 expect(result.success).to.be.true;418 expect(result.collectionId).to.be.equal(collectionCountAfter);419 // tslint:disable-next-line:no-unused-expression420 expect(collection).to.be.not.null;421 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');422 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicePrivateKey));423 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);424 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);425 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);426427428 collectionId = result.collectionId;429 });430431 return collectionId;432}433434export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {435 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};436437 await usingApi(async (api, privateKeyWrapper) => {438 // Get number of collections before the transaction439 const collectionCountBefore = await getCreatedCollectionCount(api);440441 // Run the CreateCollection transaction442 const alicePrivateKey = privateKeyWrapper('//Alice');443444 let modeprm = {};445 if (mode.type === 'NFT') {446 modeprm = {nft: null};447 } else if (mode.type === 'Fungible') {448 modeprm = {fungible: mode.decimalPoints};449 } else if (mode.type === 'ReFungible') {450 modeprm = {refungible: null};451 }452453 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});454 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;455456457 // Get number of collections after the transaction458 const collectionCountAfter = await getCreatedCollectionCount(api);459460 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');461 });462}463464export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {465 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};466467 let modeprm = {};468 if (mode.type === 'NFT') {469 modeprm = {nft: null};470 } else if (mode.type === 'Fungible') {471 modeprm = {fungible: mode.decimalPoints};472 } else if (mode.type === 'ReFungible') {473 modeprm = {refungible: null};474 }475476 await usingApi(async (api, privateKeyWrapper) => {477 // Get number of collections before the transaction478 const collectionCountBefore = await getCreatedCollectionCount(api);479480 // Run the CreateCollection transaction481 const alicePrivateKey = privateKeyWrapper('//Alice');482 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});483 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;484485 // Get number of collections after the transaction486 const collectionCountAfter = await getCreatedCollectionCount(api);487488 // What to expect489 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');490 });491}492493export async function findUnusedAddress(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, seedAddition = ''): Promise<IKeyringPair> {494 let bal = 0n;495 let unused;496 do {497 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;498 unused = privateKeyWrapper(`//${randomSeed}`);499 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();500 } while (bal !== 0n);501 return unused;502}503504export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string | IKeyringPair, approved: CrossAccountId | string | IKeyringPair, tokenId: number) {505 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();506}507508export function findUnusedAddresses(api: ApiPromise, privateKeyWrapper: (account: string) => IKeyringPair, amount: number): Promise<IKeyringPair[]> {509 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, privateKeyWrapper, '_' + Date.now())));510}511512export async function findNotExistingCollection(api: ApiPromise): Promise<number> {513 const totalNumber = await getCreatedCollectionCount(api);514 const newCollection: number = totalNumber + 1;515 return newCollection;516}517518function getDestroyResult(events: EventRecord[]): boolean {519 let success = false;520 events.forEach(({event: {method}}) => {521 if (method == 'ExtrinsicSuccess') {522 success = true;523 }524 });525 return success;526}527528export async function destroyCollectionExpectFailure(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 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;534 });535}536537export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {538 await usingApi(async (api, privateKeyWrapper) => {539 // Run the DestroyCollection transaction540 const alicePrivateKey = privateKeyWrapper(senderSeed);541 const tx = api.tx.unique.destroyCollection(collectionId);542 const events = await submitTransactionAsync(alicePrivateKey, tx);543 const result = getDestroyResult(events);544 expect(result).to.be.true;545546 // What to expect547 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;548 });549}550551export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {552 await usingApi(async (api) => {553 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);554 const events = await submitTransactionAsync(sender, tx);555 const result = getGenericResult(events);556557 expect(result.success).to.be.true;558 });559}560561export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: any) => {562 await usingApi(async(api) => {563 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);564 const events = await submitTransactionAsync(sender, tx);565 const result = getGenericResult(events);566567 expect(result.success).to.be.true;568 });569};570571export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {572 await usingApi(async (api) => {573 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);574 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;575 const result = getGenericResult(events);576577 expect(result.success).to.be.false;578 });579}580581export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {582 await usingApi(async (api, privateKeyWrapper) => {583584 // Run the transaction585 const senderPrivateKey = privateKeyWrapper(sender);586 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);587 const events = await submitTransactionAsync(senderPrivateKey, tx);588 const result = getGenericResult(events);589590 // Get the collection591 const collection = await queryCollectionExpectSuccess(api, collectionId);592593 // What to expect594 expect(result.success).to.be.true;595 expect(collection.sponsorship.toJSON()).to.deep.equal({596 unconfirmed: sponsor,597 });598 });599}600601export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {602 await usingApi(async (api, privateKeyWrapper) => {603604 // Run the transaction605 const alicePrivateKey = privateKeyWrapper(sender);606 const tx = api.tx.unique.removeCollectionSponsor(collectionId);607 const events = await submitTransactionAsync(alicePrivateKey, tx);608 const result = getGenericResult(events);609610 // Get the collection611 const collection = await queryCollectionExpectSuccess(api, collectionId);612613 // What to expect614 expect(result.success).to.be.true;615 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});616 });617}618619export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {620 await usingApi(async (api, privateKeyWrapper) => {621622 // Run the transaction623 const alicePrivateKey = privateKeyWrapper(senderSeed);624 const tx = api.tx.unique.removeCollectionSponsor(collectionId);625 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;626 });627}628629export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {630 await usingApi(async (api, privateKeyWrapper) => {631632 // Run the transaction633 const alicePrivateKey = privateKeyWrapper(senderSeed);634 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);635 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;636 });637}638639export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {640 await usingApi(async (api, privateKeyWrapper) => {641642 // Run the transaction643 const sender = privateKeyWrapper(senderSeed);644 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);645 });646}647648export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {649 await usingApi(async (api, privateKeyWrapper) => {650651 // Run the transaction652 const tx = api.tx.unique.confirmSponsorship(collectionId);653 const events = await submitTransactionAsync(sender, tx);654 const result = getGenericResult(events);655656 // Get the collection657 const collection = await queryCollectionExpectSuccess(api, collectionId);658659 // What to expect660 expect(result.success).to.be.true;661 expect(collection.sponsorship.toJSON()).to.be.deep.equal({662 confirmed: sender.address,663 });664 });665}666667668export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {669 await usingApi(async (api, privateKeyWrapper) => {670671 // Run the transaction672 const sender = privateKeyWrapper(senderSeed);673 const tx = api.tx.unique.confirmSponsorship(collectionId);674 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;675 });676}677678export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {679 await usingApi(async (api) => {680 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);681 const events = await submitTransactionAsync(sender, tx);682 const result = getGenericResult(events);683684 expect(result.success).to.be.true;685 });686}687688export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {689 await usingApi(async (api) => {690 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);691 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;692 const result = getGenericResult(events);693694 expect(result.success).to.be.false;695 });696}697698export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {699700 await usingApi(async (api) => {701702 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);703 const events = await submitTransactionAsync(sender, tx);704 const result = getGenericResult(events);705706 expect(result.success).to.be.true;707 });708}709710export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {711712 await usingApi(async (api) => {713714 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);715 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;716 const result = getGenericResult(events);717718 expect(result.success).to.be.false;719 });720}721722export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {723 await usingApi(async (api) => {724 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);725 const events = await submitTransactionAsync(sender, tx);726 const result = getGenericResult(events);727728 expect(result.success).to.be.true;729 });730}731732export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {733 await usingApi(async (api) => {734 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);735 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;736 const result = getGenericResult(events);737738 expect(result.success).to.be.false;739 });740}741742export async function getNextSponsored(743 api: ApiPromise,744 collectionId: number,745 account: string | CrossAccountId,746 tokenId: number,747): Promise<number> {748 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));749}750751export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {752 await usingApi(async (api) => {753 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);754 const events = await submitTransactionAsync(sender, tx);755 const result = getGenericResult(events);756757 expect(result.success).to.be.true;758 });759}760761export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {762 let allowlisted = false;763 await usingApi(async (api) => {764 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;765 });766 return allowlisted;767}768769export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {770 await usingApi(async (api) => {771 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());772 const events = await submitTransactionAsync(sender, tx);773 const result = getGenericResult(events);774775 expect(result.success).to.be.true;776 });777}778779export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {780 await usingApi(async (api) => {781 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());782 const events = await submitTransactionAsync(sender, tx);783 const result = getGenericResult(events);784785 expect(result.success).to.be.true;786 });787}788789export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {790 await usingApi(async (api) => {791 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());792 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;793 const result = getGenericResult(events);794795 expect(result.success).to.be.false;796 });797}798799export interface CreateFungibleData {800 readonly Value: bigint;801}802803export interface CreateReFungibleData { }804export interface CreateNftData { }805806export type CreateItemData = {807 NFT: CreateNftData;808} | {809 Fungible: CreateFungibleData;810} | {811 ReFungible: CreateReFungibleData;812};813814export async function burnItem(api: ApiPromise, sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint) : Promise<boolean> {815 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);816 const events = await submitTransactionAsync(sender, tx);817 return getGenericResult(events).success;818}819820export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value: number | bigint = 1) {821 await usingApi(async (api) => {822 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);823 // if burning token by admin - use adminButnItemExpectSuccess824 expect(balanceBefore >= BigInt(value)).to.be.true;825826 expect(await burnItem(api, sender, collectionId, tokenId, value)).to.be.true;827828 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);829 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);830 });831}832833export async function834approve(835 api: ApiPromise,836 collectionId: number,837 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string | IKeyringPair, amount: number | bigint,838) {839 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);840 const events = await submitTransactionAsync(owner, approveUniqueTx);841 return getGenericResult(events).success;842}843844export async function845approveExpectSuccess(846 collectionId: number,847 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,848) {849 await usingApi(async (api: ApiPromise) => {850 const result = await approve(api, collectionId, tokenId, owner, approved, amount);851 expect(result).to.be.true;852853 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));854 });855}856857export async function adminApproveFromExpectSuccess(858 collectionId: number,859 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,860) {861 await usingApi(async (api: ApiPromise) => {862 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);863 const events = await submitTransactionAsync(admin, approveUniqueTx);864 const result = getGenericResult(events);865 expect(result.success).to.be.true;866867 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));868 });869}870871export async function872transferFrom(873 api: ApiPromise,874 collectionId: number,875 tokenId: number,876 accountApproved: IKeyringPair,877 accountFrom: IKeyringPair | CrossAccountId,878 accountTo: IKeyringPair | CrossAccountId,879 value: number | bigint,880) {881 const from = normalizeAccountId(accountFrom);882 const to = normalizeAccountId(accountTo);883 const transferFromTx = api.tx.unique.transferFrom(from, to, collectionId, tokenId, value);884 const events = await submitTransactionAsync(accountApproved, transferFromTx);885 return getGenericResult(events).success;886}887888export async function889transferFromExpectSuccess(890 collectionId: number,891 tokenId: number,892 accountApproved: IKeyringPair,893 accountFrom: IKeyringPair | CrossAccountId,894 accountTo: IKeyringPair | CrossAccountId,895 value: number | bigint = 1,896 type = 'NFT',897) {898 await usingApi(async (api: ApiPromise) => {899 const from = normalizeAccountId(accountFrom);900 const to = normalizeAccountId(accountTo);901 let balanceBefore = 0n;902 if (type === 'Fungible' || type === 'ReFungible') {903 balanceBefore = await getBalance(api, collectionId, to, tokenId);904 }905 expect(await transferFrom(api, collectionId, tokenId, accountApproved, accountFrom, accountTo, value)).to.be.true;906 if (type === 'NFT') {907 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);908 }909 if (type === 'Fungible') {910 const balanceAfter = await getBalance(api, collectionId, to, tokenId);911 if (JSON.stringify(to) !== JSON.stringify(from)) {912 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));913 } else {914 expect(balanceAfter).to.be.equal(balanceBefore);915 }916 }917 if (type === 'ReFungible') {918 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));919 }920 });921}922923export async function924transferFromExpectFail(925 collectionId: number,926 tokenId: number,927 accountApproved: IKeyringPair,928 accountFrom: IKeyringPair,929 accountTo: IKeyringPair,930 value: number | bigint = 1,931) {932 await usingApi(async (api: ApiPromise) => {933 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);934 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;935 const result = getCreateCollectionResult(events);936 // tslint:disable-next-line:no-unused-expression937 expect(result.success).to.be.false;938 });939}940941/* eslint no-async-promise-executor: "off" */942export async function getBlockNumber(api: ApiPromise): Promise<number> {943 return new Promise<number>(async (resolve) => {944 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {945 unsubscribe();946 resolve(head.number.toNumber());947 });948 });949}950951export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {952 await usingApi(async (api) => {953 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));954 const events = await submitTransactionAsync(sender, changeAdminTx);955 const result = getCreateCollectionResult(events);956 expect(result.success).to.be.true;957 });958}959960export async function adminApproveFromExpectFail(961 collectionId: number,962 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,963) {964 await usingApi(async (api: ApiPromise) => {965 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);966 const events = await expect(submitTransactionAsync(admin, approveUniqueTx)).to.be.rejected;967 const result = getGenericResult(events);968 expect(result.success).to.be.false;969 });970}971972export async function973getFreeBalance(account: IKeyringPair): Promise<bigint> {974 let balance = 0n;975 await usingApi(async (api) => {976 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());977 });978979 return balance;980}981982export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {983 const tx = api.tx.balances.transfer(target, amount);984 const events = await submitTransactionAsync(source, tx);985 const result = getGenericResult(events);986 expect(result.success).to.be.true;987}988989export async function990scheduleExpectSuccess(991 operationTx: any,992 sender: IKeyringPair,993 blockSchedule: number,994 scheduledId: string,995 period = 1,996 repetitions = 1,997) {998 await usingApi(async (api: ApiPromise) => {999 const blockNumber: number | undefined = await getBlockNumber(api);1000 const expectedBlockNumber = blockNumber + blockSchedule;10011002 expect(blockNumber).to.be.greaterThan(0);1003 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1004 scheduledId,1005 expectedBlockNumber, 1006 repetitions > 1 ? [period, repetitions] : null, 1007 0, 1008 {value: operationTx as any},1009 );10101011 const events = await submitTransactionAsync(sender, scheduleTx);1012 expect(getGenericResult(events).success).to.be.true;1013 });1014}10151016export async function1017scheduleExpectFailure(1018 operationTx: any,1019 sender: IKeyringPair,1020 blockSchedule: number,1021 scheduledId: string,1022 period = 1,1023 repetitions = 1,1024) {1025 await usingApi(async (api: ApiPromise) => {1026 const blockNumber: number | undefined = await getBlockNumber(api);1027 const expectedBlockNumber = blockNumber + blockSchedule;10281029 expect(blockNumber).to.be.greaterThan(0);1030 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule1031 scheduledId,1032 expectedBlockNumber, 1033 repetitions <= 1 ? null : [period, repetitions], 1034 0, 1035 {value: operationTx as any},1036 );10371038 //const events = 1039 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1040 //expect(getGenericResult(events).success).to.be.false;1041 });1042}10431044export async function1045scheduleTransferAndWaitExpectSuccess(1046 collectionId: number,1047 tokenId: number,1048 sender: IKeyringPair,1049 recipient: IKeyringPair,1050 value: number | bigint = 1,1051 blockSchedule: number,1052 scheduledId: string,1053) {1054 await usingApi(async (api: ApiPromise) => {1055 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10561057 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10581059 // sleep for n + 1 blocks1060 await waitNewBlocks(blockSchedule + 1);10611062 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10631064 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1065 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1066 });1067}10681069export async function1070scheduleTransferExpectSuccess(1071 collectionId: number,1072 tokenId: number,1073 sender: IKeyringPair,1074 recipient: IKeyringPair,1075 value: number | bigint = 1,1076 blockSchedule: number,1077 scheduledId: string,1078) {1079 await usingApi(async (api: ApiPromise) => {1080 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10811082 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10831084 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1085 });1086}10871088export async function1089scheduleTransferFundsPeriodicExpectSuccess(1090 amount: bigint,1091 sender: IKeyringPair,1092 recipient: IKeyringPair,1093 blockSchedule: number,1094 scheduledId: string,1095 period: number,1096 repetitions: number,1097) {1098 await usingApi(async (api: ApiPromise) => {1099 const transferTx = api.tx.balances.transfer(recipient.address, amount);11001101 const balanceBefore = await getFreeBalance(recipient);1102 1103 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);11041105 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1106 });1107}11081109export async function1110transfer(1111 api: ApiPromise,1112 collectionId: number,1113 tokenId: number,1114 sender: IKeyringPair,1115 recipient: IKeyringPair | CrossAccountId,1116 value: number | bigint,1117) : Promise<boolean> {1118 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1119 const events = await executeTransaction(api, sender, transferTx);1120 return getGenericResult(events).success;1121}11221123export async function1124transferExpectSuccess(1125 collectionId: number,1126 tokenId: number,1127 sender: IKeyringPair,1128 recipient: IKeyringPair | CrossAccountId,1129 value: number | bigint = 1,1130 type = 'NFT',1131) {1132 await usingApi(async (api: ApiPromise) => {1133 const from = normalizeAccountId(sender);1134 const to = normalizeAccountId(recipient);11351136 let balanceBefore = 0n;1137 if (type === 'Fungible' || type === 'ReFungible') {1138 balanceBefore = await getBalance(api, collectionId, to, tokenId);1139 }11401141 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1142 const events = await executeTransaction(api, sender, transferTx);1143 const result = getTransferResult(api, events);11441145 expect(result.collectionId).to.be.equal(collectionId);1146 expect(result.itemId).to.be.equal(tokenId);1147 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1148 expect(result.recipient).to.be.deep.equal(to);1149 expect(result.value).to.be.equal(BigInt(value));11501151 if (type === 'NFT') {1152 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1153 }1154 if (type === 'Fungible' || type === 'ReFungible') {1155 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1156 if (JSON.stringify(to) !== JSON.stringify(from)) {1157 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1158 } else {1159 expect(balanceAfter).to.be.equal(balanceBefore);1160 }1161 }1162 });1163}11641165export async function1166transferExpectFailure(1167 collectionId: number,1168 tokenId: number,1169 sender: IKeyringPair,1170 recipient: IKeyringPair | CrossAccountId,1171 value: number | bigint = 1,1172) {1173 await usingApi(async (api: ApiPromise) => {1174 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1175 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1176 const result = getGenericResult(events);1177 // if (events && Array.isArray(events)) {1178 // const result = getCreateCollectionResult(events);1179 // tslint:disable-next-line:no-unused-expression1180 expect(result.success).to.be.false;1181 //}1182 });1183}11841185export async function1186approveExpectFail(1187 collectionId: number,1188 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1189) {1190 await usingApi(async (api: ApiPromise) => {1191 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1192 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1193 const result = getCreateCollectionResult(events);1194 // tslint:disable-next-line:no-unused-expression1195 expect(result.success).to.be.false;1196 });1197}11981199export async function getBalance(1200 api: ApiPromise,1201 collectionId: number,1202 owner: string | CrossAccountId | IKeyringPair,1203 token: number,1204): Promise<bigint> {1205 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1206}1207export async function getTokenOwner(1208 api: ApiPromise,1209 collectionId: number,1210 token: number,1211): Promise<CrossAccountId> {1212 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1213 if (owner == null) throw new Error('owner == null');1214 return normalizeAccountId(owner);1215}1216export async function getTopmostTokenOwner(1217 api: ApiPromise,1218 collectionId: number,1219 token: number,1220): Promise<CrossAccountId> {1221 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1222 if (owner == null) throw new Error('owner == null');1223 return normalizeAccountId(owner);1224}1225export async function getTokenChildren(1226 api: ApiPromise,1227 collectionId: number,1228 tokenId: number,1229): Promise<UpDataStructsTokenChild[]> {1230 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1231}1232export async function isTokenExists(1233 api: ApiPromise,1234 collectionId: number,1235 token: number,1236): Promise<boolean> {1237 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1238}1239export async function getLastTokenId(1240 api: ApiPromise,1241 collectionId: number,1242): Promise<number> {1243 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1244}1245export async function getAdminList(1246 api: ApiPromise,1247 collectionId: number,1248): Promise<string[]> {1249 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1250}1251export async function getTokenProperties(1252 api: ApiPromise,1253 collectionId: number,1254 tokenId: number,1255 propertyKeys: string[],1256): Promise<UpDataStructsProperty[]> {1257 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1258}12591260export async function createFungibleItemExpectSuccess(1261 sender: IKeyringPair,1262 collectionId: number,1263 data: CreateFungibleData,1264 owner: CrossAccountId | string = sender.address,1265) {1266 return await usingApi(async (api) => {1267 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12681269 const events = await submitTransactionAsync(sender, tx);1270 const result = getCreateItemResult(events);12711272 expect(result.success).to.be.true;1273 return result.itemId;1274 });1275}12761277export async function createMultipleItemsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1278 await usingApi(async (api) => {1279 const to = normalizeAccountId(owner);1280 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12811282 const events = await submitTransactionAsync(sender, tx);1283 expect(getGenericResult(events).success).to.be.true;1284 });1285}12861287export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1288 await usingApi(async (api) => {1289 const to = normalizeAccountId(owner);1290 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12911292 const events = await submitTransactionAsync(sender, tx);1293 const result = getCreateItemsResult(events);12941295 for (const res of result) {1296 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1297 }1298 });1299}13001301export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1302 await usingApi(async (api) => {1303 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);13041305 const events = await submitTransactionAsync(sender, tx);1306 const result = getCreateItemsResult(events);13071308 for (const res of result) {1309 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1310 }1311 });1312}13131314export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1315 let newItemId = 0;1316 await usingApi(async (api) => {1317 const to = normalizeAccountId(owner);1318 const itemCountBefore = await getLastTokenId(api, collectionId);1319 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13201321 let tx;1322 if (createMode === 'Fungible') {1323 const createData = {fungible: {value: 10}};1324 tx = api.tx.unique.createItem(collectionId, to, createData as any);1325 } else if (createMode === 'ReFungible') {1326 const createData = {refungible: {pieces: 100}};1327 tx = api.tx.unique.createItem(collectionId, to, createData as any);1328 } else {1329 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1330 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1331 }13321333 const events = await submitTransactionAsync(sender, tx);1334 const result = getCreateItemResult(events);13351336 const itemCountAfter = await getLastTokenId(api, collectionId);1337 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13381339 if (createMode === 'NFT') {1340 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1341 }13421343 // What to expect1344 // tslint:disable-next-line:no-unused-expression1345 expect(result.success).to.be.true;1346 if (createMode === 'Fungible') {1347 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1348 } else {1349 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1350 }1351 expect(collectionId).to.be.equal(result.collectionId);1352 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1353 expect(to).to.be.deep.equal(result.recipient);1354 newItemId = result.itemId;1355 });1356 return newItemId;1357}13581359export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1360 await usingApi(async (api) => {13611362 let tx;1363 if (createMode === 'NFT') {1364 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1365 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1366 } else {1367 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1368 }136913701371 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1372 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1373 const result = getCreateItemResult(events);13741375 expect(result.success).to.be.false;1376 });1377}13781379export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1380 let newItemId = 0;1381 await usingApi(async (api) => {1382 const to = normalizeAccountId(owner);1383 const itemCountBefore = await getLastTokenId(api, collectionId);1384 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13851386 let tx;1387 if (createMode === 'Fungible') {1388 const createData = {fungible: {value: 10}};1389 tx = api.tx.unique.createItem(collectionId, to, createData as any);1390 } else if (createMode === 'ReFungible') {1391 const createData = {refungible: {pieces: 100}};1392 tx = api.tx.unique.createItem(collectionId, to, createData as any);1393 } else {1394 const createData = {nft: {}};1395 tx = api.tx.unique.createItem(collectionId, to, createData as any);1396 }13971398 const events = await submitTransactionAsync(sender, tx);1399 const result = getCreateItemResult(events);14001401 const itemCountAfter = await getLastTokenId(api, collectionId);1402 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);14031404 // What to expect1405 // tslint:disable-next-line:no-unused-expression1406 expect(result.success).to.be.true;1407 if (createMode === 'Fungible') {1408 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1409 } else {1410 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1411 }1412 expect(collectionId).to.be.equal(result.collectionId);1413 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1414 expect(to).to.be.deep.equal(result.recipient);1415 newItemId = result.itemId;1416 });1417 return newItemId;1418}14191420export async function createRefungibleToken(api: ApiPromise, sender: IKeyringPair, collectionId: number, amount: bigint, owner: CrossAccountId | IKeyringPair | string = sender.address) : Promise<CreateItemResult> {1421 const createData = {refungible: {pieces: amount}};1422 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createData as any);14231424 const events = await submitTransactionAsync(sender, tx);1425 return getCreateItemResult(events);1426}14271428export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1429 await usingApi(async (api) => {1430 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);14311432 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1433 const result = getCreateItemResult(events);14341435 expect(result.success).to.be.false;1436 });1437}14381439export async function setPublicAccessModeExpectSuccess(1440 sender: IKeyringPair, collectionId: number,1441 accessMode: 'Normal' | 'AllowList',1442) {1443 await usingApi(async (api) => {14441445 // Run the transaction1446 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1447 const events = await submitTransactionAsync(sender, tx);1448 const result = getGenericResult(events);14491450 // Get the collection1451 const collection = await queryCollectionExpectSuccess(api, collectionId);14521453 // What to expect1454 // tslint:disable-next-line:no-unused-expression1455 expect(result.success).to.be.true;1456 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1457 });1458}14591460export async function setPublicAccessModeExpectFail(1461 sender: IKeyringPair, collectionId: number,1462 accessMode: 'Normal' | 'AllowList',1463) {1464 await usingApi(async (api) => {14651466 // Run the transaction1467 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1468 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1469 const result = getGenericResult(events);14701471 // What to expect1472 // tslint:disable-next-line:no-unused-expression1473 expect(result.success).to.be.false;1474 });1475}14761477export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1478 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1479}14801481export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1482 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1483}14841485export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1486 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1487}14881489export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1490 await usingApi(async (api) => {14911492 // Run the transaction1493 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1494 const events = await submitTransactionAsync(sender, tx);1495 const result = getGenericResult(events);1496 expect(result.success).to.be.true;14971498 // Get the collection1499 const collection = await queryCollectionExpectSuccess(api, collectionId);15001501 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1502 });1503}15041505export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1506 await setMintPermissionExpectSuccess(sender, collectionId, true);1507}15081509export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1510 await usingApi(async (api) => {1511 // Run the transaction1512 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1513 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1514 const result = getCreateCollectionResult(events);1515 // tslint:disable-next-line:no-unused-expression1516 expect(result.success).to.be.false;1517 });1518}15191520export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1521 await usingApi(async (api) => {1522 // Run the transaction1523 const tx = api.tx.unique.setChainLimits(limits);1524 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1525 const result = getCreateCollectionResult(events);1526 // tslint:disable-next-line:no-unused-expression1527 expect(result.success).to.be.false;1528 });1529}15301531export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1532 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1533}15341535export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1536 await usingApi(async (api) => {1537 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;15381539 // Run the transaction1540 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1541 const events = await submitTransactionAsync(sender, tx);1542 const result = getGenericResult(events);1543 expect(result.success).to.be.true;15441545 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1546 });1547}15481549export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1550 await usingApi(async (api) => {15511552 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;15531554 // Run the transaction1555 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1556 const events = await submitTransactionAsync(sender, tx);1557 const result = getGenericResult(events);1558 expect(result.success).to.be.true;15591560 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1561 });1562}15631564export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1565 await usingApi(async (api) => {15661567 // Run the transaction1568 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1569 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1570 const result = getGenericResult(events);15711572 // What to expect1573 // tslint:disable-next-line:no-unused-expression1574 expect(result.success).to.be.false;1575 });1576}15771578export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1579 await usingApi(async (api) => {1580 // Run the transaction1581 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1582 const events = await submitTransactionAsync(sender, tx);1583 const result = getGenericResult(events);15841585 // What to expect1586 // tslint:disable-next-line:no-unused-expression1587 expect(result.success).to.be.true;1588 });1589}15901591export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1592 await usingApi(async (api) => {1593 // Run the transaction1594 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1595 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1596 const result = getGenericResult(events);15971598 // What to expect1599 // tslint:disable-next-line:no-unused-expression1600 expect(result.success).to.be.false;1601 });1602}16031604export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1605 : Promise<UpDataStructsRpcCollection | null> => {1606 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1607};16081609export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1610 // set global object - collectionsCount1611 return (await api.rpc.unique.collectionStats()).created.toNumber();1612};16131614export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1615 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1616}16171618export async function waitNewBlocks(blocksCount = 1): Promise<void> {1619 await usingApi(async (api) => {1620 const promise = new Promise<void>(async (resolve) => {1621 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1622 if (blocksCount > 0) {1623 blocksCount--;1624 } else {1625 unsubscribe();1626 resolve();1627 }1628 });1629 });1630 return promise;1631 });1632}