difftreelog
CreateItem* tests fixes
in: master
4 files changed
tests/src/createItem.test.tsdiffbeforeafterboth--- a/tests/src/createItem.test.ts
+++ b/tests/src/createItem.test.ts
@@ -23,13 +23,14 @@
createItemExpectSuccess,
addCollectionAdminExpectSuccess,
createCollectionWithPropsExpectSuccess,
+ createItemWithPropsExpectSuccess,
} from './util/helpers';
const expect = chai.expect;
let alice: IKeyringPair;
let bob: IKeyringPair;
-describe('integration test: ext. createItem():', () => {
+describe('integration test: ext. ():', () => {
before(async () => {
await usingApi(async () => {
const keyring = new Keyring({type: 'sr25519'});
@@ -75,28 +76,25 @@
it('Set property Admin', async () => {
const createMode = 'NFT';
const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
- properties: [{key: 'key1', value: 'val1'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: false}]});
+ propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
- await createItemExpectSuccess(alice, newCollectionID, createMode);
+ await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'k', value: 't2'}]);
});
it('Set property AdminConst', async () => {
const createMode = 'NFT';
const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
- properties: [{key: 'key1', value: 'val1'}],
- propPerm: [{key: 'key1', mutable: false, collectionAdmin: true, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]});
- await createItemExpectSuccess(alice, newCollectionID, createMode);
+ await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);
});
it('Set property itemOwnerOrAdmin', async () => {
const createMode = 'NFT';
- const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
- properties: [{key: 'key1', value: 'val1'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: true}]});
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
+ propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]});
- await createItemExpectSuccess(alice, newCollectionID, createMode);
+ await createItemWithPropsExpectSuccess(alice, newCollectionID, createMode, [{key: 'key1', value: 'val1'}]);
});
});
@@ -129,7 +127,7 @@
await usingApi(async api => {
const createMode = 'NFT';
const newCollectionID = await createCollectionWithPropsExpectSuccess({mode: {type: createMode},
- propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: false, collectionAdmin: false, tokenOwner: false}}]});
const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
await addCollectionAdminExpectSuccess(alice, newCollectionID, bob.address);
@@ -144,7 +142,7 @@
it('User doesnt have editing rights', async () => {
await usingApi(async api => {
- const newCollectionID = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ const newCollectionID = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});
const token = await createItemExpectSuccess(alice, newCollectionID, 'NFT');
await expect(executeTransaction(
tests/src/createMultipleItems.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItems.test.ts
+++ b/tests/src/createMultipleItems.test.ts
@@ -34,6 +34,7 @@
getCreatedCollectionCount,
createCollectionWithPropsExpectSuccess,
getCreateItemsResult,
+ createMultipleItemsWithPropsExpectSuccess
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -133,25 +134,18 @@
it('Create 0x31, 0x32, 0x33 items in active NFT with property Admin', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = await createCollectionExpectSuccess();
+ const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const args = [{Nft: {const_data: '0x31'}},
- {Nft: {const_data: '0x32'}},
- {Nft: {const_data: '0x33'}}];
- const createMultipleItemsTx = api.tx.unique
- .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
- await submitTransactionAsync(alice, createMultipleItemsTx);
+ const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
+ {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
+ {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+
+ await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
const itemsListIndexAfter = await getLastTokenId(api, collectionId);
expect(itemsListIndexAfter).to.be.equal(3);
-
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]),
- )).to.not.be.rejected;
expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
@@ -165,26 +159,20 @@
it('Create 0x31, 0x32, 0x33 items in active NFT with property AdminConst', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = await createCollectionExpectSuccess();
+ const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const args = [{Nft: {const_data: '0x31'}},
- {Nft: {const_data: '0x32'}},
- {Nft: {const_data: '0x33'}}];
- const createMultipleItemsTx = api.tx.unique
- .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
- await submitTransactionAsync(alice, createMultipleItemsTx);
+ await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
+ const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
+ {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
+ {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+
+ await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
const itemsListIndexAfter = await getLastTokenId(api, collectionId);
expect(itemsListIndexAfter).to.be.equal(3);
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]),
- )).to.not.be.rejected;
-
expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
expect(await getTokenOwner(api, collectionId, 3)).to.be.deep.equal(normalizeAccountId(alice.address));
@@ -197,25 +185,18 @@
it('Create 0x31, 0x32, 0x33 items in active NFT with property itemOwnerOrAdmin', async () => {
await usingApi(async (api: ApiPromise) => {
- const collectionId = await createCollectionExpectSuccess();
+ const collectionId = await createCollectionWithPropsExpectSuccess({propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
- const args = [{Nft: {const_data: '0x31'}},
- {Nft: {const_data: '0x32'}},
- {Nft: {const_data: '0x33'}}];
- const createMultipleItemsTx = api.tx.unique
- .createMultipleItems(collectionId, normalizeAccountId(alice.address), args);
- await submitTransactionAsync(alice, createMultipleItemsTx);
+ const args = [{Nft: {const_data: '0x31', properties: [{key: 'k', value: 'v1'}]}},
+ {Nft: {const_data: '0x32', properties: [{key: 'k', value: 'v2'}]}},
+ {Nft: {const_data: '0x33', properties: [{key: 'k', value: 'v3'}]}}];
+
+ await createMultipleItemsWithPropsExpectSuccess(alice, collectionId, args);
const itemsListIndexAfter = await getLastTokenId(api, collectionId);
expect(itemsListIndexAfter).to.be.equal(3);
-
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collectionId, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]),
- )).to.not.be.rejected;
expect(await getTokenOwner(api, collectionId, 1)).to.be.deep.equal(normalizeAccountId(alice.address));
expect(await getTokenOwner(api, collectionId, 2)).to.be.deep.equal(normalizeAccountId(alice.address));
@@ -451,7 +432,7 @@
it('No editing rights', async () => {
await usingApi(async (api: ApiPromise) => {
const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
@@ -479,7 +460,7 @@
it('User doesnt have editing rights', async () => {
await usingApi(async (api: ApiPromise) => {
const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: false, collectionAdmin: false, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
@@ -530,7 +511,7 @@
it('Adding more than 64 prps', async () => {
await usingApi(async (api: ApiPromise) => {
const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: true, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
await addCollectionAdminExpectSuccess(alice, collectionId, bob.address);
@@ -565,7 +546,7 @@
it('Trying to add bigger property than allowed', async () => {
await usingApi(async (api: ApiPromise) => {
const collectionId = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});
const itemsListIndexBefore = await getLastTokenId(api, collectionId);
expect(itemsListIndexBefore).to.be.equal(0);
const args = [{Nft: {const_data: '0x31'}},
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -48,8 +48,8 @@
});
});
- it('createMultipleItemsEx with property Admin', async () => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ it.only('createMultipleItemsEx with property Admin', async () => {
+ const collection = await createCollectionWithPropsExpectSuccess({mode: {type: 'NFT'}, propPerm: [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]});
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
@@ -57,33 +57,30 @@
const data = [
{
owner: {substrate: alice.address},
- constData: '0x0000',
+ constData: '0x1111',
+ properties: [{key: 'k', value: 'v1'}],
}, {
owner: {substrate: bob.address},
constData: '0x2222',
+ properties: [{key: 'k', value: 'v2'}],
}, {
owner: {substrate: charlie.address},
constData: '0x4444',
+ properties: [{key: 'k', value: 'v3'}],
},
];
-
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: false}}]),
- )).to.not.be.rejected;
await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
NFT: data,
}));
- const tokens = await api.query.nonfungible.tokenData.entries(collection);
- const json = tokens.map(([, token]) => token.toJSON());
- expect(json).to.be.deep.equal(data);
+ for (let i = 1; i < 4; i++) {
+ expect(await api.rpc.unique.tokenProperties(collection, i)).not.to.be.empty;
+ }
});
});
it('createMultipleItemsEx with property AdminConst', async () => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const collection = await createCollectionWithPropsExpectSuccess({mode: {type: 'NFT'}, propPerm: [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]});
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
@@ -92,33 +89,29 @@
{
owner: {substrate: alice.address},
constData: '0x0000',
+ properties: [{key: 'k', value: 'v1'}],
}, {
owner: {substrate: bob.address},
constData: '0x2222',
+ properties: [{key: 'k', value: 'v2'}],
}, {
owner: {substrate: charlie.address},
constData: '0x4444',
+ properties: [{key: 'k', value: 'v3'}],
},
];
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: false}}]),
- )).to.not.be.rejected;
await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
NFT: data,
}));
-
-
- const tokens = await api.query.nonfungible.tokenData.entries(collection);
- const json = tokens.map(([, token]) => token.toJSON());
- expect(json).to.be.deep.equal(data);
+ for (let i = 1; i < 4; i++) {
+ expect(await api.rpc.unique.tokenProperties(collection, i)).not.to.be.empty;
+ }
});
});
it('createMultipleItemsEx with property itemOwnerOrAdmin', async () => {
- const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ const collection = await createCollectionWithPropsExpectSuccess({mode: {type: 'NFT'}, propPerm: [{key: 'k', permission: {mutable: false, collectionAdmin: true, tokenOwner: true}}]});
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
@@ -127,34 +120,30 @@
{
owner: {substrate: alice.address},
constData: '0x0000',
+ properties: [{key: 'k', value: 'v1'}],
}, {
owner: {substrate: bob.address},
constData: '0x2222',
+ properties: [{key: 'k', value: 'v2'}],
}, {
owner: {substrate: charlie.address},
constData: '0x4444',
+ properties: [{key: 'k', value: 'v3'}],
},
];
- await expect(executeTransaction(
- api,
- alice,
- api.tx.unique.setPropertyPermissions(collection, [{key: 'k', permission: {mutable: true, collectionAdmin: true, tokenOwner: true}}]),
- )).to.not.be.rejected;
await executeTransaction(api, alice, api.tx.unique.createMultipleItemsEx(collection, {
NFT: data,
}));
-
-
- const tokens = await api.query.nonfungible.tokenData.entries(collection);
- const json = tokens.map(([, token]) => token.toJSON());
- expect(json).to.be.deep.equal(data);
+ for (let i = 1; i < 4; i++) {
+ expect(await api.rpc.unique.tokenProperties(collection, i)).not.to.be.empty;
+ }
});
});
it('No editing rights', async () => {
const collection = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: true, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: true, collectionAdmin: false, tokenOwner: false}}]});
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
@@ -188,7 +177,7 @@
it('User doesnt have editing rights', async () => {
const collection = await createCollectionWithPropsExpectSuccess({properties: [{key: 'key1', value: 'v'}],
- propPerm: [{key: 'key1', mutable: false, collectionAdmin: false, tokenOwner: false}]});
+ propPerm: [{key: 'key1', permission: {mutable: false, collectionAdmin: false, tokenOwner: false}}]});
const alice = privateKey('//Alice');
const bob = privateKey('//Bob');
const charlie = privateKey('//Charlie');
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 privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection} from '@polkadot/types/lookup';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 constData: number[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175 const result: GenericResult = {176 success: false,177 };178 events.forEach(({event: {method}}) => {179 // console.log(` ${phase}: ${section}.${method}:: ${data}`);180 if (method === 'ExtrinsicSuccess') {181 result.success = true;182 }183 });184 return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190 let success = false;191 let collectionId = 0;192 events.forEach(({event: {data, method, section}}) => {193 // console.log(` ${phase}: ${section}.${method}:: ${data}`);194 if (method == 'ExtrinsicSuccess') {195 success = true;196 } else if ((section == 'common') && (method == 'CollectionCreated')) {197 collectionId = parseInt(data[0].toString(), 10);198 }199 });200 const result: CreateCollectionResult = {201 success,202 collectionId,203 };204 return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208 let success = false;209 let collectionId = 0;210 let itemId = 0;211 let recipient;212213 const results : CreateItemResult[] = [];214215 events.forEach(({event: {data, method, section}}) => {216 // console.log(` ${phase}: ${section}.${method}:: ${data}`);217 if (method == 'ExtrinsicSuccess') {218 success = true;219 } else if ((section == 'common') && (method == 'ItemCreated')) {220 collectionId = parseInt(data[0].toString(), 10);221 itemId = parseInt(data[1].toString(), 10);222 recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 }233 });234235 return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239 let success = false;240 let collectionId = 0;241 let itemId = 0;242 let recipient;243 events.forEach(({event: {data, method, section}}) => {244 // console.log(` ${phase}: ${section}.${method}:: ${data}`);245 if (method == 'ExtrinsicSuccess') {246 success = true;247 } else if ((section == 'common') && (method == 'ItemCreated')) {248 collectionId = parseInt(data[0].toString(), 10);249 itemId = parseInt(data[1].toString(), 10);250 recipient = normalizeAccountId(data[2].toJSON() as any);251 }252 });253 const result: CreateItemResult = {254 success,255 collectionId,256 itemId,257 recipient,258 };259 return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263 for (const {event} of events) {264 if (api.events.common.Transfer.is(event)) {265 const [collection, token, sender, recipient, value] = event.data;266 return {267 collectionId: collection.toNumber(),268 itemId: token.toNumber(),269 sender: normalizeAccountId(sender.toJSON() as any),270 recipient: normalizeAccountId(recipient.toJSON() as any),271 value: value.toBigInt(),272 };273 }274 }275 throw new Error('no transfer event');276}277278interface Nft {279 type: 'NFT';280}281282interface Fungible {283 type: 'Fungible';284 decimalPoints: number;285}286287interface ReFungible {288 type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294 key: any,295 value: any,296};297298type PropertyPermission = {299 key: any,300 mutable: boolean;301 collectionAdmin: boolean;302 tokenOwner: boolean;303}304305export type CreateCollectionParams = {306 mode: CollectionMode,307 name: string,308 description: string,309 tokenPrefix: string,310 schemaVersion: string,311 properties?: Array<Property>,312 propPerm?: Array<PropertyPermission>313};314315const defaultCreateCollectionParams: CreateCollectionParams = {316 description: 'description',317 mode: {type: 'NFT'},318 name: 'name',319 tokenPrefix: 'prefix',320 schemaVersion: 'ImageURL',321};322323export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {324 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};325326 let collectionId = 0;327 await usingApi(async (api) => {328 // Get number of collections before the transaction329 const collectionCountBefore = await getCreatedCollectionCount(api);330331 // Run the CreateCollection transaction332 const alicePrivateKey = privateKey('//Alice');333334 let modeprm = {};335 if (mode.type === 'NFT') {336 modeprm = {nft: null};337 } else if (mode.type === 'Fungible') {338 modeprm = {fungible: mode.decimalPoints};339 } else if (mode.type === 'ReFungible') {340 modeprm = {refungible: null};341 }342343 const tx = api.tx.unique.createCollectionEx({344 name: strToUTF16(name),345 description: strToUTF16(description),346 tokenPrefix: strToUTF16(tokenPrefix),347 mode: modeprm as any,348 schemaVersion: schemaVersion,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) => {382 // Get number of collections before the transaction383 const collectionCountBefore = await getCreatedCollectionCount(api);384385 // Run the CreateCollection transaction386 const alicePrivateKey = privateKey('//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) => {430 // Get number of collections before the transaction431 const collectionCountBefore = await getCreatedCollectionCount(api);432433 // Run the CreateCollection transaction434 const alicePrivateKey = privateKey('//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) => {469 // Get number of collections before the transaction470 const collectionCountBefore = await getCreatedCollectionCount(api);471472 // Run the CreateCollection transaction473 const alicePrivateKey = privateKey('//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) => {523 // Run the DestroyCollection transaction524 const alicePrivateKey = privateKey(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) => {532 // Run the DestroyCollection transaction533 const alicePrivateKey = privateKey(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 async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {555 await usingApi(async (api) => {556 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);557 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;558 const result = getGenericResult(events);559560 expect(result.success).to.be.false;561 });562}563564export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {565 await usingApi(async (api) => {566567 // Run the transaction568 const senderPrivateKey = privateKey(sender);569 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);570 const events = await submitTransactionAsync(senderPrivateKey, tx);571 const result = getGenericResult(events);572573 // Get the collection574 const collection = await queryCollectionExpectSuccess(api, collectionId);575576 // What to expect577 expect(result.success).to.be.true;578 expect(collection.sponsorship.toJSON()).to.deep.equal({579 unconfirmed: sponsor,580 });581 });582}583584export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {585 await usingApi(async (api) => {586587 // Run the transaction588 const alicePrivateKey = privateKey(sender);589 const tx = api.tx.unique.removeCollectionSponsor(collectionId);590 const events = await submitTransactionAsync(alicePrivateKey, tx);591 const result = getGenericResult(events);592593 // Get the collection594 const collection = await queryCollectionExpectSuccess(api, collectionId);595596 // What to expect597 expect(result.success).to.be.true;598 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});599 });600}601602export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {603 await usingApi(async (api) => {604605 // Run the transaction606 const alicePrivateKey = privateKey(senderSeed);607 const tx = api.tx.unique.removeCollectionSponsor(collectionId);608 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;609 });610}611612export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {613 await usingApi(async (api) => {614615 // Run the transaction616 const alicePrivateKey = privateKey(senderSeed);617 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);618 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619 });620}621622export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {623 await usingApi(async (api) => {624625 // Run the transaction626 const sender = privateKey(senderSeed);627 const tx = api.tx.unique.confirmSponsorship(collectionId);628 const events = await submitTransactionAsync(sender, tx);629 const result = getGenericResult(events);630631 // Get the collection632 const collection = await queryCollectionExpectSuccess(api, collectionId);633634 // What to expect635 expect(result.success).to.be.true;636 expect(collection.sponsorship.toJSON()).to.be.deep.equal({637 confirmed: sender.address,638 });639 });640}641642643export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {644 await usingApi(async (api) => {645646 // Run the transaction647 const sender = privateKey(senderSeed);648 const tx = api.tx.unique.confirmSponsorship(collectionId);649 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;650 });651}652653export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {654 await usingApi(async (api) => {655 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);656 const events = await submitTransactionAsync(sender, tx);657 const result = getGenericResult(events);658659 expect(result.success).to.be.true;660 });661}662663export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {664 await usingApi(async (api) => {665 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);666 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;667 const result = getGenericResult(events);668669 expect(result.success).to.be.false;670 });671}672673export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {674675 await usingApi(async (api) => {676677 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);678 const events = await submitTransactionAsync(sender, tx);679 const result = getGenericResult(events);680681 expect(result.success).to.be.true;682 });683}684685export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {686687 await usingApi(async (api) => {688689 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);690 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;691 const result = getGenericResult(events);692693 expect(result.success).to.be.false;694 });695}696697export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {698 await usingApi(async (api) => {699 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);700 const events = await submitTransactionAsync(sender, tx);701 const result = getGenericResult(events);702703 expect(result.success).to.be.true;704 });705}706707export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {708 await usingApi(async (api) => {709 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);710 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;711 const result = getGenericResult(events);712713 expect(result.success).to.be.false;714 });715}716717export async function getNextSponsored(718 api: ApiPromise,719 collectionId: number,720 account: string | CrossAccountId,721 tokenId: number,722): Promise<number> {723 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));724}725726export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {727 await usingApi(async (api) => {728 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);729 const events = await submitTransactionAsync(sender, tx);730 const result = getGenericResult(events);731732 expect(result.success).to.be.true;733 });734}735736export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {737 let allowlisted = false;738 await usingApi(async (api) => {739 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;740 });741 return allowlisted;742}743744export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {745 await usingApi(async (api) => {746 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());747 const events = await submitTransactionAsync(sender, tx);748 const result = getGenericResult(events);749750 expect(result.success).to.be.true;751 });752}753754export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {755 await usingApi(async (api) => {756 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());757 const events = await submitTransactionAsync(sender, tx);758 const result = getGenericResult(events);759760 expect(result.success).to.be.true;761 });762}763764export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {765 await usingApi(async (api) => {766 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());767 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;768 const result = getGenericResult(events);769770 expect(result.success).to.be.false;771 });772}773774export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {775 await usingApi(async (api) => {776 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));777 const events = await submitTransactionAsync(sender, tx);778 const result = getGenericResult(events);779780 expect(result.success).to.be.true;781 });782}783784export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {785 await usingApi(async (api) => {786 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));787 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;788 });789}790791export interface CreateFungibleData {792 readonly Value: bigint;793}794795export interface CreateReFungibleData { }796export interface CreateNftData { }797798export type CreateItemData = {799 NFT: CreateNftData;800} | {801 Fungible: CreateFungibleData;802} | {803 ReFungible: CreateReFungibleData;804};805806export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {807 await usingApi(async (api) => {808 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);809 // if burning token by admin - use adminButnItemExpectSuccess810 expect(balanceBefore >= BigInt(value)).to.be.true;811812 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);813 const events = await submitTransactionAsync(sender, tx);814 const result = getGenericResult(events);815 expect(result.success).to.be.true;816817 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);818 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);819 });820}821822export async function823approveExpectSuccess(824 collectionId: number,825 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,826) {827 await usingApi(async (api: ApiPromise) => {828 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);829 const events = await submitTransactionAsync(owner, approveUniqueTx);830 const result = getGenericResult(events);831 expect(result.success).to.be.true;832833 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));834 });835}836837export async function adminApproveFromExpectSuccess(838 collectionId: number,839 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,840) {841 await usingApi(async (api: ApiPromise) => {842 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);843 const events = await submitTransactionAsync(admin, approveUniqueTx);844 const result = getGenericResult(events);845 expect(result.success).to.be.true;846847 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));848 });849}850851export async function852transferFromExpectSuccess(853 collectionId: number,854 tokenId: number,855 accountApproved: IKeyringPair,856 accountFrom: IKeyringPair | CrossAccountId,857 accountTo: IKeyringPair | CrossAccountId,858 value: number | bigint = 1,859 type = 'NFT',860) {861 await usingApi(async (api: ApiPromise) => {862 const from = normalizeAccountId(accountFrom);863 const to = normalizeAccountId(accountTo);864 let balanceBefore = 0n;865 if (type === 'Fungible' || type === 'ReFungible') {866 balanceBefore = await getBalance(api, collectionId, to, tokenId);867 }868 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);869 const events = await submitTransactionAsync(accountApproved, transferFromTx);870 const result = getCreateItemResult(events);871 // tslint:disable-next-line:no-unused-expression872 expect(result.success).to.be.true;873 if (type === 'NFT') {874 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);875 }876 if (type === 'Fungible') {877 const balanceAfter = await getBalance(api, collectionId, to, tokenId);878 if (JSON.stringify(to) !== JSON.stringify(from)) {879 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));880 } else {881 expect(balanceAfter).to.be.equal(balanceBefore);882 }883 }884 if (type === 'ReFungible') {885 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));886 }887 });888}889890export async function891transferFromExpectFail(892 collectionId: number,893 tokenId: number,894 accountApproved: IKeyringPair,895 accountFrom: IKeyringPair,896 accountTo: IKeyringPair,897 value: number | bigint = 1,898) {899 await usingApi(async (api: ApiPromise) => {900 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);901 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;902 const result = getCreateCollectionResult(events);903 // tslint:disable-next-line:no-unused-expression904 expect(result.success).to.be.false;905 });906}907908/* eslint no-async-promise-executor: "off" */909async function getBlockNumber(api: ApiPromise): Promise<number> {910 return new Promise<number>(async (resolve) => {911 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {912 unsubscribe();913 resolve(head.number.toNumber());914 });915 });916}917918export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {919 await usingApi(async (api) => {920 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));921 const events = await submitTransactionAsync(sender, changeAdminTx);922 const result = getCreateCollectionResult(events);923 expect(result.success).to.be.true;924 });925}926927export async function928getFreeBalance(account: IKeyringPair): Promise<bigint> {929 let balance = 0n;930 await usingApi(async (api) => {931 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());932 });933934 return balance;935}936937export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {938 const tx = api.tx.balances.transfer(target, amount);939 const events = await submitTransactionAsync(source, tx);940 const result = getGenericResult(events);941 expect(result.success).to.be.true;942}943944export async function945scheduleTransferExpectSuccess(946 collectionId: number,947 tokenId: number,948 sender: IKeyringPair,949 recipient: IKeyringPair,950 value: number | bigint = 1,951 blockSchedule: number,952) {953 await usingApi(async (api: ApiPromise) => {954 const blockNumber: number | undefined = await getBlockNumber(api);955 const expectedBlockNumber = blockNumber + blockSchedule;956957 expect(blockNumber).to.be.greaterThan(0);958 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);959 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);960961 await submitTransactionAsync(sender, scheduleTx);962963 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();964965 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));966967 // sleep for 4 blocks968 await waitNewBlocks(blockSchedule + 1);969970 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();971972 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));973 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);974 });975}976977978export async function979transferExpectSuccess(980 collectionId: number,981 tokenId: number,982 sender: IKeyringPair,983 recipient: IKeyringPair | CrossAccountId,984 value: number | bigint = 1,985 type = 'NFT',986) {987 await usingApi(async (api: ApiPromise) => {988 const from = normalizeAccountId(sender);989 const to = normalizeAccountId(recipient);990991 let balanceBefore = 0n;992 if (type === 'Fungible') {993 balanceBefore = await getBalance(api, collectionId, to, tokenId);994 }995 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);996 const events = await executeTransaction(api, sender, transferTx);997998 const result = getTransferResult(api, events);999 expect(result.collectionId).to.be.equal(collectionId);1000 expect(result.itemId).to.be.equal(tokenId);1001 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1002 expect(result.recipient).to.be.deep.equal(to);1003 expect(result.value).to.be.equal(BigInt(value));10041005 if (type === 'NFT') {1006 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1007 }1008 if (type === 'Fungible') {1009 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1010 if (JSON.stringify(to) !== JSON.stringify(from)) {1011 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1012 } else {1013 expect(balanceAfter).to.be.equal(balanceBefore);1014 }1015 }1016 if (type === 'ReFungible') {1017 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1018 }1019 });1020}10211022export async function1023transferExpectFailure(1024 collectionId: number,1025 tokenId: number,1026 sender: IKeyringPair,1027 recipient: IKeyringPair | CrossAccountId,1028 value: number | bigint = 1,1029) {1030 await usingApi(async (api: ApiPromise) => {1031 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1032 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1033 const result = getGenericResult(events);1034 // if (events && Array.isArray(events)) {1035 // const result = getCreateCollectionResult(events);1036 // tslint:disable-next-line:no-unused-expression1037 expect(result.success).to.be.false;1038 //}1039 });1040}10411042export async function1043approveExpectFail(1044 collectionId: number,1045 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1046) {1047 await usingApi(async (api: ApiPromise) => {1048 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1049 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1050 const result = getCreateCollectionResult(events);1051 // tslint:disable-next-line:no-unused-expression1052 expect(result.success).to.be.false;1053 });1054}10551056export async function getBalance(1057 api: ApiPromise,1058 collectionId: number,1059 owner: string | CrossAccountId,1060 token: number,1061): Promise<bigint> {1062 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1063}1064export async function getTokenOwner(1065 api: ApiPromise,1066 collectionId: number,1067 token: number,1068): Promise<CrossAccountId> {1069 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1070 if (owner == null) throw new Error('owner == null');1071 return normalizeAccountId(owner);1072}1073export async function getTopmostTokenOwner(1074 api: ApiPromise,1075 collectionId: number,1076 token: number,1077): Promise<CrossAccountId> {1078 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1079 if (owner == null) throw new Error('owner == null');1080 return normalizeAccountId(owner);1081}1082export async function isTokenExists(1083 api: ApiPromise,1084 collectionId: number,1085 token: number,1086): Promise<boolean> {1087 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1088}1089export async function getLastTokenId(1090 api: ApiPromise,1091 collectionId: number,1092): Promise<number> {1093 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1094}1095export async function getAdminList(1096 api: ApiPromise,1097 collectionId: number,1098): Promise<string[]> {1099 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1100}1101export async function getConstMetadata(1102 api: ApiPromise,1103 collectionId: number,1104 tokenId: number,1105): Promise<number[]> {1106 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1107}11081109export async function createFungibleItemExpectSuccess(1110 sender: IKeyringPair,1111 collectionId: number,1112 data: CreateFungibleData,1113 owner: CrossAccountId | string = sender.address,1114) {1115 return await usingApi(async (api) => {1116 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11171118 const events = await submitTransactionAsync(sender, tx);1119 const result = getCreateItemResult(events);11201121 expect(result.success).to.be.true;1122 return result.itemId;1123 });1124}11251126export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1127 let newItemId = 0;1128 await usingApi(async (api) => {1129 const to = normalizeAccountId(owner);1130 const itemCountBefore = await getLastTokenId(api, collectionId);1131 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11321133 let tx;1134 if (createMode === 'Fungible') {1135 const createData = {fungible: {value: 10}};1136 tx = api.tx.unique.createItem(collectionId, to, createData as any);1137 } else if (createMode === 'ReFungible') {1138 const createData = {refungible: {const_data: [], pieces: 100}};1139 tx = api.tx.unique.createItem(collectionId, to, createData as any);1140 } else {1141 const createData = {nft: {const_data: []}};1142 tx = api.tx.unique.createItem(collectionId, to, createData as any);1143 }11441145 const events = await submitTransactionAsync(sender, tx);1146 const result = getCreateItemResult(events);11471148 const itemCountAfter = await getLastTokenId(api, collectionId);1149 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11501151 // What to expect1152 // tslint:disable-next-line:no-unused-expression1153 expect(result.success).to.be.true;1154 if (createMode === 'Fungible') {1155 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1156 } else {1157 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1158 }1159 expect(collectionId).to.be.equal(result.collectionId);1160 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1161 expect(to).to.be.deep.equal(result.recipient);1162 newItemId = result.itemId;1163 });1164 return newItemId;1165}11661167export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1168 await usingApi(async (api) => {1169 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);11701171 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1172 const result = getCreateItemResult(events);11731174 expect(result.success).to.be.false;1175 });1176}11771178export async function setPublicAccessModeExpectSuccess(1179 sender: IKeyringPair, collectionId: number,1180 accessMode: 'Normal' | 'AllowList',1181) {1182 await usingApi(async (api) => {11831184 // Run the transaction1185 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1186 const events = await submitTransactionAsync(sender, tx);1187 const result = getGenericResult(events);11881189 // Get the collection1190 const collection = await queryCollectionExpectSuccess(api, collectionId);11911192 // What to expect1193 // tslint:disable-next-line:no-unused-expression1194 expect(result.success).to.be.true;1195 expect(collection.access.toHuman()).to.be.equal(accessMode);1196 });1197}11981199export async function setPublicAccessModeExpectFail(1200 sender: IKeyringPair, collectionId: number,1201 accessMode: 'Normal' | 'AllowList',1202) {1203 await usingApi(async (api) => {12041205 // Run the transaction1206 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1207 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1208 const result = getGenericResult(events);12091210 // What to expect1211 // tslint:disable-next-line:no-unused-expression1212 expect(result.success).to.be.false;1213 });1214}12151216export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1217 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1218}12191220export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1221 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1222}12231224export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1225 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1226}12271228export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1229 await usingApi(async (api) => {12301231 // Run the transaction1232 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1233 const events = await submitTransactionAsync(sender, tx);1234 const result = getGenericResult(events);1235 expect(result.success).to.be.true;12361237 // Get the collection1238 const collection = await queryCollectionExpectSuccess(api, collectionId);12391240 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1241 });1242}12431244export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1245 await setMintPermissionExpectSuccess(sender, collectionId, true);1246}12471248export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1249 await usingApi(async (api) => {1250 // Run the transaction1251 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1252 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1253 const result = getCreateCollectionResult(events);1254 // tslint:disable-next-line:no-unused-expression1255 expect(result.success).to.be.false;1256 });1257}12581259export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1260 await usingApi(async (api) => {1261 // Run the transaction1262 const tx = api.tx.unique.setChainLimits(limits);1263 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1264 const result = getCreateCollectionResult(events);1265 // tslint:disable-next-line:no-unused-expression1266 expect(result.success).to.be.false;1267 });1268}12691270export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1271 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1272}12731274export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1275 await usingApi(async (api) => {1276 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;12771278 // Run the transaction1279 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1280 const events = await submitTransactionAsync(sender, tx);1281 const result = getGenericResult(events);1282 expect(result.success).to.be.true;12831284 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1285 });1286}12871288export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1289 await usingApi(async (api) => {12901291 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12921293 // Run the transaction1294 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1295 const events = await submitTransactionAsync(sender, tx);1296 const result = getGenericResult(events);1297 expect(result.success).to.be.true;12981299 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1300 });1301}13021303export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1304 await usingApi(async (api) => {13051306 // Run the transaction1307 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1308 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1309 const result = getGenericResult(events);13101311 // What to expect1312 // tslint:disable-next-line:no-unused-expression1313 expect(result.success).to.be.false;1314 });1315}13161317export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1318 await usingApi(async (api) => {1319 // Run the transaction1320 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1321 const events = await submitTransactionAsync(sender, tx);1322 const result = getGenericResult(events);13231324 // What to expect1325 // tslint:disable-next-line:no-unused-expression1326 expect(result.success).to.be.true;1327 });1328}13291330export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1331 await usingApi(async (api) => {1332 // Run the transaction1333 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1334 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1335 const result = getGenericResult(events);13361337 // What to expect1338 // tslint:disable-next-line:no-unused-expression1339 expect(result.success).to.be.false;1340 });1341}13421343export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1344 : Promise<UpDataStructsRpcCollection | null> => {1345 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1346};13471348export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1349 // set global object - collectionsCount1350 return (await api.rpc.unique.collectionStats()).created.toNumber();1351};13521353export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1354 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1355}13561357export async function waitNewBlocks(blocksCount = 1): Promise<void> {1358 await usingApi(async (api) => {1359 const promise = new Promise<void>(async (resolve) => {1360 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1361 if (blocksCount > 0) {1362 blocksCount--;1363 } else {1364 unsubscribe();1365 resolve();1366 }1367 });1368 });1369 return promise;1370 });1371}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 {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 privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData} from '@polkadot/types/lookup';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 constData: number[];145}146147export function uniqueEventMessage(events: EventRecord[]): IGetMessage {148 let checkMsgUnqMethod = '';149 let checkMsgTrsMethod = '';150 let checkMsgSysMethod = '';151 events.forEach(({event: {method, section}}) => {152 if (section === 'common') {153 checkMsgUnqMethod = method;154 } else if (section === 'treasury') {155 checkMsgTrsMethod = method;156 } else if (section === 'system') {157 checkMsgSysMethod = method;158 } else { return null; }159 });160 const result: IGetMessage = {161 checkMsgUnqMethod,162 checkMsgTrsMethod,163 checkMsgSysMethod,164 };165 return result;166}167168export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {169 const event = events.find(r => check(r.event));170 if (!event) return;171 return event.event as T;172}173174export function getGenericResult(events: EventRecord[]): GenericResult {175 const result: GenericResult = {176 success: false,177 };178 events.forEach(({event: {method}}) => {179 // console.log(` ${phase}: ${section}.${method}:: ${data}`);180 if (method === 'ExtrinsicSuccess') {181 result.success = true;182 }183 });184 return result;185}186187188189export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {190 let success = false;191 let collectionId = 0;192 events.forEach(({event: {data, method, section}}) => {193 // console.log(` ${phase}: ${section}.${method}:: ${data}`);194 if (method == 'ExtrinsicSuccess') {195 success = true;196 } else if ((section == 'common') && (method == 'CollectionCreated')) {197 collectionId = parseInt(data[0].toString(), 10);198 }199 });200 const result: CreateCollectionResult = {201 success,202 collectionId,203 };204 return result;205}206207export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {208 let success = false;209 let collectionId = 0;210 let itemId = 0;211 let recipient;212213 const results : CreateItemResult[] = [];214215 events.forEach(({event: {data, method, section}}) => {216 // console.log(` ${phase}: ${section}.${method}:: ${data}`);217 if (method == 'ExtrinsicSuccess') {218 success = true;219 } else if ((section == 'common') && (method == 'ItemCreated')) {220 collectionId = parseInt(data[0].toString(), 10);221 itemId = parseInt(data[1].toString(), 10);222 recipient = normalizeAccountId(data[2].toJSON() as any);223224 const itemRes: CreateItemResult = {225 success,226 collectionId,227 itemId,228 recipient,229 };230231 results.push(itemRes);232 }233 });234235 return results;236}237238export function getCreateItemResult(events: EventRecord[]): CreateItemResult {239 let success = false;240 let collectionId = 0;241 let itemId = 0;242 let recipient;243 events.forEach(({event: {data, method, section}}) => {244 // console.log(` ${phase}: ${section}.${method}:: ${data}`);245 if (method == 'ExtrinsicSuccess') {246 success = true;247 } else if ((section == 'common') && (method == 'ItemCreated')) {248 collectionId = parseInt(data[0].toString(), 10);249 itemId = parseInt(data[1].toString(), 10);250 recipient = normalizeAccountId(data[2].toJSON() as any);251 }252 });253 const result: CreateItemResult = {254 success,255 collectionId,256 itemId,257 recipient,258 };259 return result;260}261262export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {263 for (const {event} of events) {264 if (api.events.common.Transfer.is(event)) {265 const [collection, token, sender, recipient, value] = event.data;266 return {267 collectionId: collection.toNumber(),268 itemId: token.toNumber(),269 sender: normalizeAccountId(sender.toJSON() as any),270 recipient: normalizeAccountId(recipient.toJSON() as any),271 value: value.toBigInt(),272 };273 }274 }275 throw new Error('no transfer event');276}277278interface Nft {279 type: 'NFT';280}281282interface Fungible {283 type: 'Fungible';284 decimalPoints: number;285}286287interface ReFungible {288 type: 'ReFungible';289}290291type CollectionMode = Nft | Fungible | ReFungible;292293export type Property = {294 key: any,295 value: any,296};297298type Permission = {299 mutable: boolean;300 collectionAdmin: boolean;301 tokenOwner: boolean;302}303304type PropertyPermission = {305 key: any;306 permission: Permission;307}308309export type CreateCollectionParams = {310 mode: CollectionMode,311 name: string,312 description: string,313 tokenPrefix: string,314 schemaVersion: string,315 properties?: Array<Property>,316 propPerm?: Array<PropertyPermission>317};318319const defaultCreateCollectionParams: CreateCollectionParams = {320 description: 'description',321 mode: {type: 'NFT'},322 name: 'name',323 tokenPrefix: 'prefix',324 schemaVersion: 'ImageURL',325};326327export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {328 const {name, description, mode, tokenPrefix, schemaVersion} = {...defaultCreateCollectionParams, ...params};329330 let collectionId = 0;331 await usingApi(async (api) => {332 // Get number of collections before the transaction333 const collectionCountBefore = await getCreatedCollectionCount(api);334335 // Run the CreateCollection transaction336 const alicePrivateKey = privateKey('//Alice');337338 let modeprm = {};339 if (mode.type === 'NFT') {340 modeprm = {nft: null};341 } else if (mode.type === 'Fungible') {342 modeprm = {fungible: mode.decimalPoints};343 } else if (mode.type === 'ReFungible') {344 modeprm = {refungible: null};345 }346347 const tx = api.tx.unique.createCollectionEx({348 name: strToUTF16(name),349 description: strToUTF16(description),350 tokenPrefix: strToUTF16(tokenPrefix),351 mode: modeprm as any,352 schemaVersion: schemaVersion,353 });354 const events = await submitTransactionAsync(alicePrivateKey, tx);355 const result = getCreateCollectionResult(events);356357 // Get number of collections after the transaction358 const collectionCountAfter = await getCreatedCollectionCount(api);359360 // Get the collection361 const collection = await queryCollectionExpectSuccess(api, result.collectionId);362363 // What to expect364 // tslint:disable-next-line:no-unused-expression365 expect(result.success).to.be.true;366 expect(result.collectionId).to.be.equal(collectionCountAfter);367 // tslint:disable-next-line:no-unused-expression368 expect(collection).to.be.not.null;369 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');370 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));371 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);372 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);373 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);374375 collectionId = result.collectionId;376 });377378 return collectionId;379}380381export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {382 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};383384 let collectionId = 0;385 await usingApi(async (api) => {386 // Get number of collections before the transaction387 const collectionCountBefore = await getCreatedCollectionCount(api);388389 // Run the CreateCollection transaction390 const alicePrivateKey = privateKey('//Alice');391392 let modeprm = {};393 if (mode.type === 'NFT') {394 modeprm = {nft: null};395 } else if (mode.type === 'Fungible') {396 modeprm = {fungible: mode.decimalPoints};397 } else if (mode.type === 'ReFungible') {398 modeprm = {refungible: null};399 }400401 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});402 const events = await submitTransactionAsync(alicePrivateKey, tx);403 const result = getCreateCollectionResult(events);404405 // Get number of collections after the transaction406 const collectionCountAfter = await getCreatedCollectionCount(api);407408 // Get the collection409 const collection = await queryCollectionExpectSuccess(api, result.collectionId);410411 // What to expect412 // tslint:disable-next-line:no-unused-expression413 expect(result.success).to.be.true;414 expect(result.collectionId).to.be.equal(collectionCountAfter);415 // tslint:disable-next-line:no-unused-expression416 expect(collection).to.be.not.null;417 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');418 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));419 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);420 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);421 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);422423424 collectionId = result.collectionId;425 });426427 return collectionId;428}429430export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {431 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};432433 await usingApi(async (api) => {434 // Get number of collections before the transaction435 const collectionCountBefore = await getCreatedCollectionCount(api);436437 // Run the CreateCollection transaction438 const alicePrivateKey = privateKey('//Alice');439440 let modeprm = {};441 if (mode.type === 'NFT') {442 modeprm = {nft: null};443 } else if (mode.type === 'Fungible') {444 modeprm = {fungible: mode.decimalPoints};445 } else if (mode.type === 'ReFungible') {446 modeprm = {refungible: null};447 }448449 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});450 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451452453 // Get number of collections after the transaction454 const collectionCountAfter = await getCreatedCollectionCount(api);455456 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');457 });458}459460export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {461 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};462463 let modeprm = {};464 if (mode.type === 'NFT') {465 modeprm = {nft: null};466 } else if (mode.type === 'Fungible') {467 modeprm = {fungible: mode.decimalPoints};468 } else if (mode.type === 'ReFungible') {469 modeprm = {refungible: null};470 }471472 await usingApi(async (api) => {473 // Get number of collections before the transaction474 const collectionCountBefore = await getCreatedCollectionCount(api);475476 // Run the CreateCollection transaction477 const alicePrivateKey = privateKey('//Alice');478 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});479 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480481 // Get number of collections after the transaction482 const collectionCountAfter = await getCreatedCollectionCount(api);483484 // What to expect485 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');486 });487}488489export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {490 let bal = 0n;491 let unused;492 do {493 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;494 const keyring = new Keyring({type: 'sr25519'});495 unused = keyring.addFromUri(`//${randomSeed}`);496 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();497 } while (bal !== 0n);498 return unused;499}500501export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {502 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();503}504505export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {506 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));507}508509export async function findNotExistingCollection(api: ApiPromise): Promise<number> {510 const totalNumber = await getCreatedCollectionCount(api);511 const newCollection: number = totalNumber + 1;512 return newCollection;513}514515function getDestroyResult(events: EventRecord[]): boolean {516 let success = false;517 events.forEach(({event: {method}}) => {518 if (method == 'ExtrinsicSuccess') {519 success = true;520 }521 });522 return success;523}524525export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {526 await usingApi(async (api) => {527 // Run the DestroyCollection transaction528 const alicePrivateKey = privateKey(senderSeed);529 const tx = api.tx.unique.destroyCollection(collectionId);530 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;531 });532}533534export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {535 await usingApi(async (api) => {536 // Run the DestroyCollection transaction537 const alicePrivateKey = privateKey(senderSeed);538 const tx = api.tx.unique.destroyCollection(collectionId);539 const events = await submitTransactionAsync(alicePrivateKey, tx);540 const result = getDestroyResult(events);541 expect(result).to.be.true;542543 // What to expect544 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;545 });546}547548export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {549 await usingApi(async (api) => {550 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);551 const events = await submitTransactionAsync(sender, tx);552 const result = getGenericResult(events);553554 expect(result.success).to.be.true;555 });556}557558export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {559 await usingApi(async (api) => {560 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);561 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;562 const result = getGenericResult(events);563564 expect(result.success).to.be.false;565 });566}567568export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {569 await usingApi(async (api) => {570571 // Run the transaction572 const senderPrivateKey = privateKey(sender);573 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);574 const events = await submitTransactionAsync(senderPrivateKey, tx);575 const result = getGenericResult(events);576577 // Get the collection578 const collection = await queryCollectionExpectSuccess(api, collectionId);579580 // What to expect581 expect(result.success).to.be.true;582 expect(collection.sponsorship.toJSON()).to.deep.equal({583 unconfirmed: sponsor,584 });585 });586}587588export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {589 await usingApi(async (api) => {590591 // Run the transaction592 const alicePrivateKey = privateKey(sender);593 const tx = api.tx.unique.removeCollectionSponsor(collectionId);594 const events = await submitTransactionAsync(alicePrivateKey, tx);595 const result = getGenericResult(events);596597 // Get the collection598 const collection = await queryCollectionExpectSuccess(api, collectionId);599600 // What to expect601 expect(result.success).to.be.true;602 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});603 });604}605606export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {607 await usingApi(async (api) => {608609 // Run the transaction610 const alicePrivateKey = privateKey(senderSeed);611 const tx = api.tx.unique.removeCollectionSponsor(collectionId);612 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;613 });614}615616export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {617 await usingApi(async (api) => {618619 // Run the transaction620 const alicePrivateKey = privateKey(senderSeed);621 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);622 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;623 });624}625626export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {627 await usingApi(async (api) => {628629 // Run the transaction630 const sender = privateKey(senderSeed);631 const tx = api.tx.unique.confirmSponsorship(collectionId);632 const events = await submitTransactionAsync(sender, tx);633 const result = getGenericResult(events);634635 // Get the collection636 const collection = await queryCollectionExpectSuccess(api, collectionId);637638 // What to expect639 expect(result.success).to.be.true;640 expect(collection.sponsorship.toJSON()).to.be.deep.equal({641 confirmed: sender.address,642 });643 });644}645646647export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {648 await usingApi(async (api) => {649650 // Run the transaction651 const sender = privateKey(senderSeed);652 const tx = api.tx.unique.confirmSponsorship(collectionId);653 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;654 });655}656657export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {658 await usingApi(async (api) => {659 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);660 const events = await submitTransactionAsync(sender, tx);661 const result = getGenericResult(events);662663 expect(result.success).to.be.true;664 });665}666667export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {668 await usingApi(async (api) => {669 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);670 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;671 const result = getGenericResult(events);672673 expect(result.success).to.be.false;674 });675}676677export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {678679 await usingApi(async (api) => {680681 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);682 const events = await submitTransactionAsync(sender, tx);683 const result = getGenericResult(events);684685 expect(result.success).to.be.true;686 });687}688689export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {690691 await usingApi(async (api) => {692693 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);694 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;695 const result = getGenericResult(events);696697 expect(result.success).to.be.false;698 });699}700701export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {702 await usingApi(async (api) => {703 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);704 const events = await submitTransactionAsync(sender, tx);705 const result = getGenericResult(events);706707 expect(result.success).to.be.true;708 });709}710711export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {712 await usingApi(async (api) => {713 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);714 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;715 const result = getGenericResult(events);716717 expect(result.success).to.be.false;718 });719}720721export async function getNextSponsored(722 api: ApiPromise,723 collectionId: number,724 account: string | CrossAccountId,725 tokenId: number,726): Promise<number> {727 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));728}729730export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {731 await usingApi(async (api) => {732 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);733 const events = await submitTransactionAsync(sender, tx);734 const result = getGenericResult(events);735736 expect(result.success).to.be.true;737 });738}739740export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {741 let allowlisted = false;742 await usingApi(async (api) => {743 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;744 });745 return allowlisted;746}747748export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {749 await usingApi(async (api) => {750 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());751 const events = await submitTransactionAsync(sender, tx);752 const result = getGenericResult(events);753754 expect(result.success).to.be.true;755 });756}757758export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {759 await usingApi(async (api) => {760 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());761 const events = await submitTransactionAsync(sender, tx);762 const result = getGenericResult(events);763764 expect(result.success).to.be.true;765 });766}767768export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {769 await usingApi(async (api) => {770 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());771 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;772 const result = getGenericResult(events);773774 expect(result.success).to.be.false;775 });776}777778export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {779 await usingApi(async (api) => {780 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));781 const events = await submitTransactionAsync(sender, tx);782 const result = getGenericResult(events);783784 expect(result.success).to.be.true;785 });786}787788export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {789 await usingApi(async (api) => {790 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));791 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;792 });793}794795export interface CreateFungibleData {796 readonly Value: bigint;797}798799export interface CreateReFungibleData { }800export interface CreateNftData { }801802export type CreateItemData = {803 NFT: CreateNftData;804} | {805 Fungible: CreateFungibleData;806} | {807 ReFungible: CreateReFungibleData;808};809810export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {811 await usingApi(async (api) => {812 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);813 // if burning token by admin - use adminButnItemExpectSuccess814 expect(balanceBefore >= BigInt(value)).to.be.true;815816 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);817 const events = await submitTransactionAsync(sender, tx);818 const result = getGenericResult(events);819 expect(result.success).to.be.true;820821 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);822 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);823 });824}825826export async function827approveExpectSuccess(828 collectionId: number,829 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,830) {831 await usingApi(async (api: ApiPromise) => {832 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);833 const events = await submitTransactionAsync(owner, approveUniqueTx);834 const result = getGenericResult(events);835 expect(result.success).to.be.true;836837 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));838 });839}840841export async function adminApproveFromExpectSuccess(842 collectionId: number,843 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,844) {845 await usingApi(async (api: ApiPromise) => {846 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);847 const events = await submitTransactionAsync(admin, approveUniqueTx);848 const result = getGenericResult(events);849 expect(result.success).to.be.true;850851 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));852 });853}854855export async function856transferFromExpectSuccess(857 collectionId: number,858 tokenId: number,859 accountApproved: IKeyringPair,860 accountFrom: IKeyringPair | CrossAccountId,861 accountTo: IKeyringPair | CrossAccountId,862 value: number | bigint = 1,863 type = 'NFT',864) {865 await usingApi(async (api: ApiPromise) => {866 const from = normalizeAccountId(accountFrom);867 const to = normalizeAccountId(accountTo);868 let balanceBefore = 0n;869 if (type === 'Fungible' || type === 'ReFungible') {870 balanceBefore = await getBalance(api, collectionId, to, tokenId);871 }872 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);873 const events = await submitTransactionAsync(accountApproved, transferFromTx);874 const result = getCreateItemResult(events);875 // tslint:disable-next-line:no-unused-expression876 expect(result.success).to.be.true;877 if (type === 'NFT') {878 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);879 }880 if (type === 'Fungible') {881 const balanceAfter = await getBalance(api, collectionId, to, tokenId);882 if (JSON.stringify(to) !== JSON.stringify(from)) {883 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));884 } else {885 expect(balanceAfter).to.be.equal(balanceBefore);886 }887 }888 if (type === 'ReFungible') {889 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));890 }891 });892}893894export async function895transferFromExpectFail(896 collectionId: number,897 tokenId: number,898 accountApproved: IKeyringPair,899 accountFrom: IKeyringPair,900 accountTo: IKeyringPair,901 value: number | bigint = 1,902) {903 await usingApi(async (api: ApiPromise) => {904 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);905 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;906 const result = getCreateCollectionResult(events);907 // tslint:disable-next-line:no-unused-expression908 expect(result.success).to.be.false;909 });910}911912/* eslint no-async-promise-executor: "off" */913async function getBlockNumber(api: ApiPromise): Promise<number> {914 return new Promise<number>(async (resolve) => {915 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {916 unsubscribe();917 resolve(head.number.toNumber());918 });919 });920}921922export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {923 await usingApi(async (api) => {924 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));925 const events = await submitTransactionAsync(sender, changeAdminTx);926 const result = getCreateCollectionResult(events);927 expect(result.success).to.be.true;928 });929}930931export async function932getFreeBalance(account: IKeyringPair): Promise<bigint> {933 let balance = 0n;934 await usingApi(async (api) => {935 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());936 });937938 return balance;939}940941export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {942 const tx = api.tx.balances.transfer(target, amount);943 const events = await submitTransactionAsync(source, tx);944 const result = getGenericResult(events);945 expect(result.success).to.be.true;946}947948export async function949scheduleTransferExpectSuccess(950 collectionId: number,951 tokenId: number,952 sender: IKeyringPair,953 recipient: IKeyringPair,954 value: number | bigint = 1,955 blockSchedule: number,956) {957 await usingApi(async (api: ApiPromise) => {958 const blockNumber: number | undefined = await getBlockNumber(api);959 const expectedBlockNumber = blockNumber + blockSchedule;960961 expect(blockNumber).to.be.greaterThan(0);962 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);963 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);964965 await submitTransactionAsync(sender, scheduleTx);966967 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();968969 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));970971 // sleep for 4 blocks972 await waitNewBlocks(blockSchedule + 1);973974 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();975976 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));977 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);978 });979}980981982export async function983transferExpectSuccess(984 collectionId: number,985 tokenId: number,986 sender: IKeyringPair,987 recipient: IKeyringPair | CrossAccountId,988 value: number | bigint = 1,989 type = 'NFT',990) {991 await usingApi(async (api: ApiPromise) => {992 const from = normalizeAccountId(sender);993 const to = normalizeAccountId(recipient);994995 let balanceBefore = 0n;996 if (type === 'Fungible') {997 balanceBefore = await getBalance(api, collectionId, to, tokenId);998 }999 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1000 const events = await executeTransaction(api, sender, transferTx);10011002 const result = getTransferResult(api, events);1003 expect(result.collectionId).to.be.equal(collectionId);1004 expect(result.itemId).to.be.equal(tokenId);1005 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1006 expect(result.recipient).to.be.deep.equal(to);1007 expect(result.value).to.be.equal(BigInt(value));10081009 if (type === 'NFT') {1010 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1011 }1012 if (type === 'Fungible') {1013 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1014 if (JSON.stringify(to) !== JSON.stringify(from)) {1015 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1016 } else {1017 expect(balanceAfter).to.be.equal(balanceBefore);1018 }1019 }1020 if (type === 'ReFungible') {1021 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1022 }1023 });1024}10251026export async function1027transferExpectFailure(1028 collectionId: number,1029 tokenId: number,1030 sender: IKeyringPair,1031 recipient: IKeyringPair | CrossAccountId,1032 value: number | bigint = 1,1033) {1034 await usingApi(async (api: ApiPromise) => {1035 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1036 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1037 const result = getGenericResult(events);1038 // if (events && Array.isArray(events)) {1039 // const result = getCreateCollectionResult(events);1040 // tslint:disable-next-line:no-unused-expression1041 expect(result.success).to.be.false;1042 //}1043 });1044}10451046export async function1047approveExpectFail(1048 collectionId: number,1049 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1050) {1051 await usingApi(async (api: ApiPromise) => {1052 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1053 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1054 const result = getCreateCollectionResult(events);1055 // tslint:disable-next-line:no-unused-expression1056 expect(result.success).to.be.false;1057 });1058}10591060export async function getBalance(1061 api: ApiPromise,1062 collectionId: number,1063 owner: string | CrossAccountId,1064 token: number,1065): Promise<bigint> {1066 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1067}1068export async function getTokenOwner(1069 api: ApiPromise,1070 collectionId: number,1071 token: number,1072): Promise<CrossAccountId> {1073 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1074 if (owner == null) throw new Error('owner == null');1075 return normalizeAccountId(owner);1076}1077export async function getTopmostTokenOwner(1078 api: ApiPromise,1079 collectionId: number,1080 token: number,1081): Promise<CrossAccountId> {1082 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1083 if (owner == null) throw new Error('owner == null');1084 return normalizeAccountId(owner);1085}1086export async function isTokenExists(1087 api: ApiPromise,1088 collectionId: number,1089 token: number,1090): Promise<boolean> {1091 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1092}1093export async function getLastTokenId(1094 api: ApiPromise,1095 collectionId: number,1096): Promise<number> {1097 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1098}1099export async function getAdminList(1100 api: ApiPromise,1101 collectionId: number,1102): Promise<string[]> {1103 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1104}1105export async function getConstMetadata(1106 api: ApiPromise,1107 collectionId: number,1108 tokenId: number,1109): Promise<number[]> {1110 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1111}11121113export async function createFungibleItemExpectSuccess(1114 sender: IKeyringPair,1115 collectionId: number,1116 data: CreateFungibleData,1117 owner: CrossAccountId | string = sender.address,1118) {1119 return await usingApi(async (api) => {1120 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11211122 const events = await submitTransactionAsync(sender, tx);1123 const result = getCreateItemResult(events);11241125 expect(result.success).to.be.true;1126 return result.itemId;1127 });1128}11291130export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1131 await usingApi(async (api) => {1132 const to = normalizeAccountId(owner);1133 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11341135 const events = await submitTransactionAsync(sender, tx);1136 const result = getCreateItemsResult(events);11371138 for (let res of result) {1139 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1140 }1141 });1142}11431144export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1145 let newItemId = 0;1146 await usingApi(async (api) => {1147 const to = normalizeAccountId(owner);1148 const itemCountBefore = await getLastTokenId(api, collectionId);1149 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11501151 let tx;1152 if (createMode === 'Fungible') {1153 const createData = {fungible: {value: 10}};1154 tx = api.tx.unique.createItem(collectionId, to, createData as any);1155 } else if (createMode === 'ReFungible') {1156 const createData = {refungible: {const_data: [], pieces: 100}};1157 tx = api.tx.unique.createItem(collectionId, to, createData as any);1158 } else {1159 const data = api.createType('UpDataStructsCreateItemData', { NFT: { constData: 'test', properties: props}});1160 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1161 }11621163 const events = await submitTransactionAsync(sender, tx);1164 const result = getCreateItemResult(events);11651166 const itemCountAfter = await getLastTokenId(api, collectionId);1167 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11681169 if (createMode === 'NFT') {1170 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1171 }11721173 // What to expect1174 // tslint:disable-next-line:no-unused-expression1175 expect(result.success).to.be.true;1176 if (createMode === 'Fungible') {1177 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1178 } else {1179 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1180 }1181 expect(collectionId).to.be.equal(result.collectionId);1182 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1183 expect(to).to.be.deep.equal(result.recipient);1184 newItemId = result.itemId;1185 });1186 return newItemId;1187}11881189export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1190 let newItemId = 0;1191 await usingApi(async (api) => {1192 const to = normalizeAccountId(owner);1193 const itemCountBefore = await getLastTokenId(api, collectionId);1194 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11951196 let tx;1197 if (createMode === 'Fungible') {1198 const createData = {fungible: {value: 10}};1199 tx = api.tx.unique.createItem(collectionId, to, createData as any);1200 } else if (createMode === 'ReFungible') {1201 const createData = {refungible: {const_data: [], pieces: 100}};1202 tx = api.tx.unique.createItem(collectionId, to, createData as any);1203 } else {1204 const createData = {nft: {const_data: []}};1205 tx = api.tx.unique.createItem(collectionId, to, createData as any);1206 }12071208 const events = await submitTransactionAsync(sender, tx);1209 const result = getCreateItemResult(events);12101211 const itemCountAfter = await getLastTokenId(api, collectionId);1212 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12131214 // What to expect1215 // tslint:disable-next-line:no-unused-expression1216 expect(result.success).to.be.true;1217 if (createMode === 'Fungible') {1218 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1219 } else {1220 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1221 }1222 expect(collectionId).to.be.equal(result.collectionId);1223 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1224 expect(to).to.be.deep.equal(result.recipient);1225 newItemId = result.itemId;1226 });1227 return newItemId;1228}12291230export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1231 await usingApi(async (api) => {1232 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12331234 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1235 const result = getCreateItemResult(events);12361237 expect(result.success).to.be.false;1238 });1239}12401241export async function setPublicAccessModeExpectSuccess(1242 sender: IKeyringPair, collectionId: number,1243 accessMode: 'Normal' | 'AllowList',1244) {1245 await usingApi(async (api) => {12461247 // Run the transaction1248 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1249 const events = await submitTransactionAsync(sender, tx);1250 const result = getGenericResult(events);12511252 // Get the collection1253 const collection = await queryCollectionExpectSuccess(api, collectionId);12541255 // What to expect1256 // tslint:disable-next-line:no-unused-expression1257 expect(result.success).to.be.true;1258 expect(collection.access.toHuman()).to.be.equal(accessMode);1259 });1260}12611262export async function setPublicAccessModeExpectFail(1263 sender: IKeyringPair, collectionId: number,1264 accessMode: 'Normal' | 'AllowList',1265) {1266 await usingApi(async (api) => {12671268 // Run the transaction1269 const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1270 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1271 const result = getGenericResult(events);12721273 // What to expect1274 // tslint:disable-next-line:no-unused-expression1275 expect(result.success).to.be.false;1276 });1277}12781279export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1280 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1281}12821283export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1284 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1285}12861287export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1288 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1289}12901291export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1292 await usingApi(async (api) => {12931294 // Run the transaction1295 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1296 const events = await submitTransactionAsync(sender, tx);1297 const result = getGenericResult(events);1298 expect(result.success).to.be.true;12991300 // Get the collection1301 const collection = await queryCollectionExpectSuccess(api, collectionId);13021303 expect(collection.mintMode.toHuman()).to.be.equal(enabled);1304 });1305}13061307export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1308 await setMintPermissionExpectSuccess(sender, collectionId, true);1309}13101311export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1312 await usingApi(async (api) => {1313 // Run the transaction1314 const tx = api.tx.unique.setMintPermission(collectionId, enabled);1315 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1316 const result = getCreateCollectionResult(events);1317 // tslint:disable-next-line:no-unused-expression1318 expect(result.success).to.be.false;1319 });1320}13211322export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1323 await usingApi(async (api) => {1324 // Run the transaction1325 const tx = api.tx.unique.setChainLimits(limits);1326 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1327 const result = getCreateCollectionResult(events);1328 // tslint:disable-next-line:no-unused-expression1329 expect(result.success).to.be.false;1330 });1331}13321333export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1334 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1335}13361337export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1338 await usingApi(async (api) => {1339 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13401341 // Run the transaction1342 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1343 const events = await submitTransactionAsync(sender, tx);1344 const result = getGenericResult(events);1345 expect(result.success).to.be.true;13461347 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1348 });1349}13501351export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1352 await usingApi(async (api) => {13531354 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13551356 // Run the transaction1357 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1358 const events = await submitTransactionAsync(sender, tx);1359 const result = getGenericResult(events);1360 expect(result.success).to.be.true;13611362 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1363 });1364}13651366export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1367 await usingApi(async (api) => {13681369 // Run the transaction1370 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1371 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1372 const result = getGenericResult(events);13731374 // What to expect1375 // tslint:disable-next-line:no-unused-expression1376 expect(result.success).to.be.false;1377 });1378}13791380export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1381 await usingApi(async (api) => {1382 // Run the transaction1383 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1384 const events = await submitTransactionAsync(sender, tx);1385 const result = getGenericResult(events);13861387 // What to expect1388 // tslint:disable-next-line:no-unused-expression1389 expect(result.success).to.be.true;1390 });1391}13921393export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1394 await usingApi(async (api) => {1395 // Run the transaction1396 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1397 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1398 const result = getGenericResult(events);13991400 // What to expect1401 // tslint:disable-next-line:no-unused-expression1402 expect(result.success).to.be.false;1403 });1404}14051406export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1407 : Promise<UpDataStructsRpcCollection | null> => {1408 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1409};14101411export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1412 // set global object - collectionsCount1413 return (await api.rpc.unique.collectionStats()).created.toNumber();1414};14151416export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1417 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1418}14191420export async function waitNewBlocks(blocksCount = 1): Promise<void> {1421 await usingApi(async (api) => {1422 const promise = new Promise<void>(async (resolve) => {1423 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1424 if (blocksCount > 0) {1425 blocksCount--;1426 } else {1427 unsubscribe();1428 resolve();1429 }1430 });1431 });1432 return promise;1433 });1434}