difftreelog
test(rmrk-proxy) sample externality test
in: master
3 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -37,6 +37,7 @@
"testStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/**.test.ts",
"testProperties": "mocha --timeout 9999999 -r ts-node/register ./**/properties.test.ts",
"testMigrationStructure": "mocha --timeout 9999999 -r ts-node/register ./**/nesting/migration-check.test.ts",
+ "testRmrk": "mocha --timeout 9999999 -r ts-node/register ./**/rmrk/**.test.ts",
"testAddCollectionAdmin": "mocha --timeout 9999999 -r ts-node/register ./**/addCollectionAdmin.test.ts",
"testSetSchemaVersion": "mocha --timeout 9999999 -r ts-node/register ./**/setSchemaVersion.test.ts",
"testSetCollectionLimits": "mocha --timeout 9999999 -r ts-node/register ./**/setCollectionLimits.test.ts",
tests/src/rmrk/rmrk.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/rmrk/rmrk.test.ts
@@ -0,0 +1,64 @@
+import {expect} from 'chai';
+import privateKey from '../substrate/privateKey';
+import usingApi, {executeTransaction} from '../substrate/substrate-api';
+import {
+ getCreateCollectionResult,
+ getDetailedCollectionInfo,
+ getGenericResult,
+} from '../util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
+
+let alice: IKeyringPair;
+let bob: IKeyringPair;
+
+describe('RMRK External Integration Test', () => {
+ before(async () => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ it('Creates a new RMRK collection that is tagged as external', async () => {
+ await usingApi(async api => {
+ const tx = api.tx.rmrkCore.createCollection('no-limit-metadata', null, 'no-limit-symbol');
+ const events = await executeTransaction(api, alice, tx);
+ const result = getCreateCollectionResult(events);
+
+ const collection = (await getDetailedCollectionInfo(api, result.collectionId))!;
+ expect(collection.readOnly.toHuman()).to.be.true;
+ });
+ });
+
+ it('[Negative] Forbids NFT operations with an external collection', async () => {
+ await usingApi(async api => {
+ const tx1 = api.tx.rmrkCore.createCollection('metadata', null, 'symbol');
+ const events1 = await executeTransaction(api, alice, tx1);
+
+ const resultUnique1 = getCreateCollectionResult(events1);
+ const uniqueCollectionId = resultUnique1.collectionId;
+
+ const resultRmrk1 = getGenericResult(events1, 'rmrkCore', 'CollectionCreated', (data) => {
+ return parseInt(data[1].toString(), 10);
+ });
+ const rmrkCollectionId: number = resultRmrk1.data!;
+
+ const tx2 = api.tx.rmrkCore.mintNft(
+ alice.address,
+ rmrkCollectionId,
+ alice.address,
+ null,
+ 'nft-metadata',
+ true,
+ );
+ const events2 = await executeTransaction(api, alice, tx2);
+ const result2 = getGenericResult(events2, 'rmrkCore', 'NftMinted', (data) => {
+ return parseInt(data[2].toString(), 10);
+ });
+ const rmrkNftId: number = result2.data!;
+
+ const tx3 = api.tx.unique.burnItem(uniqueCollectionId, rmrkNftId, 1);
+ await expect(executeTransaction(api, alice, tx3)).to.be.rejectedWith(/common\.CollectionIsExternal/);
+ });
+ });
+});
\ No newline at end of file
tests/src/util/helpers.tsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';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 === 48 || 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;9091type GenericResult = {92 success: boolean,93};9495interface CreateCollectionResult {96 success: boolean;97 collectionId: number;98}99100interface CreateItemResult {101 success: boolean;102 collectionId: number;103 itemId: number;104 recipient?: CrossAccountId;105}106107interface TransferResult {108 collectionId: number;109 itemId: number;110 sender?: CrossAccountId;111 recipient?: CrossAccountId;112 value: bigint;113}114115interface IReFungibleOwner {116 fraction: BN;117 owner: number[];118}119120interface IGetMessage {121 checkMsgUnqMethod: string;122 checkMsgTrsMethod: string;123 checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127 value: number;128}129130export interface IChainLimits {131 collectionNumbersLimit: number;132 accountTokenOwnershipLimit: number;133 collectionsAdminsLimit: number;134 customDataLimit: number;135 nftSponsorTransferTimeout: number;136 fungibleSponsorTransferTimeout: number;137 refungibleSponsorTransferTimeout: number;138 //offchainSchemaLimit: number;139 //constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143 owner: IReFungibleOwner[];144}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147 let checkMsgUnqMethod = '';148 let checkMsgTrsMethod = '';149 let checkMsgSysMethod = '';150 events.forEach(({event: {method, section}}) => {151 if (section === 'common') {152 checkMsgUnqMethod = method;153 } else if (section === 'treasury') {154 checkMsgTrsMethod = method;155 } else if (section === 'system') {156 checkMsgSysMethod = method;157 } else { return null; }158 });159 const result: IGetMessage = {160 checkMsgUnqMethod,161 checkMsgTrsMethod,162 checkMsgSysMethod,163 };164 return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168 const event = events.find(r => check(r.event));169 if (!event) return;170 return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174 const result: GenericResult = {175 success: false,176 };177 events.forEach(({event: {method}}) => {178 // console.log(` ${phase}: ${section}.${method}:: ${data}`);179 if (method === 'ExtrinsicSuccess') {180 result.success = true;181 }182 });183 return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189 let success = false;190 let collectionId = 0;191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method == 'ExtrinsicSuccess') {194 success = true;195 } else if ((section == 'common') && (method == 'CollectionCreated')) {196 collectionId = parseInt(data[0].toString(), 10);197 }198 });199 const result: CreateCollectionResult = {200 success,201 collectionId,202 };203 return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207 let success = false;208 let collectionId = 0;209 let itemId = 0;210 let recipient;211212 const results : CreateItemResult[] = [];213214 events.forEach(({event: {data, method, section}}) => {215 // console.log(` ${phase}: ${section}.${method}:: ${data}`);216 if (method == 'ExtrinsicSuccess') {217 success = true;218 } else if ((section == 'common') && (method == 'ItemCreated')) {219 collectionId = parseInt(data[0].toString(), 10);220 itemId = parseInt(data[1].toString(), 10);221 recipient = normalizeAccountId(data[2].toJSON() as any);222223 const itemRes: CreateItemResult = {224 success,225 collectionId,226 itemId,227 recipient,228 };229230 results.push(itemRes);231 }232 });233234 return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238 let success = false;239 let collectionId = 0;240 let itemId = 0;241 let recipient;242 events.forEach(({event: {data, method, section}}) => {243 // console.log(` ${phase}: ${section}.${method}:: ${data}`);244 if (method == 'ExtrinsicSuccess') {245 success = true;246 } else if ((section == 'common') && (method == 'ItemCreated')) {247 collectionId = parseInt(data[0].toString(), 10);248 itemId = parseInt(data[1].toString(), 10);249 recipient = normalizeAccountId(data[2].toJSON() as any);250 }251 });252 const result: CreateItemResult = {253 success,254 collectionId,255 itemId,256 recipient,257 };258 return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262 for (const {event} of events) {263 if (api.events.common.Transfer.is(event)) {264 const [collection, token, sender, recipient, value] = event.data;265 return {266 collectionId: collection.toNumber(),267 itemId: token.toNumber(),268 sender: normalizeAccountId(sender.toJSON() as any),269 recipient: normalizeAccountId(recipient.toJSON() as any),270 value: value.toBigInt(),271 };272 }273 }274 throw new Error('no transfer event');275}276277interface Nft {278 type: 'NFT';279}280281interface Fungible {282 type: 'Fungible';283 decimalPoints: number;284}285286interface ReFungible {287 type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293 key: any,294 value: any,295};296297type Permission = {298 mutable: boolean;299 collectionAdmin: boolean;300 tokenOwner: boolean;301}302303type PropertyPermission = {304 key: any;305 permission: Permission;306}307308export type CreateCollectionParams = {309 mode: CollectionMode,310 name: string,311 description: string,312 tokenPrefix: string,313 properties?: Array<Property>,314 propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318 description: 'description',319 mode: {type: 'NFT'},320 name: 'name',321 tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api, privateKeyWrapper) => {329 // Get number of collections before the transaction330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 // Run the CreateCollection transaction333 const alicePrivateKey = privateKeyWrapper('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 });350 const events = await submitTransactionAsync(alicePrivateKey, tx);351 const result = getCreateCollectionResult(events);352353 // Get number of collections after the transaction354 const collectionCountAfter = await getCreatedCollectionCount(api);355356 // Get the collection357 const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359 // What to expect360 // tslint:disable-next-line:no-unused-expression361 expect(result.success).to.be.true;362 expect(result.collectionId).to.be.equal(collectionCountAfter);363 // tslint:disable-next-line:no-unused-expression364 expect(collection).to.be.not.null;365 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371 collectionId = result.collectionId;372 });373374 return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380 let collectionId = 0;381 await usingApi(async (api, privateKeyWrapper) => {382 // Get number of collections before the transaction383 const collectionCountBefore = await getCreatedCollectionCount(api);384385 // Run the CreateCollection transaction386 const alicePrivateKey = privateKeyWrapper('//Alice');387388 let modeprm = {};389 if (mode.type === 'NFT') {390 modeprm = {nft: null};391 } else if (mode.type === 'Fungible') {392 modeprm = {fungible: mode.decimalPoints};393 } else if (mode.type === 'ReFungible') {394 modeprm = {refungible: null};395 }396397 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});398 const events = await submitTransactionAsync(alicePrivateKey, tx);399 const result = getCreateCollectionResult(events);400401 // Get number of collections after the transaction402 const collectionCountAfter = await getCreatedCollectionCount(api);403404 // Get the collection405 const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407 // What to expect408 // tslint:disable-next-line:no-unused-expression409 expect(result.success).to.be.true;410 expect(result.collectionId).to.be.equal(collectionCountAfter);411 // tslint:disable-next-line:no-unused-expression412 expect(collection).to.be.not.null;413 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420 collectionId = result.collectionId;421 });422423 return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429 await usingApi(async (api, privateKeyWrapper) => {430 // Get number of collections before the transaction431 const collectionCountBefore = await getCreatedCollectionCount(api);432433 // Run the CreateCollection transaction434 const alicePrivateKey = privateKeyWrapper('//Alice');435436 let modeprm = {};437 if (mode.type === 'NFT') {438 modeprm = {nft: null};439 } else if (mode.type === 'Fungible') {440 modeprm = {fungible: mode.decimalPoints};441 } else if (mode.type === 'ReFungible') {442 modeprm = {refungible: null};443 }444445 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});446 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449 // Get number of collections after the transaction450 const collectionCountAfter = await getCreatedCollectionCount(api);451452 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453 });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459 let modeprm = {};460 if (mode.type === 'NFT') {461 modeprm = {nft: null};462 } else if (mode.type === 'Fungible') {463 modeprm = {fungible: mode.decimalPoints};464 } else if (mode.type === 'ReFungible') {465 modeprm = {refungible: null};466 }467468 await usingApi(async (api, privateKeyWrapper) => {469 // Get number of collections before the transaction470 const collectionCountBefore = await getCreatedCollectionCount(api);471472 // Run the CreateCollection transaction473 const alicePrivateKey = privateKeyWrapper('//Alice');474 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477 // Get number of collections after the transaction478 const collectionCountAfter = await getCreatedCollectionCount(api);479480 // What to expect481 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482 });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486 let bal = 0n;487 let unused;488 do {489 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490 const keyring = new Keyring({type: 'sr25519'});491 unused = keyring.addFromUri(`//${randomSeed}`);492 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493 } while (bal !== 0n);494 return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506 const totalNumber = await getCreatedCollectionCount(api);507 const newCollection: number = totalNumber + 1;508 return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512 let success = false;513 events.forEach(({event: {method}}) => {514 if (method == 'ExtrinsicSuccess') {515 success = true;516 }517 });518 return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522 await usingApi(async (api, privateKeyWrapper) => {523 // Run the DestroyCollection transaction524 const alicePrivateKey = privateKeyWrapper(senderSeed);525 const tx = api.tx.unique.destroyCollection(collectionId);526 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527 });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531 await usingApi(async (api, privateKeyWrapper) => {532 // Run the DestroyCollection transaction533 const alicePrivateKey = privateKeyWrapper(senderSeed);534 const tx = api.tx.unique.destroyCollection(collectionId);535 const events = await submitTransactionAsync(alicePrivateKey, tx);536 const result = getDestroyResult(events);537 expect(result).to.be.true;538539 // What to expect540 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541 });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545 await usingApi(async (api) => {546 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547 const events = await submitTransactionAsync(sender, tx);548 const result = getGenericResult(events);549550 expect(result.success).to.be.true;551 });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555 await usingApi(async(api) => {556 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557 const events = await submitTransactionAsync(sender, tx);558 const result = getGenericResult(events);559560 expect(result.success).to.be.true;561 });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565 await usingApi(async (api) => {566 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568 const result = getGenericResult(events);569570 expect(result.success).to.be.false;571 });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575 await usingApi(async (api, privateKeyWrapper) => {576577 // Run the transaction578 const senderPrivateKey = privateKeyWrapper(sender);579 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580 const events = await submitTransactionAsync(senderPrivateKey, tx);581 const result = getGenericResult(events);582583 // Get the collection584 const collection = await queryCollectionExpectSuccess(api, collectionId);585586 // What to expect587 expect(result.success).to.be.true;588 expect(collection.sponsorship.toJSON()).to.deep.equal({589 unconfirmed: sponsor,590 });591 });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595 await usingApi(async (api, privateKeyWrapper) => {596597 // Run the transaction598 const alicePrivateKey = privateKeyWrapper(sender);599 const tx = api.tx.unique.removeCollectionSponsor(collectionId);600 const events = await submitTransactionAsync(alicePrivateKey, tx);601 const result = getGenericResult(events);602603 // Get the collection604 const collection = await queryCollectionExpectSuccess(api, collectionId);605606 // What to expect607 expect(result.success).to.be.true;608 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609 });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613 await usingApi(async (api, privateKeyWrapper) => {614615 // Run the transaction616 const alicePrivateKey = privateKeyWrapper(senderSeed);617 const tx = api.tx.unique.removeCollectionSponsor(collectionId);618 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619 });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623 await usingApi(async (api, privateKeyWrapper) => {624625 // Run the transaction626 const alicePrivateKey = privateKeyWrapper(senderSeed);627 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629 });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633 await usingApi(async (api, privateKeyWrapper) => {634635 // Run the transaction636 const sender = privateKeyWrapper(senderSeed);637 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);638 });639}640641export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {642 await usingApi(async (api, privateKeyWrapper) => {643644 // Run the transaction645 const tx = api.tx.unique.confirmSponsorship(collectionId);646 const events = await submitTransactionAsync(sender, tx);647 const result = getGenericResult(events);648649 // Get the collection650 const collection = await queryCollectionExpectSuccess(api, collectionId);651652 // What to expect653 expect(result.success).to.be.true;654 expect(collection.sponsorship.toJSON()).to.be.deep.equal({655 confirmed: sender.address,656 });657 });658}659660661export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {662 await usingApi(async (api, privateKeyWrapper) => {663664 // Run the transaction665 const sender = privateKeyWrapper(senderSeed);666 const tx = api.tx.unique.confirmSponsorship(collectionId);667 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668 });669}670671export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {672 await usingApi(async (api) => {673 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);674 const events = await submitTransactionAsync(sender, tx);675 const result = getGenericResult(events);676677 expect(result.success).to.be.true;678 });679}680681export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {682 await usingApi(async (api) => {683 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);684 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;685 const result = getGenericResult(events);686687 expect(result.success).to.be.false;688 });689}690691export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {692693 await usingApi(async (api) => {694695 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);696 const events = await submitTransactionAsync(sender, tx);697 const result = getGenericResult(events);698699 expect(result.success).to.be.true;700 });701}702703export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {704705 await usingApi(async (api) => {706707 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);708 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;709 const result = getGenericResult(events);710711 expect(result.success).to.be.false;712 });713}714715export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {716 await usingApi(async (api) => {717 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);718 const events = await submitTransactionAsync(sender, tx);719 const result = getGenericResult(events);720721 expect(result.success).to.be.true;722 });723}724725export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {726 await usingApi(async (api) => {727 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);728 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;729 const result = getGenericResult(events);730731 expect(result.success).to.be.false;732 });733}734735export async function getNextSponsored(736 api: ApiPromise,737 collectionId: number,738 account: string | CrossAccountId,739 tokenId: number,740): Promise<number> {741 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));742}743744export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {745 await usingApi(async (api) => {746 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);747 const events = await submitTransactionAsync(sender, tx);748 const result = getGenericResult(events);749750 expect(result.success).to.be.true;751 });752}753754export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {755 let allowlisted = false;756 await usingApi(async (api) => {757 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;758 });759 return allowlisted;760}761762export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {763 await usingApi(async (api) => {764 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());765 const events = await submitTransactionAsync(sender, tx);766 const result = getGenericResult(events);767768 expect(result.success).to.be.true;769 });770}771772export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {773 await usingApi(async (api) => {774 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());775 const events = await submitTransactionAsync(sender, tx);776 const result = getGenericResult(events);777778 expect(result.success).to.be.true;779 });780}781782export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {783 await usingApi(async (api) => {784 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());785 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;786 const result = getGenericResult(events);787788 expect(result.success).to.be.false;789 });790}791792export interface CreateFungibleData {793 readonly Value: bigint;794}795796export interface CreateReFungibleData { }797export interface CreateNftData { }798799export type CreateItemData = {800 NFT: CreateNftData;801} | {802 Fungible: CreateFungibleData;803} | {804 ReFungible: CreateReFungibleData;805};806807export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {808 await usingApi(async (api) => {809 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);810 // if burning token by admin - use adminButnItemExpectSuccess811 expect(balanceBefore >= BigInt(value)).to.be.true;812813 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);814 const events = await submitTransactionAsync(sender, tx);815 const result = getGenericResult(events);816 expect(result.success).to.be.true;817818 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);819 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);820 });821}822823export async function824approveExpectSuccess(825 collectionId: number,826 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,827) {828 await usingApi(async (api: ApiPromise) => {829 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);830 const events = await submitTransactionAsync(owner, approveUniqueTx);831 const result = getGenericResult(events);832 expect(result.success).to.be.true;833834 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));835 });836}837838export async function adminApproveFromExpectSuccess(839 collectionId: number,840 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,841) {842 await usingApi(async (api: ApiPromise) => {843 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);844 const events = await submitTransactionAsync(admin, approveUniqueTx);845 const result = getGenericResult(events);846 expect(result.success).to.be.true;847848 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));849 });850}851852export async function853transferFromExpectSuccess(854 collectionId: number,855 tokenId: number,856 accountApproved: IKeyringPair,857 accountFrom: IKeyringPair | CrossAccountId,858 accountTo: IKeyringPair | CrossAccountId,859 value: number | bigint = 1,860 type = 'NFT',861) {862 await usingApi(async (api: ApiPromise) => {863 const from = normalizeAccountId(accountFrom);864 const to = normalizeAccountId(accountTo);865 let balanceBefore = 0n;866 if (type === 'Fungible' || type === 'ReFungible') {867 balanceBefore = await getBalance(api, collectionId, to, tokenId);868 }869 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);870 const events = await submitTransactionAsync(accountApproved, transferFromTx);871 const result = getCreateItemResult(events);872 // tslint:disable-next-line:no-unused-expression873 expect(result.success).to.be.true;874 if (type === 'NFT') {875 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);876 }877 if (type === 'Fungible') {878 const balanceAfter = await getBalance(api, collectionId, to, tokenId);879 if (JSON.stringify(to) !== JSON.stringify(from)) {880 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));881 } else {882 expect(balanceAfter).to.be.equal(balanceBefore);883 }884 }885 if (type === 'ReFungible') {886 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));887 }888 });889}890891export async function892transferFromExpectFail(893 collectionId: number,894 tokenId: number,895 accountApproved: IKeyringPair,896 accountFrom: IKeyringPair,897 accountTo: IKeyringPair,898 value: number | bigint = 1,899) {900 await usingApi(async (api: ApiPromise) => {901 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);902 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;903 const result = getCreateCollectionResult(events);904 // tslint:disable-next-line:no-unused-expression905 expect(result.success).to.be.false;906 });907}908909/* eslint no-async-promise-executor: "off" */910export async function getBlockNumber(api: ApiPromise): Promise<number> {911 return new Promise<number>(async (resolve) => {912 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {913 unsubscribe();914 resolve(head.number.toNumber());915 });916 });917}918919export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {920 await usingApi(async (api) => {921 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));922 const events = await submitTransactionAsync(sender, changeAdminTx);923 const result = getCreateCollectionResult(events);924 expect(result.success).to.be.true;925 });926}927928export async function929getFreeBalance(account: IKeyringPair): Promise<bigint> {930 let balance = 0n;931 await usingApi(async (api) => {932 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());933 });934935 return balance;936}937938export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {939 const tx = api.tx.balances.transfer(target, amount);940 const events = await submitTransactionAsync(source, tx);941 const result = getGenericResult(events);942 expect(result.success).to.be.true;943}944945export async function946scheduleExpectSuccess(947 operationTx: any,948 sender: IKeyringPair,949 blockSchedule: number,950 scheduledId: string,951 period = 1,952 repetitions = 1,953) {954 await usingApi(async (api: ApiPromise) => {955 const blockNumber: number | undefined = await getBlockNumber(api);956 const expectedBlockNumber = blockNumber + blockSchedule;957958 expect(blockNumber).to.be.greaterThan(0);959 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule960 scheduledId,961 expectedBlockNumber, 962 repetitions > 1 ? [period, repetitions] : null, 963 0, 964 {value: operationTx as any},965 );966967 const events = await submitTransactionAsync(sender, scheduleTx);968 expect(getGenericResult(events).success).to.be.true;969 });970}971972export async function973scheduleExpectFailure(974 operationTx: any,975 sender: IKeyringPair,976 blockSchedule: number,977 scheduledId: string,978 period = 1,979 repetitions = 1,980) {981 await usingApi(async (api: ApiPromise) => {982 const blockNumber: number | undefined = await getBlockNumber(api);983 const expectedBlockNumber = blockNumber + blockSchedule;984985 expect(blockNumber).to.be.greaterThan(0);986 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule987 scheduledId,988 expectedBlockNumber, 989 repetitions <= 1 ? null : [period, repetitions], 990 0, 991 {value: operationTx as any},992 );993994 //const events = 995 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;996 //expect(getGenericResult(events).success).to.be.false;997 });998}9991000export async function1001scheduleTransferAndWaitExpectSuccess(1002 collectionId: number,1003 tokenId: number,1004 sender: IKeyringPair,1005 recipient: IKeyringPair,1006 value: number | bigint = 1,1007 blockSchedule: number,1008 scheduledId: string,1009) {1010 await usingApi(async (api: ApiPromise) => {1011 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10121013 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10141015 // sleep for n + 1 blocks1016 await waitNewBlocks(blockSchedule + 1);10171018 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10191020 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1021 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1022 });1023}10241025export async function1026scheduleTransferExpectSuccess(1027 collectionId: number,1028 tokenId: number,1029 sender: IKeyringPair,1030 recipient: IKeyringPair,1031 value: number | bigint = 1,1032 blockSchedule: number,1033 scheduledId: string,1034) {1035 await usingApi(async (api: ApiPromise) => {1036 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10371038 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10391040 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1041 });1042}10431044export async function1045scheduleTransferFundsPeriodicExpectSuccess(1046 amount: bigint,1047 sender: IKeyringPair,1048 recipient: IKeyringPair,1049 blockSchedule: number,1050 scheduledId: string,1051 period: number,1052 repetitions: number,1053) {1054 await usingApi(async (api: ApiPromise) => {1055 const transferTx = api.tx.balances.transfer(recipient.address, amount);10561057 const balanceBefore = await getFreeBalance(recipient);1058 1059 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10601061 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1062 });1063}10641065export async function1066transferExpectSuccess(1067 collectionId: number,1068 tokenId: number,1069 sender: IKeyringPair,1070 recipient: IKeyringPair | CrossAccountId,1071 value: number | bigint = 1,1072 type = 'NFT',1073) {1074 await usingApi(async (api: ApiPromise) => {1075 const from = normalizeAccountId(sender);1076 const to = normalizeAccountId(recipient);10771078 let balanceBefore = 0n;1079 if (type === 'Fungible') {1080 balanceBefore = await getBalance(api, collectionId, to, tokenId);1081 }1082 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1083 const events = await executeTransaction(api, sender, transferTx);10841085 const result = getTransferResult(api, events);1086 expect(result.collectionId).to.be.equal(collectionId);1087 expect(result.itemId).to.be.equal(tokenId);1088 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1089 expect(result.recipient).to.be.deep.equal(to);1090 expect(result.value).to.be.equal(BigInt(value));10911092 if (type === 'NFT') {1093 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1094 }1095 if (type === 'Fungible') {1096 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1097 if (JSON.stringify(to) !== JSON.stringify(from)) {1098 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1099 } else {1100 expect(balanceAfter).to.be.equal(balanceBefore);1101 }1102 }1103 if (type === 'ReFungible') {1104 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1105 }1106 });1107}11081109export async function1110transferExpectFailure(1111 collectionId: number,1112 tokenId: number,1113 sender: IKeyringPair,1114 recipient: IKeyringPair | CrossAccountId,1115 value: number | bigint = 1,1116) {1117 await usingApi(async (api: ApiPromise) => {1118 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1119 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1120 const result = getGenericResult(events);1121 // if (events && Array.isArray(events)) {1122 // const result = getCreateCollectionResult(events);1123 // tslint:disable-next-line:no-unused-expression1124 expect(result.success).to.be.false;1125 //}1126 });1127}11281129export async function1130approveExpectFail(1131 collectionId: number,1132 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1133) {1134 await usingApi(async (api: ApiPromise) => {1135 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1136 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1137 const result = getCreateCollectionResult(events);1138 // tslint:disable-next-line:no-unused-expression1139 expect(result.success).to.be.false;1140 });1141}11421143export async function getBalance(1144 api: ApiPromise,1145 collectionId: number,1146 owner: string | CrossAccountId,1147 token: number,1148): Promise<bigint> {1149 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1150}1151export async function getTokenOwner(1152 api: ApiPromise,1153 collectionId: number,1154 token: number,1155): Promise<CrossAccountId> {1156 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1157 if (owner == null) throw new Error('owner == null');1158 return normalizeAccountId(owner);1159}1160export async function getTopmostTokenOwner(1161 api: ApiPromise,1162 collectionId: number,1163 token: number,1164): Promise<CrossAccountId> {1165 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1166 if (owner == null) throw new Error('owner == null');1167 return normalizeAccountId(owner);1168}1169export async function getTokenChildren(1170 api: ApiPromise,1171 collectionId: number,1172 tokenId: number,1173): Promise<UpDataStructsTokenChild[]> {1174 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1175}1176export async function isTokenExists(1177 api: ApiPromise,1178 collectionId: number,1179 token: number,1180): Promise<boolean> {1181 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1182}1183export async function getLastTokenId(1184 api: ApiPromise,1185 collectionId: number,1186): Promise<number> {1187 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1188}1189export async function getAdminList(1190 api: ApiPromise,1191 collectionId: number,1192): Promise<string[]> {1193 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1194}1195export async function getTokenProperties(1196 api: ApiPromise,1197 collectionId: number,1198 tokenId: number,1199 propertyKeys: string[],1200): Promise<UpDataStructsProperty[]> {1201 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1202}12031204export async function createFungibleItemExpectSuccess(1205 sender: IKeyringPair,1206 collectionId: number,1207 data: CreateFungibleData,1208 owner: CrossAccountId | string = sender.address,1209) {1210 return await usingApi(async (api) => {1211 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12121213 const events = await submitTransactionAsync(sender, tx);1214 const result = getCreateItemResult(events);12151216 expect(result.success).to.be.true;1217 return result.itemId;1218 });1219}12201221export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1222 await usingApi(async (api) => {1223 const to = normalizeAccountId(owner);1224 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12251226 const events = await submitTransactionAsync(sender, tx);1227 const result = getCreateItemsResult(events);12281229 for (const res of result) {1230 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1231 }1232 });1233}12341235export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1236 await usingApi(async (api) => {1237 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12381239 const events = await submitTransactionAsync(sender, tx);1240 const result = getCreateItemsResult(events);12411242 for (const res of result) {1243 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1244 }1245 });1246}12471248export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1249 let newItemId = 0;1250 await usingApi(async (api) => {1251 const to = normalizeAccountId(owner);1252 const itemCountBefore = await getLastTokenId(api, collectionId);1253 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12541255 let tx;1256 if (createMode === 'Fungible') {1257 const createData = {fungible: {value: 10}};1258 tx = api.tx.unique.createItem(collectionId, to, createData as any);1259 } else if (createMode === 'ReFungible') {1260 const createData = {refungible: {pieces: 100}};1261 tx = api.tx.unique.createItem(collectionId, to, createData as any);1262 } else {1263 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1264 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1265 }12661267 const events = await submitTransactionAsync(sender, tx);1268 const result = getCreateItemResult(events);12691270 const itemCountAfter = await getLastTokenId(api, collectionId);1271 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12721273 if (createMode === 'NFT') {1274 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1275 }12761277 // What to expect1278 // tslint:disable-next-line:no-unused-expression1279 expect(result.success).to.be.true;1280 if (createMode === 'Fungible') {1281 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1282 } else {1283 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1284 }1285 expect(collectionId).to.be.equal(result.collectionId);1286 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1287 expect(to).to.be.deep.equal(result.recipient);1288 newItemId = result.itemId;1289 });1290 return newItemId;1291}12921293export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1294 await usingApi(async (api) => {12951296 let tx;1297 if (createMode === 'NFT') {1298 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1299 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1300 } else {1301 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1302 }130313041305 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1306 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1307 const result = getCreateItemResult(events);13081309 expect(result.success).to.be.false;1310 });1311}13121313export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1314 let newItemId = 0;1315 await usingApi(async (api) => {1316 const to = normalizeAccountId(owner);1317 const itemCountBefore = await getLastTokenId(api, collectionId);1318 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13191320 let tx;1321 if (createMode === 'Fungible') {1322 const createData = {fungible: {value: 10}};1323 tx = api.tx.unique.createItem(collectionId, to, createData as any);1324 } else if (createMode === 'ReFungible') {1325 const createData = {refungible: {pieces: 100}};1326 tx = api.tx.unique.createItem(collectionId, to, createData as any);1327 } else {1328 const createData = {nft: {}};1329 tx = api.tx.unique.createItem(collectionId, to, createData as any);1330 }13311332 const events = await submitTransactionAsync(sender, tx);1333 const result = getCreateItemResult(events);13341335 const itemCountAfter = await getLastTokenId(api, collectionId);1336 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13371338 // What to expect1339 // tslint:disable-next-line:no-unused-expression1340 expect(result.success).to.be.true;1341 if (createMode === 'Fungible') {1342 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1343 } else {1344 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1345 }1346 expect(collectionId).to.be.equal(result.collectionId);1347 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1348 expect(to).to.be.deep.equal(result.recipient);1349 newItemId = result.itemId;1350 });1351 return newItemId;1352}13531354export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1355 await usingApi(async (api) => {1356 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13571358 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1359 const result = getCreateItemResult(events);13601361 expect(result.success).to.be.false;1362 });1363}13641365export async function setPublicAccessModeExpectSuccess(1366 sender: IKeyringPair, collectionId: number,1367 accessMode: 'Normal' | 'AllowList',1368) {1369 await usingApi(async (api) => {13701371 // Run the transaction1372 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1373 const events = await submitTransactionAsync(sender, tx);1374 const result = getGenericResult(events);13751376 // Get the collection1377 const collection = await queryCollectionExpectSuccess(api, collectionId);13781379 // What to expect1380 // tslint:disable-next-line:no-unused-expression1381 expect(result.success).to.be.true;1382 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1383 });1384}13851386export async function setPublicAccessModeExpectFail(1387 sender: IKeyringPair, collectionId: number,1388 accessMode: 'Normal' | 'AllowList',1389) {1390 await usingApi(async (api) => {13911392 // Run the transaction1393 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1394 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395 const result = getGenericResult(events);13961397 // What to expect1398 // tslint:disable-next-line:no-unused-expression1399 expect(result.success).to.be.false;1400 });1401}14021403export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1404 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1405}14061407export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1408 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1409}14101411export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1412 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1413}14141415export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1416 await usingApi(async (api) => {14171418 // Run the transaction1419 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1420 const events = await submitTransactionAsync(sender, tx);1421 const result = getGenericResult(events);1422 expect(result.success).to.be.true;14231424 // Get the collection1425 const collection = await queryCollectionExpectSuccess(api, collectionId);14261427 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1428 });1429}14301431export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1432 await setMintPermissionExpectSuccess(sender, collectionId, true);1433}14341435export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1436 await usingApi(async (api) => {1437 // Run the transaction1438 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1439 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1440 const result = getCreateCollectionResult(events);1441 // tslint:disable-next-line:no-unused-expression1442 expect(result.success).to.be.false;1443 });1444}14451446export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1447 await usingApi(async (api) => {1448 // Run the transaction1449 const tx = api.tx.unique.setChainLimits(limits);1450 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1451 const result = getCreateCollectionResult(events);1452 // tslint:disable-next-line:no-unused-expression1453 expect(result.success).to.be.false;1454 });1455}14561457export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1458 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1459}14601461export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1462 await usingApi(async (api) => {1463 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14641465 // Run the transaction1466 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1467 const events = await submitTransactionAsync(sender, tx);1468 const result = getGenericResult(events);1469 expect(result.success).to.be.true;14701471 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1472 });1473}14741475export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1476 await usingApi(async (api) => {14771478 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14791480 // Run the transaction1481 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1482 const events = await submitTransactionAsync(sender, tx);1483 const result = getGenericResult(events);1484 expect(result.success).to.be.true;14851486 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1487 });1488}14891490export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1491 await usingApi(async (api) => {14921493 // Run the transaction1494 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1495 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1496 const result = getGenericResult(events);14971498 // What to expect1499 // tslint:disable-next-line:no-unused-expression1500 expect(result.success).to.be.false;1501 });1502}15031504export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1505 await usingApi(async (api) => {1506 // Run the transaction1507 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1508 const events = await submitTransactionAsync(sender, tx);1509 const result = getGenericResult(events);15101511 // What to expect1512 // tslint:disable-next-line:no-unused-expression1513 expect(result.success).to.be.true;1514 });1515}15161517export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1518 await usingApi(async (api) => {1519 // Run the transaction1520 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1521 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1522 const result = getGenericResult(events);15231524 // What to expect1525 // tslint:disable-next-line:no-unused-expression1526 expect(result.success).to.be.false;1527 });1528}15291530export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1531 : Promise<UpDataStructsRpcCollection | null> => {1532 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1533};15341535export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1536 // set global object - collectionsCount1537 return (await api.rpc.unique.collectionStats()).created.toNumber();1538};15391540export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1541 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1542}15431544export async function waitNewBlocks(blocksCount = 1): Promise<void> {1545 await usingApi(async (api) => {1546 const promise = new Promise<void>(async (resolve) => {1547 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1548 if (blocksCount > 0) {1549 blocksCount--;1550 } else {1551 unsubscribe();1552 resolve();1553 }1554 });1555 });1556 return promise;1557 });1558}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import type {GenericEventData} from '@polkadot/types';22import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';23import {evmToAddress} from '@polkadot/util-crypto';24import BN from 'bn.js';25import chai from 'chai';26import chaiAsPromised from 'chai-as-promised';27import {alicesPublicKey} from '../accounts';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';31import {UpDataStructsTokenChild} from '../interfaces';3233chai.use(chaiAsPromised);34const expect = chai.expect;3536export type CrossAccountId = {37 Substrate: string,38} | {39 Ethereum: string,40};4142export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {43 if (typeof input === 'string') {44 if (input.length === 48 || input.length === 47) {45 return {Substrate: input};46 } else if (input.length === 42 && input.startsWith('0x')) {47 return {Ethereum: input.toLowerCase()};48 } else if (input.length === 40 && !input.startsWith('0x')) {49 return {Ethereum: '0x' + input.toLowerCase()};50 } else {51 throw new Error(`Unknown address format: "${input}"`);52 }53 }54 if ('address' in input) {55 return {Substrate: input.address};56 }57 if ('Ethereum' in input) {58 return {59 Ethereum: input.Ethereum.toLowerCase(),60 };61 } else if ('ethereum' in input) {62 return {63 Ethereum: (input as any).ethereum.toLowerCase(),64 };65 } else if ('Substrate' in input) {66 return input;67 } else if ('substrate' in input) {68 return {69 Substrate: (input as any).substrate,70 };71 }7273 // AccountId74 return {Substrate: input.toString()};75}76export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {77 input = normalizeAccountId(input);78 if ('Substrate' in input) {79 return input.Substrate;80 } else {81 return evmToAddress(input.Ethereum);82 }83}8485export const U128_MAX = (1n << 128n) - 1n;8687const MICROUNIQUE = 1_000_000_000_000n;88const MILLIUNIQUE = 1_000n * MICROUNIQUE;89const CENTIUNIQUE = 10n * MILLIUNIQUE;90export const UNIQUE = 100n * CENTIUNIQUE;9192interface GenericResult<T> {93 success: boolean;94 data: T | null;95}9697interface CreateCollectionResult {98 success: boolean;99 collectionId: number;100}101102interface CreateItemResult {103 success: boolean;104 collectionId: number;105 itemId: number;106 recipient?: CrossAccountId;107}108109interface TransferResult {110 collectionId: number;111 itemId: number;112 sender?: CrossAccountId;113 recipient?: CrossAccountId;114 value: bigint;115}116117interface IReFungibleOwner {118 fraction: BN;119 owner: number[];120}121122interface IGetMessage {123 checkMsgUnqMethod: string;124 checkMsgTrsMethod: string;125 checkMsgSysMethod: string;126}127128export interface IFungibleTokenDataType {129 value: number;130}131132export interface IChainLimits {133 collectionNumbersLimit: number;134 accountTokenOwnershipLimit: number;135 collectionsAdminsLimit: number;136 customDataLimit: number;137 nftSponsorTransferTimeout: number;138 fungibleSponsorTransferTimeout: number;139 refungibleSponsorTransferTimeout: number;140 //offchainSchemaLimit: number;141 //constOnChainSchemaLimit: number;142}143144export interface IReFungibleTokenDataType {145 owner: IReFungibleOwner[];146}147148export function uniqueEventMessage(events: EventRecord[]): IGetMessage {149 let checkMsgUnqMethod = '';150 let checkMsgTrsMethod = '';151 let checkMsgSysMethod = '';152 events.forEach(({event: {method, section}}) => {153 if (section === 'common') {154 checkMsgUnqMethod = method;155 } else if (section === 'treasury') {156 checkMsgTrsMethod = method;157 } else if (section === 'system') {158 checkMsgSysMethod = method;159 } else { return null; }160 });161 const result: IGetMessage = {162 checkMsgUnqMethod,163 checkMsgTrsMethod,164 checkMsgSysMethod,165 };166 return result;167}168169export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {170 const event = events.find(r => check(r.event));171 if (!event) return;172 return event.event as T;173}174175export function getGenericResult<T>(176 events: EventRecord[],177 expectSection?: string,178 expectMethod?: string,179 extractAction?: (data: GenericEventData) => T,180): GenericResult<T> {181 let success = false;182 let successData = null;183 events.forEach(({event: {data, method, section}}) => {184 if (method === 'ExtrinsicSuccess') {185 success = true;186 } else if ((expectSection == section) && (expectMethod == method)) {187 successData = extractAction!(data);188 }189 });190 const result: GenericResult<T> = {191 success,192 data: successData,193 };194 return result;195}196197export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {198 let success = false;199 let collectionId = 0;200 events.forEach(({event: {data, method, section}}) => {201 // console.log(` ${phase}: ${section}.${method}:: ${data}`);202 if (method == 'ExtrinsicSuccess') {203 success = true;204 } else if ((section == 'common') && (method == 'CollectionCreated')) {205 collectionId = parseInt(data[0].toString(), 10);206 }207 });208 const result: CreateCollectionResult = {209 success,210 collectionId,211 };212 return result;213}214215export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {216 let success = false;217 let collectionId = 0;218 let itemId = 0;219 let recipient;220221 const results : CreateItemResult[] = [];222223 events.forEach(({event: {data, method, section}}) => {224 // console.log(` ${phase}: ${section}.${method}:: ${data}`);225 if (method == 'ExtrinsicSuccess') {226 success = true;227 } else if ((section == 'common') && (method == 'ItemCreated')) {228 collectionId = parseInt(data[0].toString(), 10);229 itemId = parseInt(data[1].toString(), 10);230 recipient = normalizeAccountId(data[2].toJSON() as any);231232 const itemRes: CreateItemResult = {233 success,234 collectionId,235 itemId,236 recipient,237 };238239 results.push(itemRes);240 }241 });242243 return results;244}245246export function getCreateItemResult(events: EventRecord[]): CreateItemResult {247 let success = false;248 let collectionId = 0;249 let itemId = 0;250 let recipient;251 events.forEach(({event: {data, method, section}}) => {252 // console.log(` ${phase}: ${section}.${method}:: ${data}`);253 if (method == 'ExtrinsicSuccess') {254 success = true;255 } else if ((section == 'common') && (method == 'ItemCreated')) {256 collectionId = parseInt(data[0].toString(), 10);257 itemId = parseInt(data[1].toString(), 10);258 recipient = normalizeAccountId(data[2].toJSON() as any);259 }260 });261 const result: CreateItemResult = {262 success,263 collectionId,264 itemId,265 recipient,266 };267 return result;268}269270export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {271 for (const {event} of events) {272 if (api.events.common.Transfer.is(event)) {273 const [collection, token, sender, recipient, value] = event.data;274 return {275 collectionId: collection.toNumber(),276 itemId: token.toNumber(),277 sender: normalizeAccountId(sender.toJSON() as any),278 recipient: normalizeAccountId(recipient.toJSON() as any),279 value: value.toBigInt(),280 };281 }282 }283 throw new Error('no transfer event');284}285286interface Nft {287 type: 'NFT';288}289290interface Fungible {291 type: 'Fungible';292 decimalPoints: number;293}294295interface ReFungible {296 type: 'ReFungible';297}298299type CollectionMode = Nft | Fungible | ReFungible;300301export type Property = {302 key: any,303 value: any,304};305306type Permission = {307 mutable: boolean;308 collectionAdmin: boolean;309 tokenOwner: boolean;310}311312type PropertyPermission = {313 key: any;314 permission: Permission;315}316317export type CreateCollectionParams = {318 mode: CollectionMode,319 name: string,320 description: string,321 tokenPrefix: string,322 properties?: Array<Property>,323 propPerm?: Array<PropertyPermission>324};325326const defaultCreateCollectionParams: CreateCollectionParams = {327 description: 'description',328 mode: {type: 'NFT'},329 name: 'name',330 tokenPrefix: 'prefix',331};332333export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {334 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};335336 let collectionId = 0;337 await usingApi(async (api, privateKeyWrapper) => {338 // Get number of collections before the transaction339 const collectionCountBefore = await getCreatedCollectionCount(api);340341 // Run the CreateCollection transaction342 const alicePrivateKey = privateKeyWrapper('//Alice');343344 let modeprm = {};345 if (mode.type === 'NFT') {346 modeprm = {nft: null};347 } else if (mode.type === 'Fungible') {348 modeprm = {fungible: mode.decimalPoints};349 } else if (mode.type === 'ReFungible') {350 modeprm = {refungible: null};351 }352353 const tx = api.tx.unique.createCollectionEx({354 name: strToUTF16(name),355 description: strToUTF16(description),356 tokenPrefix: strToUTF16(tokenPrefix),357 mode: modeprm as any,358 });359 const events = await submitTransactionAsync(alicePrivateKey, tx);360 const result = getCreateCollectionResult(events);361362 // Get number of collections after the transaction363 const collectionCountAfter = await getCreatedCollectionCount(api);364365 // Get the collection366 const collection = await queryCollectionExpectSuccess(api, result.collectionId);367368 // What to expect369 // tslint:disable-next-line:no-unused-expression370 expect(result.success).to.be.true;371 expect(result.collectionId).to.be.equal(collectionCountAfter);372 // tslint:disable-next-line:no-unused-expression373 expect(collection).to.be.not.null;374 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');375 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));376 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);377 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);378 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);379380 collectionId = result.collectionId;381 });382383 return collectionId;384}385386export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {387 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};388389 let collectionId = 0;390 await usingApi(async (api, privateKeyWrapper) => {391 // Get number of collections before the transaction392 const collectionCountBefore = await getCreatedCollectionCount(api);393394 // Run the CreateCollection transaction395 const alicePrivateKey = privateKeyWrapper('//Alice');396397 let modeprm = {};398 if (mode.type === 'NFT') {399 modeprm = {nft: null};400 } else if (mode.type === 'Fungible') {401 modeprm = {fungible: mode.decimalPoints};402 } else if (mode.type === 'ReFungible') {403 modeprm = {refungible: null};404 }405406 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});407 const events = await submitTransactionAsync(alicePrivateKey, tx);408 const result = getCreateCollectionResult(events);409410 // Get number of collections after the transaction411 const collectionCountAfter = await getCreatedCollectionCount(api);412413 // Get the collection414 const collection = await queryCollectionExpectSuccess(api, result.collectionId);415416 // What to expect417 // tslint:disable-next-line:no-unused-expression418 expect(result.success).to.be.true;419 expect(result.collectionId).to.be.equal(collectionCountAfter);420 // tslint:disable-next-line:no-unused-expression421 expect(collection).to.be.not.null;422 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');423 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));424 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);425 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);426 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);427428429 collectionId = result.collectionId;430 });431432 return collectionId;433}434435export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {436 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};437438 await usingApi(async (api, privateKeyWrapper) => {439 // Get number of collections before the transaction440 const collectionCountBefore = await getCreatedCollectionCount(api);441442 // Run the CreateCollection transaction443 const alicePrivateKey = privateKeyWrapper('//Alice');444445 let modeprm = {};446 if (mode.type === 'NFT') {447 modeprm = {nft: null};448 } else if (mode.type === 'Fungible') {449 modeprm = {fungible: mode.decimalPoints};450 } else if (mode.type === 'ReFungible') {451 modeprm = {refungible: null};452 }453454 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});455 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;456457458 // Get number of collections after the transaction459 const collectionCountAfter = await getCreatedCollectionCount(api);460461 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');462 });463}464465export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {466 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};467468 let modeprm = {};469 if (mode.type === 'NFT') {470 modeprm = {nft: null};471 } else if (mode.type === 'Fungible') {472 modeprm = {fungible: mode.decimalPoints};473 } else if (mode.type === 'ReFungible') {474 modeprm = {refungible: null};475 }476477 await usingApi(async (api, privateKeyWrapper) => {478 // Get number of collections before the transaction479 const collectionCountBefore = await getCreatedCollectionCount(api);480481 // Run the CreateCollection transaction482 const alicePrivateKey = privateKeyWrapper('//Alice');483 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});484 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;485486 // Get number of collections after the transaction487 const collectionCountAfter = await getCreatedCollectionCount(api);488489 // What to expect490 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');491 });492}493494export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {495 let bal = 0n;496 let unused;497 do {498 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;499 const keyring = new Keyring({type: 'sr25519'});500 unused = keyring.addFromUri(`//${randomSeed}`);501 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();502 } while (bal !== 0n);503 return unused;504}505506export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {507 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();508}509510export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {511 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));512}513514export async function findNotExistingCollection(api: ApiPromise): Promise<number> {515 const totalNumber = await getCreatedCollectionCount(api);516 const newCollection: number = totalNumber + 1;517 return newCollection;518}519520function getDestroyResult(events: EventRecord[]): boolean {521 let success = false;522 events.forEach(({event: {method}}) => {523 if (method == 'ExtrinsicSuccess') {524 success = true;525 }526 });527 return success;528}529530export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {531 await usingApi(async (api, privateKeyWrapper) => {532 // Run the DestroyCollection transaction533 const alicePrivateKey = privateKeyWrapper(senderSeed);534 const tx = api.tx.unique.destroyCollection(collectionId);535 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;536 });537}538539export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {540 await usingApi(async (api, privateKeyWrapper) => {541 // Run the DestroyCollection transaction542 const alicePrivateKey = privateKeyWrapper(senderSeed);543 const tx = api.tx.unique.destroyCollection(collectionId);544 const events = await submitTransactionAsync(alicePrivateKey, tx);545 const result = getDestroyResult(events);546 expect(result).to.be.true;547548 // What to expect549 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;550 });551}552553export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {554 await usingApi(async (api) => {555 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);556 const events = await submitTransactionAsync(sender, tx);557 const result = getGenericResult(events);558559 expect(result.success).to.be.true;560 });561}562563export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {564 await usingApi(async(api) => {565 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);566 const events = await submitTransactionAsync(sender, tx);567 const result = getGenericResult(events);568569 expect(result.success).to.be.true;570 });571};572573export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {574 await usingApi(async (api) => {575 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);576 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;577 const result = getGenericResult(events);578579 expect(result.success).to.be.false;580 });581}582583export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {584 await usingApi(async (api, privateKeyWrapper) => {585586 // Run the transaction587 const senderPrivateKey = privateKeyWrapper(sender);588 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);589 const events = await submitTransactionAsync(senderPrivateKey, tx);590 const result = getGenericResult(events);591592 // Get the collection593 const collection = await queryCollectionExpectSuccess(api, collectionId);594595 // What to expect596 expect(result.success).to.be.true;597 expect(collection.sponsorship.toJSON()).to.deep.equal({598 unconfirmed: sponsor,599 });600 });601}602603export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {604 await usingApi(async (api, privateKeyWrapper) => {605606 // Run the transaction607 const alicePrivateKey = privateKeyWrapper(sender);608 const tx = api.tx.unique.removeCollectionSponsor(collectionId);609 const events = await submitTransactionAsync(alicePrivateKey, tx);610 const result = getGenericResult(events);611612 // Get the collection613 const collection = await queryCollectionExpectSuccess(api, collectionId);614615 // What to expect616 expect(result.success).to.be.true;617 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});618 });619}620621export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {622 await usingApi(async (api, privateKeyWrapper) => {623624 // Run the transaction625 const alicePrivateKey = privateKeyWrapper(senderSeed);626 const tx = api.tx.unique.removeCollectionSponsor(collectionId);627 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;628 });629}630631export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {632 await usingApi(async (api, privateKeyWrapper) => {633634 // Run the transaction635 const alicePrivateKey = privateKeyWrapper(senderSeed);636 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);637 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;638 });639}640641export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {642 await usingApi(async (api, privateKeyWrapper) => {643644 // Run the transaction645 const sender = privateKeyWrapper(senderSeed);646 await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);647 });648}649650export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {651 await usingApi(async (api, privateKeyWrapper) => {652653 // Run the transaction654 const tx = api.tx.unique.confirmSponsorship(collectionId);655 const events = await submitTransactionAsync(sender, tx);656 const result = getGenericResult(events);657658 // Get the collection659 const collection = await queryCollectionExpectSuccess(api, collectionId);660661 // What to expect662 expect(result.success).to.be.true;663 expect(collection.sponsorship.toJSON()).to.be.deep.equal({664 confirmed: sender.address,665 });666 });667}668669670export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {671 await usingApi(async (api, privateKeyWrapper) => {672673 // Run the transaction674 const sender = privateKeyWrapper(senderSeed);675 const tx = api.tx.unique.confirmSponsorship(collectionId);676 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 });678}679680export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {681 await usingApi(async (api) => {682 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);683 const events = await submitTransactionAsync(sender, tx);684 const result = getGenericResult(events);685686 expect(result.success).to.be.true;687 });688}689690export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {691 await usingApi(async (api) => {692 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);693 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;694 const result = getGenericResult(events);695696 expect(result.success).to.be.false;697 });698}699700export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {701702 await usingApi(async (api) => {703704 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);705 const events = await submitTransactionAsync(sender, tx);706 const result = getGenericResult(events);707708 expect(result.success).to.be.true;709 });710}711712export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {713714 await usingApi(async (api) => {715716 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);717 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;718 const result = getGenericResult(events);719720 expect(result.success).to.be.false;721 });722}723724export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {725 await usingApi(async (api) => {726 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);727 const events = await submitTransactionAsync(sender, tx);728 const result = getGenericResult(events);729730 expect(result.success).to.be.true;731 });732}733734export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {735 await usingApi(async (api) => {736 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);737 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;738 const result = getGenericResult(events);739740 expect(result.success).to.be.false;741 });742}743744export async function getNextSponsored(745 api: ApiPromise,746 collectionId: number,747 account: string | CrossAccountId,748 tokenId: number,749): Promise<number> {750 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));751}752753export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {754 await usingApi(async (api) => {755 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);756 const events = await submitTransactionAsync(sender, tx);757 const result = getGenericResult(events);758759 expect(result.success).to.be.true;760 });761}762763export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {764 let allowlisted = false;765 await usingApi(async (api) => {766 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;767 });768 return allowlisted;769}770771export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {772 await usingApi(async (api) => {773 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());774 const events = await submitTransactionAsync(sender, tx);775 const result = getGenericResult(events);776777 expect(result.success).to.be.true;778 });779}780781export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {782 await usingApi(async (api) => {783 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());784 const events = await submitTransactionAsync(sender, tx);785 const result = getGenericResult(events);786787 expect(result.success).to.be.true;788 });789}790791export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {792 await usingApi(async (api) => {793 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());794 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;795 const result = getGenericResult(events);796797 expect(result.success).to.be.false;798 });799}800801export interface CreateFungibleData {802 readonly Value: bigint;803}804805export interface CreateReFungibleData { }806export interface CreateNftData { }807808export type CreateItemData = {809 NFT: CreateNftData;810} | {811 Fungible: CreateFungibleData;812} | {813 ReFungible: CreateReFungibleData;814};815816export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {817 await usingApi(async (api) => {818 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);819 // if burning token by admin - use adminButnItemExpectSuccess820 expect(balanceBefore >= BigInt(value)).to.be.true;821822 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);823 const events = await submitTransactionAsync(sender, tx);824 const result = getGenericResult(events);825 expect(result.success).to.be.true;826827 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);828 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);829 });830}831832export async function833approveExpectSuccess(834 collectionId: number,835 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,836) {837 await usingApi(async (api: ApiPromise) => {838 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);839 const events = await submitTransactionAsync(owner, approveUniqueTx);840 const result = getGenericResult(events);841 expect(result.success).to.be.true;842843 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));844 });845}846847export async function adminApproveFromExpectSuccess(848 collectionId: number,849 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,850) {851 await usingApi(async (api: ApiPromise) => {852 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);853 const events = await submitTransactionAsync(admin, approveUniqueTx);854 const result = getGenericResult(events);855 expect(result.success).to.be.true;856857 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));858 });859}860861export async function862transferFromExpectSuccess(863 collectionId: number,864 tokenId: number,865 accountApproved: IKeyringPair,866 accountFrom: IKeyringPair | CrossAccountId,867 accountTo: IKeyringPair | CrossAccountId,868 value: number | bigint = 1,869 type = 'NFT',870) {871 await usingApi(async (api: ApiPromise) => {872 const from = normalizeAccountId(accountFrom);873 const to = normalizeAccountId(accountTo);874 let balanceBefore = 0n;875 if (type === 'Fungible' || type === 'ReFungible') {876 balanceBefore = await getBalance(api, collectionId, to, tokenId);877 }878 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);879 const events = await submitTransactionAsync(accountApproved, transferFromTx);880 const result = getCreateItemResult(events);881 // tslint:disable-next-line:no-unused-expression882 expect(result.success).to.be.true;883 if (type === 'NFT') {884 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);885 }886 if (type === 'Fungible') {887 const balanceAfter = await getBalance(api, collectionId, to, tokenId);888 if (JSON.stringify(to) !== JSON.stringify(from)) {889 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890 } else {891 expect(balanceAfter).to.be.equal(balanceBefore);892 }893 }894 if (type === 'ReFungible') {895 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));896 }897 });898}899900export async function901transferFromExpectFail(902 collectionId: number,903 tokenId: number,904 accountApproved: IKeyringPair,905 accountFrom: IKeyringPair,906 accountTo: IKeyringPair,907 value: number | bigint = 1,908) {909 await usingApi(async (api: ApiPromise) => {910 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);911 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;912 const result = getCreateCollectionResult(events);913 // tslint:disable-next-line:no-unused-expression914 expect(result.success).to.be.false;915 });916}917918/* eslint no-async-promise-executor: "off" */919export async function getBlockNumber(api: ApiPromise): Promise<number> {920 return new Promise<number>(async (resolve) => {921 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {922 unsubscribe();923 resolve(head.number.toNumber());924 });925 });926}927928export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {929 await usingApi(async (api) => {930 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));931 const events = await submitTransactionAsync(sender, changeAdminTx);932 const result = getCreateCollectionResult(events);933 expect(result.success).to.be.true;934 });935}936937export async function938getFreeBalance(account: IKeyringPair): Promise<bigint> {939 let balance = 0n;940 await usingApi(async (api) => {941 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());942 });943944 return balance;945}946947export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {948 const tx = api.tx.balances.transfer(target, amount);949 const events = await submitTransactionAsync(source, tx);950 const result = getGenericResult(events);951 expect(result.success).to.be.true;952}953954export async function955scheduleExpectSuccess(956 operationTx: any,957 sender: IKeyringPair,958 blockSchedule: number,959 scheduledId: string,960 period = 1,961 repetitions = 1,962) {963 await usingApi(async (api: ApiPromise) => {964 const blockNumber: number | undefined = await getBlockNumber(api);965 const expectedBlockNumber = blockNumber + blockSchedule;966967 expect(blockNumber).to.be.greaterThan(0);968 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule969 scheduledId,970 expectedBlockNumber, 971 repetitions > 1 ? [period, repetitions] : null, 972 0, 973 {value: operationTx as any},974 );975976 const events = await submitTransactionAsync(sender, scheduleTx);977 expect(getGenericResult(events).success).to.be.true;978 });979}980981export async function982scheduleExpectFailure(983 operationTx: any,984 sender: IKeyringPair,985 blockSchedule: number,986 scheduledId: string,987 period = 1,988 repetitions = 1,989) {990 await usingApi(async (api: ApiPromise) => {991 const blockNumber: number | undefined = await getBlockNumber(api);992 const expectedBlockNumber = blockNumber + blockSchedule;993994 expect(blockNumber).to.be.greaterThan(0);995 const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule996 scheduledId,997 expectedBlockNumber, 998 repetitions <= 1 ? null : [period, repetitions], 999 0, 1000 {value: operationTx as any},1001 );10021003 //const events = 1004 await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;1005 //expect(getGenericResult(events).success).to.be.false;1006 });1007}10081009export async function1010scheduleTransferAndWaitExpectSuccess(1011 collectionId: number,1012 tokenId: number,1013 sender: IKeyringPair,1014 recipient: IKeyringPair,1015 value: number | bigint = 1,1016 blockSchedule: number,1017 scheduledId: string,1018) {1019 await usingApi(async (api: ApiPromise) => {1020 await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);10211022 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();10231024 // sleep for n + 1 blocks1025 await waitNewBlocks(blockSchedule + 1);10261027 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();10281029 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));1030 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);1031 });1032}10331034export async function1035scheduleTransferExpectSuccess(1036 collectionId: number,1037 tokenId: number,1038 sender: IKeyringPair,1039 recipient: IKeyringPair,1040 value: number | bigint = 1,1041 blockSchedule: number,1042 scheduledId: string,1043) {1044 await usingApi(async (api: ApiPromise) => {1045 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);10461047 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);10481049 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));1050 });1051}10521053export async function1054scheduleTransferFundsPeriodicExpectSuccess(1055 amount: bigint,1056 sender: IKeyringPair,1057 recipient: IKeyringPair,1058 blockSchedule: number,1059 scheduledId: string,1060 period: number,1061 repetitions: number,1062) {1063 await usingApi(async (api: ApiPromise) => {1064 const transferTx = api.tx.balances.transfer(recipient.address, amount);10651066 const balanceBefore = await getFreeBalance(recipient);1067 1068 await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);10691070 expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);1071 });1072}10731074export async function1075transferExpectSuccess(1076 collectionId: number,1077 tokenId: number,1078 sender: IKeyringPair,1079 recipient: IKeyringPair | CrossAccountId,1080 value: number | bigint = 1,1081 type = 'NFT',1082) {1083 await usingApi(async (api: ApiPromise) => {1084 const from = normalizeAccountId(sender);1085 const to = normalizeAccountId(recipient);10861087 let balanceBefore = 0n;1088 if (type === 'Fungible') {1089 balanceBefore = await getBalance(api, collectionId, to, tokenId);1090 }1091 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1092 const events = await executeTransaction(api, sender, transferTx);10931094 const result = getTransferResult(api, events);1095 expect(result.collectionId).to.be.equal(collectionId);1096 expect(result.itemId).to.be.equal(tokenId);1097 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1098 expect(result.recipient).to.be.deep.equal(to);1099 expect(result.value).to.be.equal(BigInt(value));11001101 if (type === 'NFT') {1102 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1103 }1104 if (type === 'Fungible') {1105 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1106 if (JSON.stringify(to) !== JSON.stringify(from)) {1107 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1108 } else {1109 expect(balanceAfter).to.be.equal(balanceBefore);1110 }1111 }1112 if (type === 'ReFungible') {1113 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1114 }1115 });1116}11171118export async function1119transferExpectFailure(1120 collectionId: number,1121 tokenId: number,1122 sender: IKeyringPair,1123 recipient: IKeyringPair | CrossAccountId,1124 value: number | bigint = 1,1125) {1126 await usingApi(async (api: ApiPromise) => {1127 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1128 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1129 const result = getGenericResult(events);1130 // if (events && Array.isArray(events)) {1131 // const result = getCreateCollectionResult(events);1132 // tslint:disable-next-line:no-unused-expression1133 expect(result.success).to.be.false;1134 //}1135 });1136}11371138export async function1139approveExpectFail(1140 collectionId: number,1141 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1142) {1143 await usingApi(async (api: ApiPromise) => {1144 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1145 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1146 const result = getCreateCollectionResult(events);1147 // tslint:disable-next-line:no-unused-expression1148 expect(result.success).to.be.false;1149 });1150}11511152export async function getBalance(1153 api: ApiPromise,1154 collectionId: number,1155 owner: string | CrossAccountId,1156 token: number,1157): Promise<bigint> {1158 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1159}1160export async function getTokenOwner(1161 api: ApiPromise,1162 collectionId: number,1163 token: number,1164): Promise<CrossAccountId> {1165 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1166 if (owner == null) throw new Error('owner == null');1167 return normalizeAccountId(owner);1168}1169export async function getTopmostTokenOwner(1170 api: ApiPromise,1171 collectionId: number,1172 token: number,1173): Promise<CrossAccountId> {1174 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1175 if (owner == null) throw new Error('owner == null');1176 return normalizeAccountId(owner);1177}1178export async function getTokenChildren(1179 api: ApiPromise,1180 collectionId: number,1181 tokenId: number,1182): Promise<UpDataStructsTokenChild[]> {1183 return (await api.rpc.unique.tokenChildren(collectionId, tokenId)).toJSON() as any;1184}1185export async function isTokenExists(1186 api: ApiPromise,1187 collectionId: number,1188 token: number,1189): Promise<boolean> {1190 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1191}1192export async function getLastTokenId(1193 api: ApiPromise,1194 collectionId: number,1195): Promise<number> {1196 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1197}1198export async function getAdminList(1199 api: ApiPromise,1200 collectionId: number,1201): Promise<string[]> {1202 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1203}1204export async function getTokenProperties(1205 api: ApiPromise,1206 collectionId: number,1207 tokenId: number,1208 propertyKeys: string[],1209): Promise<UpDataStructsProperty[]> {1210 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1211}12121213export async function createFungibleItemExpectSuccess(1214 sender: IKeyringPair,1215 collectionId: number,1216 data: CreateFungibleData,1217 owner: CrossAccountId | string = sender.address,1218) {1219 return await usingApi(async (api) => {1220 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});12211222 const events = await submitTransactionAsync(sender, tx);1223 const result = getCreateItemResult(events);12241225 expect(result.success).to.be.true;1226 return result.itemId;1227 });1228}12291230export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1231 await usingApi(async (api) => {1232 const to = normalizeAccountId(owner);1233 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);12341235 const events = await submitTransactionAsync(sender, tx);1236 const result = getCreateItemsResult(events);12371238 for (const res of result) {1239 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1240 }1241 });1242}12431244export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1245 await usingApi(async (api) => {1246 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);12471248 const events = await submitTransactionAsync(sender, tx);1249 const result = getCreateItemsResult(events);12501251 for (const res of result) {1252 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1253 }1254 });1255}12561257export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1258 let newItemId = 0;1259 await usingApi(async (api) => {1260 const to = normalizeAccountId(owner);1261 const itemCountBefore = await getLastTokenId(api, collectionId);1262 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12631264 let tx;1265 if (createMode === 'Fungible') {1266 const createData = {fungible: {value: 10}};1267 tx = api.tx.unique.createItem(collectionId, to, createData as any);1268 } else if (createMode === 'ReFungible') {1269 const createData = {refungible: {pieces: 100}};1270 tx = api.tx.unique.createItem(collectionId, to, createData as any);1271 } else {1272 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1273 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1274 }12751276 const events = await submitTransactionAsync(sender, tx);1277 const result = getCreateItemResult(events);12781279 const itemCountAfter = await getLastTokenId(api, collectionId);1280 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12811282 if (createMode === 'NFT') {1283 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1284 }12851286 // What to expect1287 // tslint:disable-next-line:no-unused-expression1288 expect(result.success).to.be.true;1289 if (createMode === 'Fungible') {1290 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1291 } else {1292 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1293 }1294 expect(collectionId).to.be.equal(result.collectionId);1295 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1296 expect(to).to.be.deep.equal(result.recipient);1297 newItemId = result.itemId;1298 });1299 return newItemId;1300}13011302export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1303 await usingApi(async (api) => {13041305 let tx;1306 if (createMode === 'NFT') {1307 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1308 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1309 } else {1310 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1311 }131213131314 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1315 if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1316 const result = getCreateItemResult(events);13171318 expect(result.success).to.be.false;1319 });1320}13211322export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1323 let newItemId = 0;1324 await usingApi(async (api) => {1325 const to = normalizeAccountId(owner);1326 const itemCountBefore = await getLastTokenId(api, collectionId);1327 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);13281329 let tx;1330 if (createMode === 'Fungible') {1331 const createData = {fungible: {value: 10}};1332 tx = api.tx.unique.createItem(collectionId, to, createData as any);1333 } else if (createMode === 'ReFungible') {1334 const createData = {refungible: {pieces: 100}};1335 tx = api.tx.unique.createItem(collectionId, to, createData as any);1336 } else {1337 const createData = {nft: {}};1338 tx = api.tx.unique.createItem(collectionId, to, createData as any);1339 }13401341 const events = await submitTransactionAsync(sender, tx);1342 const result = getCreateItemResult(events);13431344 const itemCountAfter = await getLastTokenId(api, collectionId);1345 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);13461347 // What to expect1348 // tslint:disable-next-line:no-unused-expression1349 expect(result.success).to.be.true;1350 if (createMode === 'Fungible') {1351 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1352 } else {1353 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1354 }1355 expect(collectionId).to.be.equal(result.collectionId);1356 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1357 expect(to).to.be.deep.equal(result.recipient);1358 newItemId = result.itemId;1359 });1360 return newItemId;1361}13621363export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1364 await usingApi(async (api) => {1365 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);13661367 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1368 const result = getCreateItemResult(events);13691370 expect(result.success).to.be.false;1371 });1372}13731374export async function setPublicAccessModeExpectSuccess(1375 sender: IKeyringPair, collectionId: number,1376 accessMode: 'Normal' | 'AllowList',1377) {1378 await usingApi(async (api) => {13791380 // Run the transaction1381 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1382 const events = await submitTransactionAsync(sender, tx);1383 const result = getGenericResult(events);13841385 // Get the collection1386 const collection = await queryCollectionExpectSuccess(api, collectionId);13871388 // What to expect1389 // tslint:disable-next-line:no-unused-expression1390 expect(result.success).to.be.true;1391 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1392 });1393}13941395export async function setPublicAccessModeExpectFail(1396 sender: IKeyringPair, collectionId: number,1397 accessMode: 'Normal' | 'AllowList',1398) {1399 await usingApi(async (api) => {14001401 // Run the transaction1402 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1403 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1404 const result = getGenericResult(events);14051406 // What to expect1407 // tslint:disable-next-line:no-unused-expression1408 expect(result.success).to.be.false;1409 });1410}14111412export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1413 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1414}14151416export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1417 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1418}14191420export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1421 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1422}14231424export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1425 await usingApi(async (api) => {14261427 // Run the transaction1428 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1429 const events = await submitTransactionAsync(sender, tx);1430 const result = getGenericResult(events);1431 expect(result.success).to.be.true;14321433 // Get the collection1434 const collection = await queryCollectionExpectSuccess(api, collectionId);14351436 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1437 });1438}14391440export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1441 await setMintPermissionExpectSuccess(sender, collectionId, true);1442}14431444export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1445 await usingApi(async (api) => {1446 // Run the transaction1447 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1448 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1449 const result = getCreateCollectionResult(events);1450 // tslint:disable-next-line:no-unused-expression1451 expect(result.success).to.be.false;1452 });1453}14541455export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1456 await usingApi(async (api) => {1457 // Run the transaction1458 const tx = api.tx.unique.setChainLimits(limits);1459 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1460 const result = getCreateCollectionResult(events);1461 // tslint:disable-next-line:no-unused-expression1462 expect(result.success).to.be.false;1463 });1464}14651466export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1467 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1468}14691470export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1471 await usingApi(async (api) => {1472 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;14731474 // Run the transaction1475 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1476 const events = await submitTransactionAsync(sender, tx);1477 const result = getGenericResult(events);1478 expect(result.success).to.be.true;14791480 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1481 });1482}14831484export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1485 await usingApi(async (api) => {14861487 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14881489 // Run the transaction1490 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1491 const events = await submitTransactionAsync(sender, tx);1492 const result = getGenericResult(events);1493 expect(result.success).to.be.true;14941495 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1496 });1497}14981499export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1500 await usingApi(async (api) => {15011502 // Run the transaction1503 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1504 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1505 const result = getGenericResult(events);15061507 // What to expect1508 // tslint:disable-next-line:no-unused-expression1509 expect(result.success).to.be.false;1510 });1511}15121513export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1514 await usingApi(async (api) => {1515 // Run the transaction1516 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1517 const events = await submitTransactionAsync(sender, tx);1518 const result = getGenericResult(events);15191520 // What to expect1521 // tslint:disable-next-line:no-unused-expression1522 expect(result.success).to.be.true;1523 });1524}15251526export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1527 await usingApi(async (api) => {1528 // Run the transaction1529 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1530 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1531 const result = getGenericResult(events);15321533 // What to expect1534 // tslint:disable-next-line:no-unused-expression1535 expect(result.success).to.be.false;1536 });1537}15381539export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1540 : Promise<UpDataStructsRpcCollection | null> => {1541 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1542};15431544export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1545 // set global object - collectionsCount1546 return (await api.rpc.unique.collectionStats()).created.toNumber();1547};15481549export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1550 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1551}15521553export async function waitNewBlocks(blocksCount = 1): Promise<void> {1554 await usingApi(async (api) => {1555 const promise = new Promise<void>(async (resolve) => {1556 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1557 if (blocksCount > 0) {1558 blocksCount--;1559 } else {1560 unsubscribe();1561 resolve();1562 }1563 });1564 });1565 return promise;1566 });1567}