difftreelog
test transfer already nested token + destroy a non-empty collection + additional refactoring
in: master
7 files changed
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -54,6 +54,7 @@
"testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
"testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",
"testCreateCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
+ "testDestroyCollection": "mocha --timeout 9999999 -r ts-node/register ./**/destroyCollection.test.ts",
"testToggleContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/toggleContractAllowList.test.ts",
"testAddToContractAllowList": "mocha --timeout 9999999 -r ts-node/register ./**/addToContractAllowList.test.ts",
"testTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/transfer.test.ts",
tests/src/createMultipleItemsEx.test.tsdiffbeforeafterboth--- a/tests/src/createMultipleItemsEx.test.ts
+++ b/tests/src/createMultipleItemsEx.test.ts
@@ -29,13 +29,10 @@
const data = [
{
owner: {substrate: alice.address},
- // constData: '0x0000',
}, {
owner: {substrate: bob.address},
- // constData: '0x2222',
}, {
owner: {substrate: charlie.address},
- // constData: '0x4444',
},
];
@@ -57,15 +54,12 @@
const data = [
{
owner: {substrate: alice.address},
- // 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'}],
},
];
@@ -88,15 +82,12 @@
const data = [
{
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'}],
},
];
@@ -119,15 +110,12 @@
const data = [
{
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'}],
},
];
@@ -272,13 +260,10 @@
const data = [
{
owner: {substrate: alice.address},
- // constData: '0x0000',
}, {
owner: {substrate: bob.address},
- // constData: '0x2222',
}, {
owner: {substrate: charlie.address},
- // constData: '0x4444',
},
];
@@ -300,13 +285,10 @@
const data = [
{
owner: {substrate: alice.address},
- // constData: '0x0000',
}, {
owner: {substrate: bob.address},
- // constData: '0x2222',
}, {
owner: {substrate: charlie.address},
- // constData: '0x4444',
},
];
tests/src/destroyCollection.test.tsdiffbeforeafterboth--- a/tests/src/destroyCollection.test.ts
+++ b/tests/src/destroyCollection.test.ts
@@ -25,6 +25,7 @@
setCollectionLimitsExpectSuccess,
addCollectionAdminExpectSuccess,
getCreatedCollectionCount,
+ createItemExpectSuccess,
} from './util/helpers';
chai.use(chaiAsPromised);
@@ -83,4 +84,10 @@
await destroyCollectionExpectFailure(collectionId, '//Alice');
});
+ it('fails when a collection still has a token', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await createItemExpectSuccess(alice, collectionId, 'NFT');
+
+ await destroyCollectionExpectFailure(collectionId, '//Alice');
+ });
});
tests/src/nesting/migration-check.test.tsdiffbeforeafterboth--- a/tests/src/nesting/migration-check.test.ts
+++ b/tests/src/nesting/migration-check.test.ts
@@ -31,12 +31,12 @@
name: strToUTF16('Mojave Pictures'),
description: strToUTF16('$2.2 billion power plant!'),
tokenPrefix: '0x0002030',
- offchainSchema: '0x111111',
- schemaVersion: 'Unique',
+ //offchainSchema: '0x111111',
+ //schemaVersion: 'Unique',
limits: {
accountTokenOwnershipLimit: 3,
},
- constOnChainSchema: '0x333333',
+ //constOnChainSchema: '0x333333',
});
const events = await submitTransactionAsync(alice, tx);
const result = getCreateCollectionResult(events);
@@ -96,17 +96,17 @@
const collectionNew = (await api.query.common.collectionById(collectionId)).toJSON() as any;
// Make sure the extra fields are what they should be
- const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');
- const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');
+ //const constOnChainSchema = await api.query.common.collectionData(collectionId, 'ConstOnChainSchema');
+ //const offchainSchema = await api.query.common.collectionData(collectionId, 'OffchainSchema');
- expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);
- expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);
+ //expect(constOnChainSchema.toHex()).to.be.deep.equal(collectionOld.constOnChainSchema);
+ //expect(offchainSchema.toHex()).to.be.deep.equal(collectionOld.offchainSchema);
expect(collectionNew).to.have.nested.property('limits.nestingRule');
// Get rid of extra fields to perform comparison on the rest of the collection
delete collectionNew.limits.nestingRule;
- delete collectionOld.constOnChainSchema;
- delete collectionOld.offchainSchema;
+ //delete collectionOld.constOnChainSchema;
+ //delete collectionOld.offchainSchema;
expect(collectionNew).to.be.deep.equal(collectionOld);
});
tests/src/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/nesting/nest.test.ts
+++ b/tests/src/nesting/nest.test.ts
@@ -10,6 +10,7 @@
enablePublicMintingExpectSuccess,
getTokenOwner,
getTopmostTokenOwner,
+ normalizeAccountId,
setCollectionPermissionsExpectSuccess,
transferExpectFailure,
transferExpectSuccess,
@@ -28,7 +29,7 @@
});
});
- it('Performs the full suite: bundles a token, transfers, and allows to unnest', async () => {
+ it('Performs the full suite: bundles a token, transfers, and unnests', async () => {
await usingApi(async api => {
const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: 'Owner'});
@@ -58,6 +59,33 @@
});
});
+ it('Transfers an already bundled token', async () => {
+ await usingApi(async api => {
+ const collection = await createCollectionExpectSuccess({mode: {type: 'NFT'}});
+ await setCollectionPermissionsExpectSuccess(alice, collection, {nesting: 'Owner'});
+
+ const tokenA = await createItemExpectSuccess(alice, collection, 'NFT');
+ const tokenB = await createItemExpectSuccess(alice, collection, 'NFT');
+
+ // Create a nested token
+ const tokenC = await createItemExpectSuccess(alice, collection, 'NFT', {Ethereum: tokenIdToAddress(collection, tokenA)});
+ expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
+ expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenA).toLowerCase()});
+
+ // Transfer the nested token to another token
+ await expect(executeTransaction(
+ api,
+ alice,
+ api.tx.unique.transferFrom(
+ normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenA)}),
+ normalizeAccountId({Ethereum: tokenIdToAddress(collection, tokenB)}),
+ collection, tokenC, 1),
+ )).to.not.be.rejected;
+ expect(await getTopmostTokenOwner(api, collection, tokenC)).to.be.deep.equal({Substrate: alice.address});
+ expect(await getTokenOwner(api, collection, tokenC)).to.be.deep.equal({Ethereum: tokenIdToAddress(collection, tokenB).toLowerCase()});
+ });
+ });
+
// ---------- Non-Fungible ----------
it('NFT: allows an Owner to nest/unnest their token', async () => {
tests/src/setChainLimits.test.tsdiffbeforeafterboth--- a/tests/src/setChainLimits.test.ts
+++ b/tests/src/setChainLimits.test.ts
@@ -43,8 +43,6 @@
nftSponsorTransferTimeout: 1,
fungibleSponsorTransferTimeout: 1,
refungibleSponsorTransferTimeout: 1,
- offchainSchemaLimit: 1,
- constOnChainSchemaLimit: 1,
};
});
});
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, UpDataStructsCreateItemData, UpDataStructsProperty} 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}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147 let checkMsgUnqMethod = '';148 let checkMsgTrsMethod = '';149 let checkMsgSysMethod = '';150 events.forEach(({event: {method, section}}) => {151 if (section === 'common') {152 checkMsgUnqMethod = method;153 } else if (section === 'treasury') {154 checkMsgTrsMethod = method;155 } else if (section === 'system') {156 checkMsgSysMethod = method;157 } else { return null; }158 });159 const result: IGetMessage = {160 checkMsgUnqMethod,161 checkMsgTrsMethod,162 checkMsgSysMethod,163 };164 return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168 const event = events.find(r => check(r.event));169 if (!event) return;170 return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174 const result: GenericResult = {175 success: false,176 };177 events.forEach(({event: {method}}) => {178 // console.log(` ${phase}: ${section}.${method}:: ${data}`);179 if (method === 'ExtrinsicSuccess') {180 result.success = true;181 }182 });183 return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189 let success = false;190 let collectionId = 0;191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method == 'ExtrinsicSuccess') {194 success = true;195 } else if ((section == 'common') && (method == 'CollectionCreated')) {196 collectionId = parseInt(data[0].toString(), 10);197 }198 });199 const result: CreateCollectionResult = {200 success,201 collectionId,202 };203 return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207 let success = false;208 let collectionId = 0;209 let itemId = 0;210 let recipient;211212 const results : CreateItemResult[] = [];213214 events.forEach(({event: {data, method, section}}) => {215 // console.log(` ${phase}: ${section}.${method}:: ${data}`);216 if (method == 'ExtrinsicSuccess') {217 success = true;218 } else if ((section == 'common') && (method == 'ItemCreated')) {219 collectionId = parseInt(data[0].toString(), 10);220 itemId = parseInt(data[1].toString(), 10);221 recipient = normalizeAccountId(data[2].toJSON() as any);222223 const itemRes: CreateItemResult = {224 success,225 collectionId,226 itemId,227 recipient,228 };229230 results.push(itemRes);231 }232 });233234 return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238 let success = false;239 let collectionId = 0;240 let itemId = 0;241 let recipient;242 events.forEach(({event: {data, method, section}}) => {243 // console.log(` ${phase}: ${section}.${method}:: ${data}`);244 if (method == 'ExtrinsicSuccess') {245 success = true;246 } else if ((section == 'common') && (method == 'ItemCreated')) {247 collectionId = parseInt(data[0].toString(), 10);248 itemId = parseInt(data[1].toString(), 10);249 recipient = normalizeAccountId(data[2].toJSON() as any);250 }251 });252 const result: CreateItemResult = {253 success,254 collectionId,255 itemId,256 recipient,257 };258 return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262 for (const {event} of events) {263 if (api.events.common.Transfer.is(event)) {264 const [collection, token, sender, recipient, value] = event.data;265 return {266 collectionId: collection.toNumber(),267 itemId: token.toNumber(),268 sender: normalizeAccountId(sender.toJSON() as any),269 recipient: normalizeAccountId(recipient.toJSON() as any),270 value: value.toBigInt(),271 };272 }273 }274 throw new Error('no transfer event');275}276277interface Nft {278 type: 'NFT';279}280281interface Fungible {282 type: 'Fungible';283 decimalPoints: number;284}285286interface ReFungible {287 type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293 key: any,294 value: any,295};296297type Permission = {298 mutable: boolean;299 collectionAdmin: boolean;300 tokenOwner: boolean;301}302303type PropertyPermission = {304 key: any;305 permission: Permission;306}307308export type CreateCollectionParams = {309 mode: CollectionMode,310 name: string,311 description: string,312 tokenPrefix: string,313 schemaVersion: string,314 properties?: Array<Property>,315 propPerm?: Array<PropertyPermission>316};317318const defaultCreateCollectionParams: CreateCollectionParams = {319 description: 'description',320 mode: {type: 'NFT'},321 name: 'name',322 tokenPrefix: 'prefix',323 schemaVersion: 'ImageURL',324};325326export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {327 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};328329 let collectionId = 0;330 await usingApi(async (api) => {331 // Get number of collections before the transaction332 const collectionCountBefore = await getCreatedCollectionCount(api);333334 // Run the CreateCollection transaction335 const alicePrivateKey = privateKey('//Alice');336337 let modeprm = {};338 if (mode.type === 'NFT') {339 modeprm = {nft: null};340 } else if (mode.type === 'Fungible') {341 modeprm = {fungible: mode.decimalPoints};342 } else if (mode.type === 'ReFungible') {343 modeprm = {refungible: null};344 }345346 const tx = api.tx.unique.createCollectionEx({347 name: strToUTF16(name),348 description: strToUTF16(description),349 tokenPrefix: strToUTF16(tokenPrefix),350 mode: modeprm as any,351 });352 const events = await submitTransactionAsync(alicePrivateKey, tx);353 const result = getCreateCollectionResult(events);354355 // Get number of collections after the transaction356 const collectionCountAfter = await getCreatedCollectionCount(api);357358 // Get the collection359 const collection = await queryCollectionExpectSuccess(api, result.collectionId);360361 // What to expect362 // tslint:disable-next-line:no-unused-expression363 expect(result.success).to.be.true;364 expect(result.collectionId).to.be.equal(collectionCountAfter);365 // tslint:disable-next-line:no-unused-expression366 expect(collection).to.be.not.null;367 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');368 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));369 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);370 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);371 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);372373 collectionId = result.collectionId;374 });375376 return collectionId;377}378379export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {380 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};381382 let collectionId = 0;383 await usingApi(async (api) => {384 // Get number of collections before the transaction385 const collectionCountBefore = await getCreatedCollectionCount(api);386387 // Run the CreateCollection transaction388 const alicePrivateKey = privateKey('//Alice');389390 let modeprm = {};391 if (mode.type === 'NFT') {392 modeprm = {nft: null};393 } else if (mode.type === 'Fungible') {394 modeprm = {fungible: mode.decimalPoints};395 } else if (mode.type === 'ReFungible') {396 modeprm = {refungible: null};397 }398399 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});400 const events = await submitTransactionAsync(alicePrivateKey, tx);401 const result = getCreateCollectionResult(events);402403 // Get number of collections after the transaction404 const collectionCountAfter = await getCreatedCollectionCount(api);405406 // Get the collection407 const collection = await queryCollectionExpectSuccess(api, result.collectionId);408409 // What to expect410 // tslint:disable-next-line:no-unused-expression411 expect(result.success).to.be.true;412 expect(result.collectionId).to.be.equal(collectionCountAfter);413 // tslint:disable-next-line:no-unused-expression414 expect(collection).to.be.not.null;415 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');416 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));417 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);418 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);419 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);420421422 collectionId = result.collectionId;423 });424425 return collectionId;426}427428export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {429 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};430431 await usingApi(async (api) => {432 // Get number of collections before the transaction433 const collectionCountBefore = await getCreatedCollectionCount(api);434435 // Run the CreateCollection transaction436 const alicePrivateKey = privateKey('//Alice');437438 let modeprm = {};439 if (mode.type === 'NFT') {440 modeprm = {nft: null};441 } else if (mode.type === 'Fungible') {442 modeprm = {fungible: mode.decimalPoints};443 } else if (mode.type === 'ReFungible') {444 modeprm = {refungible: null};445 }446447 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});448 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449450451 // Get number of collections after the transaction452 const collectionCountAfter = await getCreatedCollectionCount(api);453454 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');455 });456}457458export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {459 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};460461 let modeprm = {};462 if (mode.type === 'NFT') {463 modeprm = {nft: null};464 } else if (mode.type === 'Fungible') {465 modeprm = {fungible: mode.decimalPoints};466 } else if (mode.type === 'ReFungible') {467 modeprm = {refungible: null};468 }469470 await usingApi(async (api) => {471 // Get number of collections before the transaction472 const collectionCountBefore = await getCreatedCollectionCount(api);473474 // Run the CreateCollection transaction475 const alicePrivateKey = privateKey('//Alice');476 const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});477 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;478479 // Get number of collections after the transaction480 const collectionCountAfter = await getCreatedCollectionCount(api);481482 // What to expect483 expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');484 });485}486487export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {488 let bal = 0n;489 let unused;490 do {491 const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;492 const keyring = new Keyring({type: 'sr25519'});493 unused = keyring.addFromUri(`//${randomSeed}`);494 bal = (await api.query.system.account(unused.address)).data.free.toBigInt();495 } while (bal !== 0n);496 return unused;497}498499export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {500 return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();501}502503export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {504 return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));505}506507export async function findNotExistingCollection(api: ApiPromise): Promise<number> {508 const totalNumber = await getCreatedCollectionCount(api);509 const newCollection: number = totalNumber + 1;510 return newCollection;511}512513function getDestroyResult(events: EventRecord[]): boolean {514 let success = false;515 events.forEach(({event: {method}}) => {516 if (method == 'ExtrinsicSuccess') {517 success = true;518 }519 });520 return success;521}522523export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {524 await usingApi(async (api) => {525 // Run the DestroyCollection transaction526 const alicePrivateKey = privateKey(senderSeed);527 const tx = api.tx.unique.destroyCollection(collectionId);528 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;529 });530}531532export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {533 await usingApi(async (api) => {534 // Run the DestroyCollection transaction535 const alicePrivateKey = privateKey(senderSeed);536 const tx = api.tx.unique.destroyCollection(collectionId);537 const events = await submitTransactionAsync(alicePrivateKey, tx);538 const result = getDestroyResult(events);539 expect(result).to.be.true;540541 // What to expect542 expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;543 });544}545546export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {547 await usingApi(async (api) => {548 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);549 const events = await submitTransactionAsync(sender, tx);550 const result = getGenericResult(events);551552 expect(result.success).to.be.true;553 });554}555556export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {557 await usingApi(async(api) => {558 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);559 const events = await submitTransactionAsync(sender, tx);560 const result = getGenericResult(events);561562 expect(result.success).to.be.true;563 });564};565566export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {567 await usingApi(async (api) => {568 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);569 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;570 const result = getGenericResult(events);571572 expect(result.success).to.be.false;573 });574}575576export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {577 await usingApi(async (api) => {578579 // Run the transaction580 const senderPrivateKey = privateKey(sender);581 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);582 const events = await submitTransactionAsync(senderPrivateKey, tx);583 const result = getGenericResult(events);584585 // Get the collection586 const collection = await queryCollectionExpectSuccess(api, collectionId);587588 // What to expect589 expect(result.success).to.be.true;590 expect(collection.sponsorship.toJSON()).to.deep.equal({591 unconfirmed: sponsor,592 });593 });594}595596export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {597 await usingApi(async (api) => {598599 // Run the transaction600 const alicePrivateKey = privateKey(sender);601 const tx = api.tx.unique.removeCollectionSponsor(collectionId);602 const events = await submitTransactionAsync(alicePrivateKey, tx);603 const result = getGenericResult(events);604605 // Get the collection606 const collection = await queryCollectionExpectSuccess(api, collectionId);607608 // What to expect609 expect(result.success).to.be.true;610 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});611 });612}613614export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {615 await usingApi(async (api) => {616617 // Run the transaction618 const alicePrivateKey = privateKey(senderSeed);619 const tx = api.tx.unique.removeCollectionSponsor(collectionId);620 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;621 });622}623624export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {625 await usingApi(async (api) => {626627 // Run the transaction628 const alicePrivateKey = privateKey(senderSeed);629 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);630 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;631 });632}633634export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {635 await usingApi(async (api) => {636637 // Run the transaction638 const sender = privateKey(senderSeed);639 const tx = api.tx.unique.confirmSponsorship(collectionId);640 const events = await submitTransactionAsync(sender, tx);641 const result = getGenericResult(events);642643 // Get the collection644 const collection = await queryCollectionExpectSuccess(api, collectionId);645646 // What to expect647 expect(result.success).to.be.true;648 expect(collection.sponsorship.toJSON()).to.be.deep.equal({649 confirmed: sender.address,650 });651 });652}653654655export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {656 await usingApi(async (api) => {657658 // Run the transaction659 const sender = privateKey(senderSeed);660 const tx = api.tx.unique.confirmSponsorship(collectionId);661 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662 });663}664665export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {666 await usingApi(async (api) => {667 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);668 const events = await submitTransactionAsync(sender, tx);669 const result = getGenericResult(events);670671 expect(result.success).to.be.true;672 });673}674675export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {676 await usingApi(async (api) => {677 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);678 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679 const result = getGenericResult(events);680681 expect(result.success).to.be.false;682 });683}684685export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {686687 await usingApi(async (api) => {688689 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);690 const events = await submitTransactionAsync(sender, tx);691 const result = getGenericResult(events);692693 expect(result.success).to.be.true;694 });695}696697export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {698699 await usingApi(async (api) => {700701 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);702 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;703 const result = getGenericResult(events);704705 expect(result.success).to.be.false;706 });707}708709export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {710 await usingApi(async (api) => {711 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);712 const events = await submitTransactionAsync(sender, tx);713 const result = getGenericResult(events);714715 expect(result.success).to.be.true;716 });717}718719export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {720 await usingApi(async (api) => {721 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);722 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;723 const result = getGenericResult(events);724725 expect(result.success).to.be.false;726 });727}728729export async function getNextSponsored(730 api: ApiPromise,731 collectionId: number,732 account: string | CrossAccountId,733 tokenId: number,734): Promise<number> {735 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));736}737738export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {739 await usingApi(async (api) => {740 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);741 const events = await submitTransactionAsync(sender, tx);742 const result = getGenericResult(events);743744 expect(result.success).to.be.true;745 });746}747748export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {749 let allowlisted = false;750 await usingApi(async (api) => {751 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;752 });753 return allowlisted;754}755756export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {757 await usingApi(async (api) => {758 const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());759 const events = await submitTransactionAsync(sender, tx);760 const result = getGenericResult(events);761762 expect(result.success).to.be.true;763 });764}765766export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {767 await usingApi(async (api) => {768 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());769 const events = await submitTransactionAsync(sender, tx);770 const result = getGenericResult(events);771772 expect(result.success).to.be.true;773 });774}775776export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {777 await usingApi(async (api) => {778 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());779 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;780 const result = getGenericResult(events);781782 expect(result.success).to.be.false;783 });784}785786/*export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {787 await usingApi(async (api) => {788 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));789 const events = await submitTransactionAsync(sender, tx);790 const result = getGenericResult(events);791792 expect(result.success).to.be.true;793 });794}795796export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {797 await usingApi(async (api) => {798 const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));799 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;800 });801}*/802803export interface CreateFungibleData {804 readonly Value: bigint;805}806807export interface CreateReFungibleData { }808export interface CreateNftData { }809810export type CreateItemData = {811 NFT: CreateNftData;812} | {813 Fungible: CreateFungibleData;814} | {815 ReFungible: CreateReFungibleData;816};817818export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {819 await usingApi(async (api) => {820 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);821 // if burning token by admin - use adminButnItemExpectSuccess822 expect(balanceBefore >= BigInt(value)).to.be.true;823824 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);825 const events = await submitTransactionAsync(sender, tx);826 const result = getGenericResult(events);827 expect(result.success).to.be.true;828829 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);830 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);831 });832}833834export async function835approveExpectSuccess(836 collectionId: number,837 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,838) {839 await usingApi(async (api: ApiPromise) => {840 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);841 const events = await submitTransactionAsync(owner, approveUniqueTx);842 const result = getGenericResult(events);843 expect(result.success).to.be.true;844845 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));846 });847}848849export async function adminApproveFromExpectSuccess(850 collectionId: number,851 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,852) {853 await usingApi(async (api: ApiPromise) => {854 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);855 const events = await submitTransactionAsync(admin, approveUniqueTx);856 const result = getGenericResult(events);857 expect(result.success).to.be.true;858859 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));860 });861}862863export async function864transferFromExpectSuccess(865 collectionId: number,866 tokenId: number,867 accountApproved: IKeyringPair,868 accountFrom: IKeyringPair | CrossAccountId,869 accountTo: IKeyringPair | CrossAccountId,870 value: number | bigint = 1,871 type = 'NFT',872) {873 await usingApi(async (api: ApiPromise) => {874 const from = normalizeAccountId(accountFrom);875 const to = normalizeAccountId(accountTo);876 let balanceBefore = 0n;877 if (type === 'Fungible' || type === 'ReFungible') {878 balanceBefore = await getBalance(api, collectionId, to, tokenId);879 }880 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);881 const events = await submitTransactionAsync(accountApproved, transferFromTx);882 const result = getCreateItemResult(events);883 // tslint:disable-next-line:no-unused-expression884 expect(result.success).to.be.true;885 if (type === 'NFT') {886 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);887 }888 if (type === 'Fungible') {889 const balanceAfter = await getBalance(api, collectionId, to, tokenId);890 if (JSON.stringify(to) !== JSON.stringify(from)) {891 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));892 } else {893 expect(balanceAfter).to.be.equal(balanceBefore);894 }895 }896 if (type === 'ReFungible') {897 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));898 }899 });900}901902export async function903transferFromExpectFail(904 collectionId: number,905 tokenId: number,906 accountApproved: IKeyringPair,907 accountFrom: IKeyringPair,908 accountTo: IKeyringPair,909 value: number | bigint = 1,910) {911 await usingApi(async (api: ApiPromise) => {912 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);913 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;914 const result = getCreateCollectionResult(events);915 // tslint:disable-next-line:no-unused-expression916 expect(result.success).to.be.false;917 });918}919920/* eslint no-async-promise-executor: "off" */921async function getBlockNumber(api: ApiPromise): Promise<number> {922 return new Promise<number>(async (resolve) => {923 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {924 unsubscribe();925 resolve(head.number.toNumber());926 });927 });928}929930export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {931 await usingApi(async (api) => {932 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));933 const events = await submitTransactionAsync(sender, changeAdminTx);934 const result = getCreateCollectionResult(events);935 expect(result.success).to.be.true;936 });937}938939export async function940getFreeBalance(account: IKeyringPair): Promise<bigint> {941 let balance = 0n;942 await usingApi(async (api) => {943 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());944 });945946 return balance;947}948949export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {950 const tx = api.tx.balances.transfer(target, amount);951 const events = await submitTransactionAsync(source, tx);952 const result = getGenericResult(events);953 expect(result.success).to.be.true;954}955956export async function957scheduleTransferExpectSuccess(958 collectionId: number,959 tokenId: number,960 sender: IKeyringPair,961 recipient: IKeyringPair,962 value: number | bigint = 1,963 blockSchedule: number,964) {965 await usingApi(async (api: ApiPromise) => {966 const blockNumber: number | undefined = await getBlockNumber(api);967 const expectedBlockNumber = blockNumber + blockSchedule;968969 expect(blockNumber).to.be.greaterThan(0);970 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);971 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);972973 await submitTransactionAsync(sender, scheduleTx);974975 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();976977 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));978979 // sleep for 4 blocks980 await waitNewBlocks(blockSchedule + 1);981982 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();983984 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));985 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);986 });987}988989990export async function991transferExpectSuccess(992 collectionId: number,993 tokenId: number,994 sender: IKeyringPair,995 recipient: IKeyringPair | CrossAccountId,996 value: number | bigint = 1,997 type = 'NFT',998) {999 await usingApi(async (api: ApiPromise) => {1000 const from = normalizeAccountId(sender);1001 const to = normalizeAccountId(recipient);10021003 let balanceBefore = 0n;1004 if (type === 'Fungible') {1005 balanceBefore = await getBalance(api, collectionId, to, tokenId);1006 }1007 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);1008 const events = await executeTransaction(api, sender, transferTx);10091010 const result = getTransferResult(api, events);1011 expect(result.collectionId).to.be.equal(collectionId);1012 expect(result.itemId).to.be.equal(tokenId);1013 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));1014 expect(result.recipient).to.be.deep.equal(to);1015 expect(result.value).to.be.equal(BigInt(value));10161017 if (type === 'NFT') {1018 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1019 }1020 if (type === 'Fungible') {1021 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1022 if (JSON.stringify(to) !== JSON.stringify(from)) {1023 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1024 } else {1025 expect(balanceAfter).to.be.equal(balanceBefore);1026 }1027 }1028 if (type === 'ReFungible') {1029 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1030 }1031 });1032}10331034export async function1035transferExpectFailure(1036 collectionId: number,1037 tokenId: number,1038 sender: IKeyringPair,1039 recipient: IKeyringPair | CrossAccountId,1040 value: number | bigint = 1,1041) {1042 await usingApi(async (api: ApiPromise) => {1043 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1044 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1045 const result = getGenericResult(events);1046 // if (events && Array.isArray(events)) {1047 // const result = getCreateCollectionResult(events);1048 // tslint:disable-next-line:no-unused-expression1049 expect(result.success).to.be.false;1050 //}1051 });1052}10531054export async function1055approveExpectFail(1056 collectionId: number,1057 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1058) {1059 await usingApi(async (api: ApiPromise) => {1060 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1061 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1062 const result = getCreateCollectionResult(events);1063 // tslint:disable-next-line:no-unused-expression1064 expect(result.success).to.be.false;1065 });1066}10671068export async function getBalance(1069 api: ApiPromise,1070 collectionId: number,1071 owner: string | CrossAccountId,1072 token: number,1073): Promise<bigint> {1074 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1075}1076export async function getTokenOwner(1077 api: ApiPromise,1078 collectionId: number,1079 token: number,1080): Promise<CrossAccountId> {1081 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1082 if (owner == null) throw new Error('owner == null');1083 return normalizeAccountId(owner);1084}1085export async function getTopmostTokenOwner(1086 api: ApiPromise,1087 collectionId: number,1088 token: number,1089): Promise<CrossAccountId> {1090 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1091 if (owner == null) throw new Error('owner == null');1092 return normalizeAccountId(owner);1093}1094export async function isTokenExists(1095 api: ApiPromise,1096 collectionId: number,1097 token: number,1098): Promise<boolean> {1099 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1100}1101export async function getLastTokenId(1102 api: ApiPromise,1103 collectionId: number,1104): Promise<number> {1105 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1106}1107export async function getAdminList(1108 api: ApiPromise,1109 collectionId: number,1110): Promise<string[]> {1111 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1112}1113/*export async function getConstMetadata(1114 api: ApiPromise,1115 collectionId: number,1116 tokenId: number,1117): Promise<number[]> {1118 return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1119}*/1120export async function getTokenProperties(1121 api: ApiPromise,1122 collectionId: number,1123 tokenId: number,1124 propertyKeys: string[],1125): Promise<UpDataStructsProperty[]> {1126 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1127}11281129export async function createFungibleItemExpectSuccess(1130 sender: IKeyringPair,1131 collectionId: number,1132 data: CreateFungibleData,1133 owner: CrossAccountId | string = sender.address,1134) {1135 return await usingApi(async (api) => {1136 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11371138 const events = await submitTransactionAsync(sender, tx);1139 const result = getCreateItemResult(events);11401141 expect(result.success).to.be.true;1142 return result.itemId;1143 });1144}11451146export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1147 await usingApi(async (api) => {1148 const to = normalizeAccountId(owner);1149 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11501151 const events = await submitTransactionAsync(sender, tx);1152 const result = getCreateItemsResult(events);11531154 for (const res of result) {1155 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1156 }1157 });1158}11591160export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1161 await usingApi(async (api) => {1162 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11631164 const events = await submitTransactionAsync(sender, tx);1165 const result = getCreateItemsResult(events);11661167 for (const res of result) {1168 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1169 }1170 });1171}11721173export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1174 let newItemId = 0;1175 await usingApi(async (api) => {1176 const to = normalizeAccountId(owner);1177 const itemCountBefore = await getLastTokenId(api, collectionId);1178 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11791180 let tx;1181 if (createMode === 'Fungible') {1182 const createData = {fungible: {value: 10}};1183 tx = api.tx.unique.createItem(collectionId, to, createData as any);1184 } else if (createMode === 'ReFungible') {1185 const createData = {refungible: {pieces: 100}};1186 tx = api.tx.unique.createItem(collectionId, to, createData as any);1187 } else {1188 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1189 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1190 }11911192 const events = await submitTransactionAsync(sender, tx);1193 const result = getCreateItemResult(events);11941195 const itemCountAfter = await getLastTokenId(api, collectionId);1196 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11971198 if (createMode === 'NFT') {1199 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1200 }12011202 // What to expect1203 // tslint:disable-next-line:no-unused-expression1204 expect(result.success).to.be.true;1205 if (createMode === 'Fungible') {1206 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1207 } else {1208 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1209 }1210 expect(collectionId).to.be.equal(result.collectionId);1211 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1212 expect(to).to.be.deep.equal(result.recipient);1213 newItemId = result.itemId;1214 });1215 return newItemId;1216}12171218export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1219 await usingApi(async (api) => {12201221 let tx;1222 if (createMode === 'NFT') {1223 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1224 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1225 } else {1226 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1227 }122812291230 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1231 if(events.message && events.message.contains('1002: Verification Error')) return;1232 const result = getCreateItemResult(events);12331234 expect(result.success).to.be.false;1235 });1236}12371238export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1239 let newItemId = 0;1240 await usingApi(async (api) => {1241 const to = normalizeAccountId(owner);1242 const itemCountBefore = await getLastTokenId(api, collectionId);1243 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12441245 let tx;1246 if (createMode === 'Fungible') {1247 const createData = {fungible: {value: 10}};1248 tx = api.tx.unique.createItem(collectionId, to, createData as any);1249 } else if (createMode === 'ReFungible') {1250 const createData = {refungible: {pieces: 100}};1251 tx = api.tx.unique.createItem(collectionId, to, createData as any);1252 } else {1253 const createData = {nft: {}};1254 tx = api.tx.unique.createItem(collectionId, to, createData as any);1255 }12561257 const events = await submitTransactionAsync(sender, tx);1258 const result = getCreateItemResult(events);12591260 const itemCountAfter = await getLastTokenId(api, collectionId);1261 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12621263 // What to expect1264 // tslint:disable-next-line:no-unused-expression1265 expect(result.success).to.be.true;1266 if (createMode === 'Fungible') {1267 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1268 } else {1269 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1270 }1271 expect(collectionId).to.be.equal(result.collectionId);1272 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1273 expect(to).to.be.deep.equal(result.recipient);1274 newItemId = result.itemId;1275 });1276 return newItemId;1277}12781279export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1280 await usingApi(async (api) => {1281 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12821283 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1284 const result = getCreateItemResult(events);12851286 expect(result.success).to.be.false;1287 });1288}12891290export async function setPublicAccessModeExpectSuccess(1291 sender: IKeyringPair, collectionId: number,1292 accessMode: 'Normal' | 'AllowList',1293) {1294 await usingApi(async (api) => {12951296 // Run the transaction1297 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1298 const events = await submitTransactionAsync(sender, tx);1299 const result = getGenericResult(events);13001301 // Get the collection1302 const collection = await queryCollectionExpectSuccess(api, collectionId);13031304 // What to expect1305 // tslint:disable-next-line:no-unused-expression1306 expect(result.success).to.be.true;1307 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1308 });1309}13101311export async function setPublicAccessModeExpectFail(1312 sender: IKeyringPair, collectionId: number,1313 accessMode: 'Normal' | 'AllowList',1314) {1315 await usingApi(async (api) => {13161317 // Run the transaction1318 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1319 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1320 const result = getGenericResult(events);13211322 // What to expect1323 // tslint:disable-next-line:no-unused-expression1324 expect(result.success).to.be.false;1325 });1326}13271328export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1329 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1330}13311332export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1333 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1334}13351336export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1337 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1338}13391340export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1341 await usingApi(async (api) => {13421343 // Run the transaction1344 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1345 const events = await submitTransactionAsync(sender, tx);1346 const result = getGenericResult(events);1347 expect(result.success).to.be.true;13481349 // Get the collection1350 const collection = await queryCollectionExpectSuccess(api, collectionId);13511352 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1353 });1354}13551356export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1357 await setMintPermissionExpectSuccess(sender, collectionId, true);1358}13591360export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1361 await usingApi(async (api) => {1362 // Run the transaction1363 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1364 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1365 const result = getCreateCollectionResult(events);1366 // tslint:disable-next-line:no-unused-expression1367 expect(result.success).to.be.false;1368 });1369}13701371export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1372 await usingApi(async (api) => {1373 // Run the transaction1374 const tx = api.tx.unique.setChainLimits(limits);1375 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1376 const result = getCreateCollectionResult(events);1377 // tslint:disable-next-line:no-unused-expression1378 expect(result.success).to.be.false;1379 });1380}13811382export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1383 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1384}13851386export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1387 await usingApi(async (api) => {1388 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13891390 // Run the transaction1391 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1392 const events = await submitTransactionAsync(sender, tx);1393 const result = getGenericResult(events);1394 expect(result.success).to.be.true;13951396 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1397 });1398}13991400export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1401 await usingApi(async (api) => {14021403 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;14041405 // Run the transaction1406 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1407 const events = await submitTransactionAsync(sender, tx);1408 const result = getGenericResult(events);1409 expect(result.success).to.be.true;14101411 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1412 });1413}14141415export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1416 await usingApi(async (api) => {14171418 // Run the transaction1419 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1420 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1421 const result = getGenericResult(events);14221423 // What to expect1424 // tslint:disable-next-line:no-unused-expression1425 expect(result.success).to.be.false;1426 });1427}14281429export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1430 await usingApi(async (api) => {1431 // Run the transaction1432 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1433 const events = await submitTransactionAsync(sender, tx);1434 const result = getGenericResult(events);14351436 // What to expect1437 // tslint:disable-next-line:no-unused-expression1438 expect(result.success).to.be.true;1439 });1440}14411442export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1443 await usingApi(async (api) => {1444 // Run the transaction1445 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1446 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1447 const result = getGenericResult(events);14481449 // What to expect1450 // tslint:disable-next-line:no-unused-expression1451 expect(result.success).to.be.false;1452 });1453}14541455export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1456 : Promise<UpDataStructsRpcCollection | null> => {1457 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1458};14591460export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1461 // set global object - collectionsCount1462 return (await api.rpc.unique.collectionStats()).created.toNumber();1463};14641465export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1466 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1467}14681469export async function waitNewBlocks(blocksCount = 1): Promise<void> {1470 await usingApi(async (api) => {1471 const promise = new Promise<void>(async (resolve) => {1472 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1473 if (blocksCount > 0) {1474 blocksCount--;1475 } else {1476 unsubscribe();1477 resolve();1478 }1479 });1480 });1481 return promise;1482 });1483}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, UpDataStructsProperty} 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}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147 let checkMsgUnqMethod = '';148 let checkMsgTrsMethod = '';149 let checkMsgSysMethod = '';150 events.forEach(({event: {method, section}}) => {151 if (section === 'common') {152 checkMsgUnqMethod = method;153 } else if (section === 'treasury') {154 checkMsgTrsMethod = method;155 } else if (section === 'system') {156 checkMsgSysMethod = method;157 } else { return null; }158 });159 const result: IGetMessage = {160 checkMsgUnqMethod,161 checkMsgTrsMethod,162 checkMsgSysMethod,163 };164 return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168 const event = events.find(r => check(r.event));169 if (!event) return;170 return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174 const result: GenericResult = {175 success: false,176 };177 events.forEach(({event: {method}}) => {178 // console.log(` ${phase}: ${section}.${method}:: ${data}`);179 if (method === 'ExtrinsicSuccess') {180 result.success = true;181 }182 });183 return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189 let success = false;190 let collectionId = 0;191 events.forEach(({event: {data, method, section}}) => {192 // console.log(` ${phase}: ${section}.${method}:: ${data}`);193 if (method == 'ExtrinsicSuccess') {194 success = true;195 } else if ((section == 'common') && (method == 'CollectionCreated')) {196 collectionId = parseInt(data[0].toString(), 10);197 }198 });199 const result: CreateCollectionResult = {200 success,201 collectionId,202 };203 return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207 let success = false;208 let collectionId = 0;209 let itemId = 0;210 let recipient;211212 const results : CreateItemResult[] = [];213214 events.forEach(({event: {data, method, section}}) => {215 // console.log(` ${phase}: ${section}.${method}:: ${data}`);216 if (method == 'ExtrinsicSuccess') {217 success = true;218 } else if ((section == 'common') && (method == 'ItemCreated')) {219 collectionId = parseInt(data[0].toString(), 10);220 itemId = parseInt(data[1].toString(), 10);221 recipient = normalizeAccountId(data[2].toJSON() as any);222223 const itemRes: CreateItemResult = {224 success,225 collectionId,226 itemId,227 recipient,228 };229230 results.push(itemRes);231 }232 });233234 return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238 let success = false;239 let collectionId = 0;240 let itemId = 0;241 let recipient;242 events.forEach(({event: {data, method, section}}) => {243 // console.log(` ${phase}: ${section}.${method}:: ${data}`);244 if (method == 'ExtrinsicSuccess') {245 success = true;246 } else if ((section == 'common') && (method == 'ItemCreated')) {247 collectionId = parseInt(data[0].toString(), 10);248 itemId = parseInt(data[1].toString(), 10);249 recipient = normalizeAccountId(data[2].toJSON() as any);250 }251 });252 const result: CreateItemResult = {253 success,254 collectionId,255 itemId,256 recipient,257 };258 return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262 for (const {event} of events) {263 if (api.events.common.Transfer.is(event)) {264 const [collection, token, sender, recipient, value] = event.data;265 return {266 collectionId: collection.toNumber(),267 itemId: token.toNumber(),268 sender: normalizeAccountId(sender.toJSON() as any),269 recipient: normalizeAccountId(recipient.toJSON() as any),270 value: value.toBigInt(),271 };272 }273 }274 throw new Error('no transfer event');275}276277interface Nft {278 type: 'NFT';279}280281interface Fungible {282 type: 'Fungible';283 decimalPoints: number;284}285286interface ReFungible {287 type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293 key: any,294 value: any,295};296297type Permission = {298 mutable: boolean;299 collectionAdmin: boolean;300 tokenOwner: boolean;301}302303type PropertyPermission = {304 key: any;305 permission: Permission;306}307308export type CreateCollectionParams = {309 mode: CollectionMode,310 name: string,311 description: string,312 tokenPrefix: string,313 properties?: Array<Property>,314 propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318 description: 'description',319 mode: {type: 'NFT'},320 name: 'name',321 tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327 let collectionId = 0;328 await usingApi(async (api) => {329 // Get number of collections before the transaction330 const collectionCountBefore = await getCreatedCollectionCount(api);331332 // Run the CreateCollection transaction333 const alicePrivateKey = privateKey('//Alice');334335 let modeprm = {};336 if (mode.type === 'NFT') {337 modeprm = {nft: null};338 } else if (mode.type === 'Fungible') {339 modeprm = {fungible: mode.decimalPoints};340 } else if (mode.type === 'ReFungible') {341 modeprm = {refungible: null};342 }343344 const tx = api.tx.unique.createCollectionEx({345 name: strToUTF16(name),346 description: strToUTF16(description),347 tokenPrefix: strToUTF16(tokenPrefix),348 mode: modeprm as any,349 });350 const events = await submitTransactionAsync(alicePrivateKey, tx);351 const result = getCreateCollectionResult(events);352353 // Get number of collections after the transaction354 const collectionCountAfter = await getCreatedCollectionCount(api);355356 // Get the collection357 const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359 // What to expect360 // tslint:disable-next-line:no-unused-expression361 expect(result.success).to.be.true;362 expect(result.collectionId).to.be.equal(collectionCountAfter);363 // tslint:disable-next-line:no-unused-expression364 expect(collection).to.be.not.null;365 expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366 expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367 expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368 expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369 expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371 collectionId = result.collectionId;372 });373374 return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378 const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380 let collectionId = 0;381 await usingApi(async (api) => {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 const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555 await usingApi(async(api) => {556 const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557 const events = await submitTransactionAsync(sender, tx);558 const result = getGenericResult(events);559560 expect(result.success).to.be.true;561 });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565 await usingApi(async (api) => {566 const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568 const result = getGenericResult(events);569570 expect(result.success).to.be.false;571 });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575 await usingApi(async (api) => {576577 // Run the transaction578 const senderPrivateKey = privateKey(sender);579 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580 const events = await submitTransactionAsync(senderPrivateKey, tx);581 const result = getGenericResult(events);582583 // Get the collection584 const collection = await queryCollectionExpectSuccess(api, collectionId);585586 // What to expect587 expect(result.success).to.be.true;588 expect(collection.sponsorship.toJSON()).to.deep.equal({589 unconfirmed: sponsor,590 });591 });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595 await usingApi(async (api) => {596597 // Run the transaction598 const alicePrivateKey = privateKey(sender);599 const tx = api.tx.unique.removeCollectionSponsor(collectionId);600 const events = await submitTransactionAsync(alicePrivateKey, tx);601 const result = getGenericResult(events);602603 // Get the collection604 const collection = await queryCollectionExpectSuccess(api, collectionId);605606 // What to expect607 expect(result.success).to.be.true;608 expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609 });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613 await usingApi(async (api) => {614615 // Run the transaction616 const alicePrivateKey = privateKey(senderSeed);617 const tx = api.tx.unique.removeCollectionSponsor(collectionId);618 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619 });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623 await usingApi(async (api) => {624625 // Run the transaction626 const alicePrivateKey = privateKey(senderSeed);627 const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628 await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629 });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633 await usingApi(async (api) => {634635 // Run the transaction636 const sender = privateKey(senderSeed);637 const tx = api.tx.unique.confirmSponsorship(collectionId);638 const events = await submitTransactionAsync(sender, tx);639 const result = getGenericResult(events);640641 // Get the collection642 const collection = await queryCollectionExpectSuccess(api, collectionId);643644 // What to expect645 expect(result.success).to.be.true;646 expect(collection.sponsorship.toJSON()).to.be.deep.equal({647 confirmed: sender.address,648 });649 });650}651652653export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {654 await usingApi(async (api) => {655656 // Run the transaction657 const sender = privateKey(senderSeed);658 const tx = api.tx.unique.confirmSponsorship(collectionId);659 await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;660 });661}662663export async function enableContractSponsoringExpectSuccess(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 submitTransactionAsync(sender, tx);667 const result = getGenericResult(events);668669 expect(result.success).to.be.true;670 });671}672673export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {674 await usingApi(async (api) => {675 const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);676 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677 const result = getGenericResult(events);678679 expect(result.success).to.be.false;680 });681}682683export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {684685 await usingApi(async (api) => {686687 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);688 const events = await submitTransactionAsync(sender, tx);689 const result = getGenericResult(events);690691 expect(result.success).to.be.true;692 });693}694695export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {696697 await usingApi(async (api) => {698699 const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);700 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;701 const result = getGenericResult(events);702703 expect(result.success).to.be.false;704 });705}706707export async function setContractSponsoringRateLimitExpectSuccess(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 submitTransactionAsync(sender, tx);711 const result = getGenericResult(events);712713 expect(result.success).to.be.true;714 });715}716717export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {718 await usingApi(async (api) => {719 const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);720 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;721 const result = getGenericResult(events);722723 expect(result.success).to.be.false;724 });725}726727export async function getNextSponsored(728 api: ApiPromise,729 collectionId: number,730 account: string | CrossAccountId,731 tokenId: number,732): Promise<number> {733 return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));734}735736export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {737 await usingApi(async (api) => {738 const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);739 const events = await submitTransactionAsync(sender, tx);740 const result = getGenericResult(events);741742 expect(result.success).to.be.true;743 });744}745746export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {747 let allowlisted = false;748 await usingApi(async (api) => {749 allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;750 });751 return allowlisted;752}753754export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {755 await usingApi(async (api) => {756 const tx = api.tx.unique.addToContractAllowList(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 removeFromContractAllowListExpectSuccess(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 submitTransactionAsync(sender, tx);768 const result = getGenericResult(events);769770 expect(result.success).to.be.true;771 });772}773774export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {775 await usingApi(async (api) => {776 const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());777 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778 const result = getGenericResult(events);779780 expect(result.success).to.be.false;781 });782}783784export interface CreateFungibleData {785 readonly Value: bigint;786}787788export interface CreateReFungibleData { }789export interface CreateNftData { }790791export type CreateItemData = {792 NFT: CreateNftData;793} | {794 Fungible: CreateFungibleData;795} | {796 ReFungible: CreateReFungibleData;797};798799export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {800 await usingApi(async (api) => {801 const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);802 // if burning token by admin - use adminButnItemExpectSuccess803 expect(balanceBefore >= BigInt(value)).to.be.true;804805 const tx = api.tx.unique.burnItem(collectionId, tokenId, value);806 const events = await submitTransactionAsync(sender, tx);807 const result = getGenericResult(events);808 expect(result.success).to.be.true;809810 const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);811 expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);812 });813}814815export async function816approveExpectSuccess(817 collectionId: number,818 tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,819) {820 await usingApi(async (api: ApiPromise) => {821 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);822 const events = await submitTransactionAsync(owner, approveUniqueTx);823 const result = getGenericResult(events);824 expect(result.success).to.be.true;825826 expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));827 });828}829830export async function adminApproveFromExpectSuccess(831 collectionId: number,832 tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,833) {834 await usingApi(async (api: ApiPromise) => {835 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);836 const events = await submitTransactionAsync(admin, approveUniqueTx);837 const result = getGenericResult(events);838 expect(result.success).to.be.true;839840 expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));841 });842}843844export async function845transferFromExpectSuccess(846 collectionId: number,847 tokenId: number,848 accountApproved: IKeyringPair,849 accountFrom: IKeyringPair | CrossAccountId,850 accountTo: IKeyringPair | CrossAccountId,851 value: number | bigint = 1,852 type = 'NFT',853) {854 await usingApi(async (api: ApiPromise) => {855 const from = normalizeAccountId(accountFrom);856 const to = normalizeAccountId(accountTo);857 let balanceBefore = 0n;858 if (type === 'Fungible' || type === 'ReFungible') {859 balanceBefore = await getBalance(api, collectionId, to, tokenId);860 }861 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);862 const events = await submitTransactionAsync(accountApproved, transferFromTx);863 const result = getCreateItemResult(events);864 // tslint:disable-next-line:no-unused-expression865 expect(result.success).to.be.true;866 if (type === 'NFT') {867 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);868 }869 if (type === 'Fungible') {870 const balanceAfter = await getBalance(api, collectionId, to, tokenId);871 if (JSON.stringify(to) !== JSON.stringify(from)) {872 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));873 } else {874 expect(balanceAfter).to.be.equal(balanceBefore);875 }876 }877 if (type === 'ReFungible') {878 expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));879 }880 });881}882883export async function884transferFromExpectFail(885 collectionId: number,886 tokenId: number,887 accountApproved: IKeyringPair,888 accountFrom: IKeyringPair,889 accountTo: IKeyringPair,890 value: number | bigint = 1,891) {892 await usingApi(async (api: ApiPromise) => {893 const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);894 const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;895 const result = getCreateCollectionResult(events);896 // tslint:disable-next-line:no-unused-expression897 expect(result.success).to.be.false;898 });899}900901/* eslint no-async-promise-executor: "off" */902async function getBlockNumber(api: ApiPromise): Promise<number> {903 return new Promise<number>(async (resolve) => {904 const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {905 unsubscribe();906 resolve(head.number.toNumber());907 });908 });909}910911export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {912 await usingApi(async (api) => {913 const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));914 const events = await submitTransactionAsync(sender, changeAdminTx);915 const result = getCreateCollectionResult(events);916 expect(result.success).to.be.true;917 });918}919920export async function921getFreeBalance(account: IKeyringPair): Promise<bigint> {922 let balance = 0n;923 await usingApi(async (api) => {924 balance = BigInt((await api.query.system.account(account.address)).data.free.toString());925 });926927 return balance;928}929930export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {931 const tx = api.tx.balances.transfer(target, amount);932 const events = await submitTransactionAsync(source, tx);933 const result = getGenericResult(events);934 expect(result.success).to.be.true;935}936937export async function938scheduleTransferExpectSuccess(939 collectionId: number,940 tokenId: number,941 sender: IKeyringPair,942 recipient: IKeyringPair,943 value: number | bigint = 1,944 blockSchedule: number,945) {946 await usingApi(async (api: ApiPromise) => {947 const blockNumber: number | undefined = await getBlockNumber(api);948 const expectedBlockNumber = blockNumber + blockSchedule;949950 expect(blockNumber).to.be.greaterThan(0);951 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);952 const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);953954 await submitTransactionAsync(sender, scheduleTx);955956 const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();957958 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));959960 // sleep for 4 blocks961 await waitNewBlocks(blockSchedule + 1);962963 const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();964965 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));966 expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);967 });968}969970971export async function972transferExpectSuccess(973 collectionId: number,974 tokenId: number,975 sender: IKeyringPair,976 recipient: IKeyringPair | CrossAccountId,977 value: number | bigint = 1,978 type = 'NFT',979) {980 await usingApi(async (api: ApiPromise) => {981 const from = normalizeAccountId(sender);982 const to = normalizeAccountId(recipient);983984 let balanceBefore = 0n;985 if (type === 'Fungible') {986 balanceBefore = await getBalance(api, collectionId, to, tokenId);987 }988 const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);989 const events = await executeTransaction(api, sender, transferTx);990991 const result = getTransferResult(api, events);992 expect(result.collectionId).to.be.equal(collectionId);993 expect(result.itemId).to.be.equal(tokenId);994 expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));995 expect(result.recipient).to.be.deep.equal(to);996 expect(result.value).to.be.equal(BigInt(value));997998 if (type === 'NFT') {999 expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1000 }1001 if (type === 'Fungible') {1002 const balanceAfter = await getBalance(api, collectionId, to, tokenId);1003 if (JSON.stringify(to) !== JSON.stringify(from)) {1004 expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1005 } else {1006 expect(balanceAfter).to.be.equal(balanceBefore);1007 }1008 }1009 if (type === 'ReFungible') {1010 expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1011 }1012 });1013}10141015export async function1016transferExpectFailure(1017 collectionId: number,1018 tokenId: number,1019 sender: IKeyringPair,1020 recipient: IKeyringPair | CrossAccountId,1021 value: number | bigint = 1,1022) {1023 await usingApi(async (api: ApiPromise) => {1024 const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1025 const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1026 const result = getGenericResult(events);1027 // if (events && Array.isArray(events)) {1028 // const result = getCreateCollectionResult(events);1029 // tslint:disable-next-line:no-unused-expression1030 expect(result.success).to.be.false;1031 //}1032 });1033}10341035export async function1036approveExpectFail(1037 collectionId: number,1038 tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1039) {1040 await usingApi(async (api: ApiPromise) => {1041 const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1042 const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1043 const result = getCreateCollectionResult(events);1044 // tslint:disable-next-line:no-unused-expression1045 expect(result.success).to.be.false;1046 });1047}10481049export async function getBalance(1050 api: ApiPromise,1051 collectionId: number,1052 owner: string | CrossAccountId,1053 token: number,1054): Promise<bigint> {1055 return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1056}1057export async function getTokenOwner(1058 api: ApiPromise,1059 collectionId: number,1060 token: number,1061): Promise<CrossAccountId> {1062 const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1063 if (owner == null) throw new Error('owner == null');1064 return normalizeAccountId(owner);1065}1066export async function getTopmostTokenOwner(1067 api: ApiPromise,1068 collectionId: number,1069 token: number,1070): Promise<CrossAccountId> {1071 const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1072 if (owner == null) throw new Error('owner == null');1073 return normalizeAccountId(owner);1074}1075export async function isTokenExists(1076 api: ApiPromise,1077 collectionId: number,1078 token: number,1079): Promise<boolean> {1080 return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1081}1082export async function getLastTokenId(1083 api: ApiPromise,1084 collectionId: number,1085): Promise<number> {1086 return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1087}1088export async function getAdminList(1089 api: ApiPromise,1090 collectionId: number,1091): Promise<string[]> {1092 return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1093}1094export async function getTokenProperties(1095 api: ApiPromise,1096 collectionId: number,1097 tokenId: number,1098 propertyKeys: string[],1099): Promise<UpDataStructsProperty[]> {1100 return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1101}11021103export async function createFungibleItemExpectSuccess(1104 sender: IKeyringPair,1105 collectionId: number,1106 data: CreateFungibleData,1107 owner: CrossAccountId | string = sender.address,1108) {1109 return await usingApi(async (api) => {1110 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11111112 const events = await submitTransactionAsync(sender, tx);1113 const result = getCreateItemResult(events);11141115 expect(result.success).to.be.true;1116 return result.itemId;1117 });1118}11191120export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1121 await usingApi(async (api) => {1122 const to = normalizeAccountId(owner);1123 const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11241125 const events = await submitTransactionAsync(sender, tx);1126 const result = getCreateItemsResult(events);11271128 for (const res of result) {1129 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1130 }1131 });1132}11331134export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1135 await usingApi(async (api) => {1136 const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11371138 const events = await submitTransactionAsync(sender, tx);1139 const result = getCreateItemsResult(events);11401141 for (const res of result) {1142 expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1143 }1144 });1145}11461147export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1148 let newItemId = 0;1149 await usingApi(async (api) => {1150 const to = normalizeAccountId(owner);1151 const itemCountBefore = await getLastTokenId(api, collectionId);1152 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11531154 let tx;1155 if (createMode === 'Fungible') {1156 const createData = {fungible: {value: 10}};1157 tx = api.tx.unique.createItem(collectionId, to, createData as any);1158 } else if (createMode === 'ReFungible') {1159 const createData = {refungible: {pieces: 100}};1160 tx = api.tx.unique.createItem(collectionId, to, createData as any);1161 } else {1162 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1163 tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1164 }11651166 const events = await submitTransactionAsync(sender, tx);1167 const result = getCreateItemResult(events);11681169 const itemCountAfter = await getLastTokenId(api, collectionId);1170 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11711172 if (createMode === 'NFT') {1173 expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1174 }11751176 // What to expect1177 // tslint:disable-next-line:no-unused-expression1178 expect(result.success).to.be.true;1179 if (createMode === 'Fungible') {1180 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1181 } else {1182 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1183 }1184 expect(collectionId).to.be.equal(result.collectionId);1185 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1186 expect(to).to.be.deep.equal(result.recipient);1187 newItemId = result.itemId;1188 });1189 return newItemId;1190}11911192export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1193 await usingApi(async (api) => {11941195 let tx;1196 if (createMode === 'NFT') {1197 const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1198 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1199 } else {1200 tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1201 }120212031204 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1205 if(events.message && events.message.contains('1002: Verification Error')) return;1206 const result = getCreateItemResult(events);12071208 expect(result.success).to.be.false;1209 });1210}12111212export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1213 let newItemId = 0;1214 await usingApi(async (api) => {1215 const to = normalizeAccountId(owner);1216 const itemCountBefore = await getLastTokenId(api, collectionId);1217 const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12181219 let tx;1220 if (createMode === 'Fungible') {1221 const createData = {fungible: {value: 10}};1222 tx = api.tx.unique.createItem(collectionId, to, createData as any);1223 } else if (createMode === 'ReFungible') {1224 const createData = {refungible: {pieces: 100}};1225 tx = api.tx.unique.createItem(collectionId, to, createData as any);1226 } else {1227 const createData = {nft: {}};1228 tx = api.tx.unique.createItem(collectionId, to, createData as any);1229 }12301231 const events = await submitTransactionAsync(sender, tx);1232 const result = getCreateItemResult(events);12331234 const itemCountAfter = await getLastTokenId(api, collectionId);1235 const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12361237 // What to expect1238 // tslint:disable-next-line:no-unused-expression1239 expect(result.success).to.be.true;1240 if (createMode === 'Fungible') {1241 expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1242 } else {1243 expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1244 }1245 expect(collectionId).to.be.equal(result.collectionId);1246 expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1247 expect(to).to.be.deep.equal(result.recipient);1248 newItemId = result.itemId;1249 });1250 return newItemId;1251}12521253export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1254 await usingApi(async (api) => {1255 const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12561257 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1258 const result = getCreateItemResult(events);12591260 expect(result.success).to.be.false;1261 });1262}12631264export async function setPublicAccessModeExpectSuccess(1265 sender: IKeyringPair, collectionId: number,1266 accessMode: 'Normal' | 'AllowList',1267) {1268 await usingApi(async (api) => {12691270 // Run the transaction1271 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1272 const events = await submitTransactionAsync(sender, tx);1273 const result = getGenericResult(events);12741275 // Get the collection1276 const collection = await queryCollectionExpectSuccess(api, collectionId);12771278 // What to expect1279 // tslint:disable-next-line:no-unused-expression1280 expect(result.success).to.be.true;1281 expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1282 });1283}12841285export async function setPublicAccessModeExpectFail(1286 sender: IKeyringPair, collectionId: number,1287 accessMode: 'Normal' | 'AllowList',1288) {1289 await usingApi(async (api) => {12901291 // Run the transaction1292 const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1293 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1294 const result = getGenericResult(events);12951296 // What to expect1297 // tslint:disable-next-line:no-unused-expression1298 expect(result.success).to.be.false;1299 });1300}13011302export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1303 await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1304}13051306export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1307 await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1308}13091310export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1311 await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1312}13131314export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1315 await usingApi(async (api) => {13161317 // Run the transaction1318 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1319 const events = await submitTransactionAsync(sender, tx);1320 const result = getGenericResult(events);1321 expect(result.success).to.be.true;13221323 // Get the collection1324 const collection = await queryCollectionExpectSuccess(api, collectionId);13251326 expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1327 });1328}13291330export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1331 await setMintPermissionExpectSuccess(sender, collectionId, true);1332}13331334export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1335 await usingApi(async (api) => {1336 // Run the transaction1337 const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1338 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1339 const result = getCreateCollectionResult(events);1340 // tslint:disable-next-line:no-unused-expression1341 expect(result.success).to.be.false;1342 });1343}13441345export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1346 await usingApi(async (api) => {1347 // Run the transaction1348 const tx = api.tx.unique.setChainLimits(limits);1349 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1350 const result = getCreateCollectionResult(events);1351 // tslint:disable-next-line:no-unused-expression1352 expect(result.success).to.be.false;1353 });1354}13551356export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1357 return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1358}13591360export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1361 await usingApi(async (api) => {1362 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13631364 // Run the transaction1365 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1366 const events = await submitTransactionAsync(sender, tx);1367 const result = getGenericResult(events);1368 expect(result.success).to.be.true;13691370 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1371 });1372}13731374export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1375 await usingApi(async (api) => {13761377 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13781379 // Run the transaction1380 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1381 const events = await submitTransactionAsync(sender, tx);1382 const result = getGenericResult(events);1383 expect(result.success).to.be.true;13841385 expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1386 });1387}13881389export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1390 await usingApi(async (api) => {13911392 // Run the transaction1393 const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1394 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395 const result = getGenericResult(events);13961397 // What to expect1398 // tslint:disable-next-line:no-unused-expression1399 expect(result.success).to.be.false;1400 });1401}14021403export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1404 await usingApi(async (api) => {1405 // Run the transaction1406 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1407 const events = await submitTransactionAsync(sender, tx);1408 const result = getGenericResult(events);14091410 // What to expect1411 // tslint:disable-next-line:no-unused-expression1412 expect(result.success).to.be.true;1413 });1414}14151416export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1417 await usingApi(async (api) => {1418 // Run the transaction1419 const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1420 const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1421 const result = getGenericResult(events);14221423 // What to expect1424 // tslint:disable-next-line:no-unused-expression1425 expect(result.success).to.be.false;1426 });1427}14281429export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1430 : Promise<UpDataStructsRpcCollection | null> => {1431 return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1432};14331434export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1435 // set global object - collectionsCount1436 return (await api.rpc.unique.collectionStats()).created.toNumber();1437};14381439export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1440 return (await api.rpc.unique.collectionById(collectionId)).unwrap();1441}14421443export async function waitNewBlocks(blocksCount = 1): Promise<void> {1444 await usingApi(async (api) => {1445 const promise = new Promise<void>(async (resolve) => {1446 const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1447 if (blocksCount > 0) {1448 blocksCount--;1449 } else {1450 unsubscribe();1451 resolve();1452 }1453 });1454 });1455 return promise;1456 });1457}