git.delta.rocks / unique-network / refs/commits / dcb255f64332

difftreelog

Merge pull request #103 from usetech-llc/feature/NFTPAR-303_itemCreated_event_recipient

Greg Zaitsev2021-02-17parents: #a09692c #cadb228.patch.diff
in: master
Add recipient field to ItemCreated event

4 files changed

modifieddoc/application_development.mddiffbeforeafterboth
--- a/doc/application_development.md
+++ b/doc/application_development.md
@@ -79,6 +79,7 @@
 ##### Events
 ItemCreated
 ItemId: Identifier of newly created NFT, which is unique within the Collection, so the NFT is uniquely identified with a pair of values: CollectionId and ItemId.
+Recipient: Address, owner of newly created item
 
 #### BurnItem
 
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -495,7 +495,9 @@
         /// * collection_id: Id of the collection where item was created.
         /// 
         /// * item_id: Id of an item. Unique within the collection.
-        ItemCreated(CollectionId, TokenId),
+        ///
+        /// * recipient: Owner of newly created item 
+        ItemCreated(CollectionId, TokenId, AccountId),
 
         /// Collection item was burned.
         /// 
@@ -1635,7 +1637,7 @@
         {
             CreateItemData::NFT(data) => {
                 let item = NftItemType {
-                    owner,
+                    owner: owner.clone(),
                     const_data: data.const_data,
                     variable_data: data.variable_data
                 };
@@ -1660,7 +1662,7 @@
         };
 
         // call event
-        Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id)));
+        Self::deposit_event(RawEvent::ItemCreated(collection_id, <ItemListIndex>::get(collection_id), owner));
 
         Ok(())
     }
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -29,6 +29,7 @@
     "testRemoveFromWhiteList": "mocha --timeout 9999999 -r ts-node/register ./**/removeFromWhiteList.test.ts",
     "testConnection": "mocha --timeout 9999999 -r ts-node/register ./**/connection.test.ts",
     "testCollection": "mocha --timeout 9999999 -r ts-node/register ./**/createCollection.test.ts",
+    "testCreateItem": "mocha --timeout 9999999 -r ts-node/register ./**/createItem.test.ts",
     "testCreateMultipleItems": "mocha --timeout 9999999 -r ts-node/register ./**/createMultipleItems.test.ts",
     "testApprove": "mocha --timeout 9999999 -r ts-node/register ./**/approve.test.ts",
     "testTransferFrom": "mocha --timeout 9999999 -r ts-node/register ./**/transferFrom.test.ts",
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39}4041interface IReFungibleOwner {42  Fraction: BN;43  Owner: number[];44}4546interface ITokenDataType {47  Owner: number[];48  ConstData: number[];49  VariableData: number[];50}5152interface IFungibleTokenDataType {53  Value: BN;54}5556export interface IReFungibleTokenDataType {57  Owner: IReFungibleOwner[];58  ConstData: number[];59  VariableData: number[];60}6162export function getGenericResult(events: EventRecord[]): GenericResult {63  const result: GenericResult = {64    success: false,65  };66  events.forEach(({ phase, event: { data, method, section } }) => {67    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);68    if (method === 'ExtrinsicSuccess') {69      result.success = true;70    }71  });72  return result;73}7475export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {76  let success = false;77  let collectionId: number = 0;78  events.forEach(({ phase, event: { data, method, section } }) => {79    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);80    if (method == 'ExtrinsicSuccess') {81      success = true;82    } else if ((section == 'nft') && (method == 'Created')) {83      collectionId = parseInt(data[0].toString());84    }85  });86  const result: CreateCollectionResult = {87    success,88    collectionId,89  };90  return result;91}9293export function getCreateItemResult(events: EventRecord[]): CreateItemResult {94  let success = false;95  let collectionId: number = 0;96  let itemId: number = 0;97  events.forEach(({ phase, event: { data, method, section } }) => {98    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);99    if (method == 'ExtrinsicSuccess') {100      success = true;101    } else if ((section == 'nft') && (method == 'ItemCreated')) {102      collectionId = parseInt(data[0].toString());103      itemId = parseInt(data[1].toString());104    }105  });106  const result: CreateItemResult = {107    success,108    collectionId,109    itemId,110  };111  return result;112}113114interface Invalid {115  type: 'Invalid';116}117118interface Nft {119  type: 'NFT';120}121122interface Fungible {123  type: 'Fungible';124  decimalPoints: number;125}126127interface ReFungible {128  type: 'ReFungible';129}130131type CollectionMode = Nft | Fungible | ReFungible | Invalid;132133export type CreateCollectionParams = {134  mode: CollectionMode,135  name: string,136  description: string,137  tokenPrefix: string,138};139140const defaultCreateCollectionParams: CreateCollectionParams = {141  description: 'description',142  mode: { type: 'NFT' },143  name: 'name',144  tokenPrefix: 'prefix',145}146147export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {148  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};149150  let collectionId: number = 0;151  await usingApi(async (api) => {152    // Get number of collections before the transaction153    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);154155    // Run the CreateCollection transaction156    const alicePrivateKey = privateKey('//Alice');157158    let modeprm = {};159    if (mode.type === 'NFT') {160      modeprm = {nft: null};161    } else if (mode.type === 'Fungible') {162      modeprm = {fungible: mode.decimalPoints};163    } else if (mode.type === 'ReFungible') {164      modeprm = {refungible: null};165    } else if (mode.type === 'Invalid') {166      modeprm = {invalid: null};167    }168169    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);170    const events = await submitTransactionAsync(alicePrivateKey, tx);171    const result = getCreateCollectionResult(events);172173    // Get number of collections after the transaction174    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);175176    // Get the collection177    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();178179    // What to expect180    // tslint:disable-next-line:no-unused-expression181    expect(result.success).to.be.true;182    expect(result.collectionId).to.be.equal(BcollectionCount);183    // tslint:disable-next-line:no-unused-expression184    expect(collection).to.be.not.null;185    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');186    expect(collection.Owner).to.be.equal(alicesPublicKey);187    expect(utf16ToStr(collection.Name)).to.be.equal(name);188    expect(utf16ToStr(collection.Description)).to.be.equal(description);189    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);190191    collectionId = result.collectionId;192  });193194  return collectionId;195}196197export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {198  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};199200  let modeprm = {};201  if (mode.type === 'NFT') {202    modeprm = {nft: null};203  } else if (mode.type === 'Fungible') {204    modeprm = {fungible: mode.decimalPoints};205  } else if (mode.type === 'ReFungible') {206    modeprm = {refungible: null};207  } else if (mode.type === 'Invalid') {208    modeprm = {invalid: null};209  }210211  await usingApi(async (api) => {212    // Get number of collections before the transaction213    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());214215    // Run the CreateCollection transaction216    const alicePrivateKey = privateKey('//Alice');217    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);218    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;219    const result = getCreateCollectionResult(events);220221    // Get number of collections after the transaction222    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());223224    // What to expect225    // tslint:disable-next-line:no-unused-expression226    expect(result.success).to.be.false;227    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');228  });229}230231export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {232  let bal = new BigNumber(0);233  let unused;234  do {235    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;236    const keyring = new Keyring({ type: 'sr25519' });237    unused = keyring.addFromUri(`//${randomSeed}`);238    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());239  } while (bal.toFixed() != '0');240  return unused;241}242243export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {244  return await usingApi(async (api) => {245    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;246    return BigInt(bn.toString());247  });248}249250export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {251  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));252}253254export async function findNotExistingCollection(api: ApiPromise): Promise<number> {255  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;256  const newCollection: number = totalNumber + 1;257  return newCollection;258}259260function getDestroyResult(events: EventRecord[]): boolean {261  let success: boolean = false;262  events.forEach(({ phase, event: { data, method, section } }) => {263    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);264    if (method == 'ExtrinsicSuccess') {265      success = true;266    }267  });268  return success;269}270271export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {272  await usingApi(async (api) => {273    // Run the DestroyCollection transaction274    const alicePrivateKey = privateKey(senderSeed);275    const tx = api.tx.nft.destroyCollection(collectionId);276    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;277  });278}279280export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {281  await usingApi(async (api) => {282    // Run the DestroyCollection transaction283    const alicePrivateKey = privateKey(senderSeed);284    const tx = api.tx.nft.destroyCollection(collectionId);285    const events = await submitTransactionAsync(alicePrivateKey, tx);286    const result = getDestroyResult(events);287288    // Get the collection289    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();290291    // What to expect292    expect(result).to.be.true;293    expect(collection).to.be.not.null;294    expect(collection.Owner).to.be.equal(nullPublicKey);295  });296}297298export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {299  await usingApi(async (api) => {300301    // Run the transaction302    const alicePrivateKey = privateKey('//Alice');303    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);304    const events = await submitTransactionAsync(alicePrivateKey, tx);305    const result = getGenericResult(events);306307    // Get the collection308    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();309310    // What to expect311    expect(result.success).to.be.true;312    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());313    expect(collection.SponsorConfirmed).to.be.false;314  });315}316317export async function removeCollectionSponsorExpectSuccess(collectionId: number) {318  await usingApi(async (api) => {319320    // Run the transaction321    const alicePrivateKey = privateKey('//Alice');322    const tx = api.tx.nft.removeCollectionSponsor(collectionId);323    const events = await submitTransactionAsync(alicePrivateKey, tx);324    const result = getGenericResult(events);325326    // Get the collection327    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();328329    // What to expect330    expect(result.success).to.be.true;331    expect(collection.Sponsor).to.be.equal(nullPublicKey);332    expect(collection.SponsorConfirmed).to.be.false;333  });334}335336export async function removeCollectionSponsorExpectFailure(collectionId: number) {337  await usingApi(async (api) => {338339    // Run the transaction340    const alicePrivateKey = privateKey('//Alice');341    const tx = api.tx.nft.removeCollectionSponsor(collectionId);342    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;343  });344}345346export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {347  await usingApi(async (api) => {348349    // Run the transaction350    const alicePrivateKey = privateKey(senderSeed);351    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);352    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;353  });354}355356export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {357  await usingApi(async (api) => {358359    // Run the transaction360    const sender = privateKey(senderSeed);361    const tx = api.tx.nft.confirmSponsorship(collectionId);362    const events = await submitTransactionAsync(sender, tx);363    const result = getGenericResult(events);364365    // Get the collection366    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();367368    // What to expect369    expect(result.success).to.be.true;370    expect(collection.Sponsor).to.be.equal(sender.address);371    expect(collection.SponsorConfirmed).to.be.true;372  });373}374375376export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {377  await usingApi(async (api) => {378379    // Run the transaction380    const sender = privateKey(senderSeed);381    const tx = api.tx.nft.confirmSponsorship(collectionId);382    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;383  });384}385386export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {387  await usingApi(async (api) => {388    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);389    const events = await submitTransactionAsync(sender, tx);390    const result = getGenericResult(events);391392    expect(result.success).to.be.true;393  });394}395396export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {397  await usingApi(async (api) => {398    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);399    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;400    const result = getGenericResult(events);401402    expect(result.success).to.be.false;403  });404}405406export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {407  await usingApi(async (api) => {408    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);409    const events = await submitTransactionAsync(sender, tx);410    const result = getGenericResult(events);411412    expect(result.success).to.be.true;413  });414}415416export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {417  await usingApi(async (api) => {418    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);419    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;420    const result = getGenericResult(events);421422    expect(result.success).to.be.false;423  });424}425426export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {427  await usingApi(async (api) => {428    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);429    const events = await submitTransactionAsync(sender, tx);430    const result = getGenericResult(events);431432    expect(result.success).to.be.true;433  });434}435436export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {437  let whitelisted: boolean = false;438  await usingApi(async (api) => {439    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;440  });441  return whitelisted;442}443444export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {445  await usingApi(async (api) => {446    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);447    const events = await submitTransactionAsync(sender, tx);448    const result = getGenericResult(events);449450    expect(result.success).to.be.true;451  });452}453454export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {455  await usingApi(async (api) => {456    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);457    const events = await submitTransactionAsync(sender, tx);458    const result = getGenericResult(events);459460    expect(result.success).to.be.true;461  });462}463464export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {465  await usingApi(async (api) => {466    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);467    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;468    const result = getGenericResult(events);469470    expect(result.success).to.be.false;471  });472}473474export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {475  await usingApi(async (api) => {476    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));477    const events = await submitTransactionAsync(sender, tx);478    const result = getGenericResult(events);479480    expect(result.success).to.be.true;481  });482}483484export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {485  await usingApi(async (api) => {486    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));487    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;488  });489}490491export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {492  await usingApi(async (api) => {493    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));494    const events = await submitTransactionAsync(sender, tx);495    const result = getGenericResult(events);496497    expect(result.success).to.be.true;498  });499}500501export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {502  await usingApi(async (api) => {503    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));504    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;505  });506}507508export interface CreateFungibleData {509  readonly Value: bigint;510}511512export interface CreateReFungibleData { }513export interface CreateNftData { }514515export type CreateItemData = {516  NFT: CreateNftData;517} | {518  Fungible: CreateFungibleData;519} | {520  ReFungible: CreateReFungibleData;521};522523export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);526    const events = await submitTransactionAsync(owner, tx);527    const result = getGenericResult(events);528    // Get the item529    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();530    // What to expect531    // tslint:disable-next-line:no-unused-expression532    expect(result.success).to.be.true;533    // tslint:disable-next-line:no-unused-expression534    expect(item).to.be.not.null;535    expect(item.Owner).to.be.equal(nullPublicKey);536  });537}538539export async function540approveExpectSuccess(collectionId: number,541                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {542  await usingApi(async (api: ApiPromise) => {543    const allowanceBefore =544      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;545    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);546    const events = await submitTransactionAsync(owner, approveNftTx);547    const result = getCreateItemResult(events);548    // tslint:disable-next-line:no-unused-expression549    expect(result.success).to.be.true;550    const allowanceAfter =551      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;552    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());553  });554}555556export async function557transferFromExpectSuccess(collectionId: number,558                          tokenId: number,559                          accountApproved: IKeyringPair,560                          accountFrom: IKeyringPair,561                          accountTo: IKeyringPair,562                          value: number | bigint = 1,563                          type: string = 'NFT') {564  await usingApi(async (api: ApiPromise) => {565    let balanceBefore = new BN(0);566    if (type === 'Fungible') {567      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;568    }569    const transferFromTx = await api.tx.nft.transferFrom(570      accountFrom.address, accountTo.address, collectionId, tokenId, value);571    const events = await submitTransactionAsync(accountApproved, transferFromTx);572    const result = getCreateItemResult(events);573    // tslint:disable-next-line:no-unused-expression574    expect(result.success).to.be.true;575    if (type === 'NFT') {576      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;577      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);578    }579    if (type === 'Fungible') {580      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;581      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());582    }583    if (type === 'ReFungible') {584      const nftItemData =585        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;586      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);587      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);588    }589  });590}591592export async function593transferFromExpectFail(collectionId: number,594                       tokenId: number,595                       accountApproved: IKeyringPair,596                       accountFrom: IKeyringPair,597                       accountTo: IKeyringPair,598                       value: number | bigint = 1) {599  await usingApi(async (api: ApiPromise) => {600    const transferFromTx = await api.tx.nft.transferFrom(601      accountFrom.address, accountTo.address, collectionId, tokenId, value);602    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;603    const result = getCreateCollectionResult(events);604    // tslint:disable-next-line:no-unused-expression605    expect(result.success).to.be.false;606  });607}608609export async function610transferExpectSuccess(collectionId: number,611                      tokenId: number,612                      sender: IKeyringPair,613                      recipient: IKeyringPair,614                      value: number | bigint = 1,615                      type: string = 'NFT') {616  await usingApi(async (api: ApiPromise) => {617    let balanceBefore = new BN(0);618    if (type === 'Fungible') {619      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;620    }621    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);622    const events = await submitTransactionAsync(sender, transferTx);623    const result = getCreateItemResult(events);624    // tslint:disable-next-line:no-unused-expression625    expect(result.success).to.be.true;626    if (type === 'NFT') {627      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;628      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);629    }630    if (type === 'Fungible') {631      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;632      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());633    }634    if (type === 'ReFungible') {635      const nftItemData =636        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;637      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);638      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);639    }640  });641}642643export async function644transferExpectFail(collectionId: number,645                   tokenId: number,646                   sender: IKeyringPair,647                   recipient: IKeyringPair,648                   value: number | bigint = 1,649                   type: string = 'NFT') {650  await usingApi(async (api: ApiPromise) => {651    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);652    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;653    if (events && Array.isArray(events)) {654      const result = getCreateCollectionResult(events);655      // tslint:disable-next-line:no-unused-expression656      expect(result.success).to.be.false;657    }658  });659}660661export async function662approveExpectFail(collectionId: number,663                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {664  await usingApi(async (api: ApiPromise) => {665    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);666    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;667    const result = getCreateCollectionResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.false;670  });671}672673export async function getFungibleBalance(674  collectionId: number,675  owner: string,676) {677  return await usingApi(async (api) => {678    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};679    return BigInt(response.Value);680  });681}682683export async function createFungibleItemExpectSuccess(684  sender: IKeyringPair,685  collectionId: number,686  data: CreateFungibleData,687  owner: string = sender.address,688) {689  return await usingApi(async (api) => {690    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });691692    const events = await submitTransactionAsync(sender, tx);693    const result = getCreateItemResult(events);694695    expect(result.success).to.be.true;696    return result.itemId;697  });698}699700export async function createItemExpectSuccess(701  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {702  let newItemId: number = 0;703  await usingApi(async (api) => {704    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);705    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();706    const AItemBalance = new BigNumber(Aitem.Value);707708    if (owner === '') {709      owner = sender.address;710    }711712    let tx;713    if (createMode === 'Fungible') {714      const createData = {fungible: {value: 10}};715      tx = api.tx.nft.createItem(collectionId, owner, createData);716    } else if (createMode === 'ReFungible') {717      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};718      tx = api.tx.nft.createItem(collectionId, owner, createData);719    } else {720      tx = api.tx.nft.createItem(collectionId, owner, createMode);721    }722    const events = await submitTransactionAsync(sender, tx);723    const result = getCreateItemResult(events);724725    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);726    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();727    const BItemBalance = new BigNumber(Bitem.Value);728729    // What to expect730    // tslint:disable-next-line:no-unused-expression731    expect(result.success).to.be.true;732    if (createMode === 'Fungible') {733      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);734    } else {735      expect(BItemCount).to.be.equal(AItemCount + 1);736    }737    expect(collectionId).to.be.equal(result.collectionId);738    expect(BItemCount).to.be.equal(result.itemId);739    newItemId = result.itemId;740  });741  return newItemId;742}743744export async function createItemExpectFailure(745  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {746  await usingApi(async (api) => {747    const tx = api.tx.nft.createItem(collectionId, owner, createMode);748    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;749    const result = getCreateItemResult(events);750751    expect(result.success).to.be.false;752  });753}754755export async function setPublicAccessModeExpectSuccess(756  sender: IKeyringPair, collectionId: number,757  accessMode: 'Normal' | 'WhiteList',758) {759  await usingApi(async (api) => {760761    // Run the transaction762    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);763    const events = await submitTransactionAsync(sender, tx);764    const result = getGenericResult(events);765766    // Get the collection767    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();768769    // What to expect770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.true;772    expect(collection.Access).to.be.equal(accessMode);773  });774}775776export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {777  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');778}779780export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {781  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');782}783784export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {785  await usingApi(async (api) => {786787    // Run the transaction788    const tx = api.tx.nft.setMintPermission(collectionId, enabled);789    const events = await submitTransactionAsync(sender, tx);790    const result = getGenericResult(events);791792    // Get the collection793    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();794795    // What to expect796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.true;798    expect(collection.MintMode).to.be.equal(enabled);799  });800}801802export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {803  await setMintPermissionExpectSuccess(sender, collectionId, true);804}805806export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {807  await usingApi(async (api) => {808    // Run the transaction809    const tx = api.tx.nft.setMintPermission(collectionId, enabled);810    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;811    const result = getCreateCollectionResult(events);812    // tslint:disable-next-line:no-unused-expression813    expect(result.success).to.be.false;814  });815}816817export async function isWhitelisted(collectionId: number, address: string) {818  let whitelisted: boolean = false;819  await usingApi(async (api) => {820    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;821  });822  return whitelisted;823}824825export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {826  await usingApi(async (api) => {827828    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();829830    // Run the transaction831    const tx = api.tx.nft.addToWhiteList(collectionId, address);832    const events = await submitTransactionAsync(sender, tx);833    const result = getGenericResult(events);834835    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();836837    // What to expect838    // tslint:disable-next-line:no-unused-expression839    expect(result.success).to.be.true;840    // tslint:disable-next-line: no-unused-expression841    expect(whiteListedBefore).to.be.false;842    // tslint:disable-next-line: no-unused-expression843    expect(whiteListedAfter).to.be.true;844  });845}846847export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {848  await usingApi(async (api) => {849    // Run the transaction850    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);851    const events = await submitTransactionAsync(sender, tx);852    const result = getGenericResult(events);853854    // What to expect855    // tslint:disable-next-line:no-unused-expression856    expect(result.success).to.be.true;857  });858}859860export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {861  await usingApi(async (api) => {862    // Run the transaction863    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);864    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;865    const result = getGenericResult(events);866867    // What to expect868    // tslint:disable-next-line:no-unused-expression869    expect(result.success).to.be.false;870  });871}872873export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)874  : Promise<ICollectionInterface | null> => {875  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;876};877878export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {879  // set global object - collectionsCount880  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();881};882883export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {884  return await usingApi(async (api) => {885    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;886  });887}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import { ApiPromise, Keyring } from '@polkadot/api';7import { Enum, Struct } from '@polkadot/types/codec';8import type { AccountId, EventRecord } from '@polkadot/types/interfaces';9import { u128 } from '@polkadot/types/primitive';10import { IKeyringPair } from '@polkadot/types/types';11import { BigNumber } from 'bignumber.js';12import BN from 'bn.js';13import chai from 'chai';14import chaiAsPromised from 'chai-as-promised';15import { alicesPublicKey, nullPublicKey } from '../accounts';16import privateKey from '../substrate/privateKey';17import { default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync } from '../substrate/substrate-api';18import { ICollectionInterface } from '../types';19import { hexToStr, strToUTF16, utf16ToStr } from './util';2021chai.use(chaiAsPromised);22const expect = chai.expect;2324export const U128_MAX = (1n << 128n) - 1n;2526type GenericResult = {27  success: boolean,28};2930interface CreateCollectionResult {31  success: boolean;32  collectionId: number;33}3435interface CreateItemResult {36  success: boolean;37  collectionId: number;38  itemId: number;39  recipient: string;40}4142interface IReFungibleOwner {43  Fraction: BN;44  Owner: number[];45}4647interface ITokenDataType {48  Owner: number[];49  ConstData: number[];50  VariableData: number[];51}5253interface IFungibleTokenDataType {54  Value: BN;55}5657export interface IReFungibleTokenDataType {58  Owner: IReFungibleOwner[];59  ConstData: number[];60  VariableData: number[];61}6263export function getGenericResult(events: EventRecord[]): GenericResult {64  const result: GenericResult = {65    success: false,66  };67  events.forEach(({ phase, event: { data, method, section } }) => {68    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);69    if (method === 'ExtrinsicSuccess') {70      result.success = true;71    }72  });73  return result;74}7576export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {77  let success = false;78  let collectionId: number = 0;79  events.forEach(({ phase, event: { data, method, section } }) => {80    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);81    if (method == 'ExtrinsicSuccess') {82      success = true;83    } else if ((section == 'nft') && (method == 'Created')) {84      collectionId = parseInt(data[0].toString());85    }86  });87  const result: CreateCollectionResult = {88    success,89    collectionId,90  };91  return result;92}9394export function getCreateItemResult(events: EventRecord[]): CreateItemResult {95  let success = false;96  let collectionId: number = 0;97  let itemId: number = 0;98  let recipient: string = '';99  events.forEach(({ phase, event: { data, method, section } }) => {100    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);101    if (method == 'ExtrinsicSuccess') {102      success = true;103    } else if ((section == 'nft') && (method == 'ItemCreated')) {104      collectionId = parseInt(data[0].toString());105      itemId = parseInt(data[1].toString());106      recipient = data[2].toString();107    }108  });109  const result: CreateItemResult = {110    success,111    collectionId,112    itemId,113    recipient,114  };115  return result;116}117118interface Invalid {119  type: 'Invalid';120}121122interface Nft {123  type: 'NFT';124}125126interface Fungible {127  type: 'Fungible';128  decimalPoints: number;129}130131interface ReFungible {132  type: 'ReFungible';133}134135type CollectionMode = Nft | Fungible | ReFungible | Invalid;136137export type CreateCollectionParams = {138  mode: CollectionMode,139  name: string,140  description: string,141  tokenPrefix: string,142};143144const defaultCreateCollectionParams: CreateCollectionParams = {145  description: 'description',146  mode: { type: 'NFT' },147  name: 'name',148  tokenPrefix: 'prefix',149}150151export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {152  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};153154  let collectionId: number = 0;155  await usingApi(async (api) => {156    // Get number of collections before the transaction157    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);158159    // Run the CreateCollection transaction160    const alicePrivateKey = privateKey('//Alice');161162    let modeprm = {};163    if (mode.type === 'NFT') {164      modeprm = {nft: null};165    } else if (mode.type === 'Fungible') {166      modeprm = {fungible: mode.decimalPoints};167    } else if (mode.type === 'ReFungible') {168      modeprm = {refungible: null};169    } else if (mode.type === 'Invalid') {170      modeprm = {invalid: null};171    }172173    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);174    const events = await submitTransactionAsync(alicePrivateKey, tx);175    const result = getCreateCollectionResult(events);176177    // Get number of collections after the transaction178    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);179180    // Get the collection181    const collection: any = (await api.query.nft.collection(result.collectionId)).toJSON();182183    // What to expect184    // tslint:disable-next-line:no-unused-expression185    expect(result.success).to.be.true;186    expect(result.collectionId).to.be.equal(BcollectionCount);187    // tslint:disable-next-line:no-unused-expression188    expect(collection).to.be.not.null;189    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');190    expect(collection.Owner).to.be.equal(alicesPublicKey);191    expect(utf16ToStr(collection.Name)).to.be.equal(name);192    expect(utf16ToStr(collection.Description)).to.be.equal(description);193    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);194195    collectionId = result.collectionId;196  });197198  return collectionId;199}200201export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {202  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};203204  let modeprm = {};205  if (mode.type === 'NFT') {206    modeprm = {nft: null};207  } else if (mode.type === 'Fungible') {208    modeprm = {fungible: mode.decimalPoints};209  } else if (mode.type === 'ReFungible') {210    modeprm = {refungible: null};211  } else if (mode.type === 'Invalid') {212    modeprm = {invalid: null};213  }214215  await usingApi(async (api) => {216    // Get number of collections before the transaction217    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());218219    // Run the CreateCollection transaction220    const alicePrivateKey = privateKey('//Alice');221    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);222    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;223    const result = getCreateCollectionResult(events);224225    // Get number of collections after the transaction226    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());227228    // What to expect229    // tslint:disable-next-line:no-unused-expression230    expect(result.success).to.be.false;231    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');232  });233}234235export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {236  let bal = new BigNumber(0);237  let unused;238  do {239    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;240    const keyring = new Keyring({ type: 'sr25519' });241    unused = keyring.addFromUri(`//${randomSeed}`);242    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());243  } while (bal.toFixed() != '0');244  return unused;245}246247export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {248  return await usingApi(async (api) => {249    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;250    return BigInt(bn.toString());251  });252}253254export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {255  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));256}257258export async function findNotExistingCollection(api: ApiPromise): Promise<number> {259  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;260  const newCollection: number = totalNumber + 1;261  return newCollection;262}263264function getDestroyResult(events: EventRecord[]): boolean {265  let success: boolean = false;266  events.forEach(({ phase, event: { data, method, section } }) => {267    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);268    if (method == 'ExtrinsicSuccess') {269      success = true;270    }271  });272  return success;273}274275export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {276  await usingApi(async (api) => {277    // Run the DestroyCollection transaction278    const alicePrivateKey = privateKey(senderSeed);279    const tx = api.tx.nft.destroyCollection(collectionId);280    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;281  });282}283284export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {285  await usingApi(async (api) => {286    // Run the DestroyCollection transaction287    const alicePrivateKey = privateKey(senderSeed);288    const tx = api.tx.nft.destroyCollection(collectionId);289    const events = await submitTransactionAsync(alicePrivateKey, tx);290    const result = getDestroyResult(events);291292    // Get the collection293    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();294295    // What to expect296    expect(result).to.be.true;297    expect(collection).to.be.not.null;298    expect(collection.Owner).to.be.equal(nullPublicKey);299  });300}301302export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {303  await usingApi(async (api) => {304305    // Run the transaction306    const alicePrivateKey = privateKey('//Alice');307    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);308    const events = await submitTransactionAsync(alicePrivateKey, tx);309    const result = getGenericResult(events);310311    // Get the collection312    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();313314    // What to expect315    expect(result.success).to.be.true;316    expect(collection.Sponsor.toString()).to.be.equal(sponsor.toString());317    expect(collection.SponsorConfirmed).to.be.false;318  });319}320321export async function removeCollectionSponsorExpectSuccess(collectionId: number) {322  await usingApi(async (api) => {323324    // Run the transaction325    const alicePrivateKey = privateKey('//Alice');326    const tx = api.tx.nft.removeCollectionSponsor(collectionId);327    const events = await submitTransactionAsync(alicePrivateKey, tx);328    const result = getGenericResult(events);329330    // Get the collection331    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();332333    // What to expect334    expect(result.success).to.be.true;335    expect(collection.Sponsor).to.be.equal(nullPublicKey);336    expect(collection.SponsorConfirmed).to.be.false;337  });338}339340export async function removeCollectionSponsorExpectFailure(collectionId: number) {341  await usingApi(async (api) => {342343    // Run the transaction344    const alicePrivateKey = privateKey('//Alice');345    const tx = api.tx.nft.removeCollectionSponsor(collectionId);346    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;347  });348}349350export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {351  await usingApi(async (api) => {352353    // Run the transaction354    const alicePrivateKey = privateKey(senderSeed);355    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);356    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;357  });358}359360export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {361  await usingApi(async (api) => {362363    // Run the transaction364    const sender = privateKey(senderSeed);365    const tx = api.tx.nft.confirmSponsorship(collectionId);366    const events = await submitTransactionAsync(sender, tx);367    const result = getGenericResult(events);368369    // Get the collection370    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();371372    // What to expect373    expect(result.success).to.be.true;374    expect(collection.Sponsor).to.be.equal(sender.address);375    expect(collection.SponsorConfirmed).to.be.true;376  });377}378379380export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {381  await usingApi(async (api) => {382383    // Run the transaction384    const sender = privateKey(senderSeed);385    const tx = api.tx.nft.confirmSponsorship(collectionId);386    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;387  });388}389390export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {391  await usingApi(async (api) => {392    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);393    const events = await submitTransactionAsync(sender, tx);394    const result = getGenericResult(events);395396    expect(result.success).to.be.true;397  });398}399400export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {401  await usingApi(async (api) => {402    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);403    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;404    const result = getGenericResult(events);405406    expect(result.success).to.be.false;407  });408}409410export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {411  await usingApi(async (api) => {412    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);413    const events = await submitTransactionAsync(sender, tx);414    const result = getGenericResult(events);415416    expect(result.success).to.be.true;417  });418}419420export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {421  await usingApi(async (api) => {422    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);423    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;424    const result = getGenericResult(events);425426    expect(result.success).to.be.false;427  });428}429430export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {431  await usingApi(async (api) => {432    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);433    const events = await submitTransactionAsync(sender, tx);434    const result = getGenericResult(events);435436    expect(result.success).to.be.true;437  });438}439440export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {441  let whitelisted: boolean = false;442  await usingApi(async (api) => {443    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;444  });445  return whitelisted;446}447448export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {449  await usingApi(async (api) => {450    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);451    const events = await submitTransactionAsync(sender, tx);452    const result = getGenericResult(events);453454    expect(result.success).to.be.true;455  });456}457458export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {459  await usingApi(async (api) => {460    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);461    const events = await submitTransactionAsync(sender, tx);462    const result = getGenericResult(events);463464    expect(result.success).to.be.true;465  });466}467468export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {469  await usingApi(async (api) => {470    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);471    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;472    const result = getGenericResult(events);473474    expect(result.success).to.be.false;475  });476}477478export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {479  await usingApi(async (api) => {480    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    expect(result.success).to.be.true;485  });486}487488export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {489  await usingApi(async (api) => {490    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));491    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;492  });493}494495export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {496  await usingApi(async (api) => {497    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));498    const events = await submitTransactionAsync(sender, tx);499    const result = getGenericResult(events);500501    expect(result.success).to.be.true;502  });503}504505export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {506  await usingApi(async (api) => {507    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));508    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;509  });510}511512export interface CreateFungibleData {513  readonly Value: bigint;514}515516export interface CreateReFungibleData { }517export interface CreateNftData { }518519export type CreateItemData = {520  NFT: CreateNftData;521} | {522  Fungible: CreateFungibleData;523} | {524  ReFungible: CreateReFungibleData;525};526527export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {528  await usingApi(async (api) => {529    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);530    const events = await submitTransactionAsync(owner, tx);531    const result = getGenericResult(events);532    // Get the item533    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();534    // What to expect535    // tslint:disable-next-line:no-unused-expression536    expect(result.success).to.be.true;537    // tslint:disable-next-line:no-unused-expression538    expect(item).to.be.not.null;539    expect(item.Owner).to.be.equal(nullPublicKey);540  });541}542543export async function544approveExpectSuccess(collectionId: number,545                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {546  await usingApi(async (api: ApiPromise) => {547    const allowanceBefore =548      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;549    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);550    const events = await submitTransactionAsync(owner, approveNftTx);551    const result = getCreateItemResult(events);552    // tslint:disable-next-line:no-unused-expression553    expect(result.success).to.be.true;554    const allowanceAfter =555      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;556    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());557  });558}559560export async function561transferFromExpectSuccess(collectionId: number,562                          tokenId: number,563                          accountApproved: IKeyringPair,564                          accountFrom: IKeyringPair,565                          accountTo: IKeyringPair,566                          value: number | bigint = 1,567                          type: string = 'NFT') {568  await usingApi(async (api: ApiPromise) => {569    let balanceBefore = new BN(0);570    if (type === 'Fungible') {571      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;572    }573    const transferFromTx = await api.tx.nft.transferFrom(574      accountFrom.address, accountTo.address, collectionId, tokenId, value);575    const events = await submitTransactionAsync(accountApproved, transferFromTx);576    const result = getCreateItemResult(events);577    // tslint:disable-next-line:no-unused-expression578    expect(result.success).to.be.true;579    if (type === 'NFT') {580      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;581      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);582    }583    if (type === 'Fungible') {584      const balanceAfter = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;585      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());586    }587    if (type === 'ReFungible') {588      const nftItemData =589        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;590      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);591      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);592    }593  });594}595596export async function597transferFromExpectFail(collectionId: number,598                       tokenId: number,599                       accountApproved: IKeyringPair,600                       accountFrom: IKeyringPair,601                       accountTo: IKeyringPair,602                       value: number | bigint = 1) {603  await usingApi(async (api: ApiPromise) => {604    const transferFromTx = await api.tx.nft.transferFrom(605      accountFrom.address, accountTo.address, collectionId, tokenId, value);606    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;607    const result = getCreateCollectionResult(events);608    // tslint:disable-next-line:no-unused-expression609    expect(result.success).to.be.false;610  });611}612613export async function614transferExpectSuccess(collectionId: number,615                      tokenId: number,616                      sender: IKeyringPair,617                      recipient: IKeyringPair,618                      value: number | bigint = 1,619                      type: string = 'NFT') {620  await usingApi(async (api: ApiPromise) => {621    let balanceBefore = new BN(0);622    if (type === 'Fungible') {623      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;624    }625    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);626    const events = await submitTransactionAsync(sender, transferTx);627    const result = getCreateItemResult(events);628    // tslint:disable-next-line:no-unused-expression629    expect(result.success).to.be.true;630    if (type === 'NFT') {631      const nftItemData = await api.query.nft.nftItemList(collectionId, tokenId) as unknown as ITokenDataType;632      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);633    }634    if (type === 'Fungible') {635      const balanceAfter = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;636      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());637    }638    if (type === 'ReFungible') {639      const nftItemData =640        await api.query.nft.reFungibleItemList(collectionId, tokenId) as unknown as IReFungibleTokenDataType;641      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);642      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);643    }644  });645}646647export async function648transferExpectFail(collectionId: number,649                   tokenId: number,650                   sender: IKeyringPair,651                   recipient: IKeyringPair,652                   value: number | bigint = 1,653                   type: string = 'NFT') {654  await usingApi(async (api: ApiPromise) => {655    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);656    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;657    if (events && Array.isArray(events)) {658      const result = getCreateCollectionResult(events);659      // tslint:disable-next-line:no-unused-expression660      expect(result.success).to.be.false;661    }662  });663}664665export async function666approveExpectFail(collectionId: number,667                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {668  await usingApi(async (api: ApiPromise) => {669    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);670    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;671    const result = getCreateCollectionResult(events);672    // tslint:disable-next-line:no-unused-expression673    expect(result.success).to.be.false;674  });675}676677export async function getFungibleBalance(678  collectionId: number,679  owner: string,680) {681  return await usingApi(async (api) => {682    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};683    return BigInt(response.Value);684  });685}686687export async function createFungibleItemExpectSuccess(688  sender: IKeyringPair,689  collectionId: number,690  data: CreateFungibleData,691  owner: string = sender.address,692) {693  return await usingApi(async (api) => {694    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });695696    const events = await submitTransactionAsync(sender, tx);697    const result = getCreateItemResult(events);698699    expect(result.success).to.be.true;700    return result.itemId;701  });702}703704export async function createItemExpectSuccess(705  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {706  let newItemId: number = 0;707  await usingApi(async (api) => {708    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);709    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();710    const AItemBalance = new BigNumber(Aitem.Value);711712    if (owner === '') {713      owner = sender.address;714    }715716    let tx;717    if (createMode === 'Fungible') {718      const createData = {fungible: {value: 10}};719      tx = api.tx.nft.createItem(collectionId, owner, createData);720    } else if (createMode === 'ReFungible') {721      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};722      tx = api.tx.nft.createItem(collectionId, owner, createData);723    } else {724      tx = api.tx.nft.createItem(collectionId, owner, createMode);725    }726    const events = await submitTransactionAsync(sender, tx);727    const result = getCreateItemResult(events);728729    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);730    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();731    const BItemBalance = new BigNumber(Bitem.Value);732733    // What to expect734    // tslint:disable-next-line:no-unused-expression735    expect(result.success).to.be.true;736    if (createMode === 'Fungible') {737      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);738    } else {739      expect(BItemCount).to.be.equal(AItemCount + 1);740    }741    expect(collectionId).to.be.equal(result.collectionId);742    expect(BItemCount).to.be.equal(result.itemId);743    expect(owner).to.be.equal(result.recipient);744    newItemId = result.itemId;745  });746  return newItemId;747}748749export async function createItemExpectFailure(750  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {751  await usingApi(async (api) => {752    const tx = api.tx.nft.createItem(collectionId, owner, createMode);753    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;754    const result = getCreateItemResult(events);755756    expect(result.success).to.be.false;757  });758}759760export async function setPublicAccessModeExpectSuccess(761  sender: IKeyringPair, collectionId: number,762  accessMode: 'Normal' | 'WhiteList',763) {764  await usingApi(async (api) => {765766    // Run the transaction767    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);768    const events = await submitTransactionAsync(sender, tx);769    const result = getGenericResult(events);770771    // Get the collection772    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();773774    // What to expect775    // tslint:disable-next-line:no-unused-expression776    expect(result.success).to.be.true;777    expect(collection.Access).to.be.equal(accessMode);778  });779}780781export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {782  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');783}784785export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {786  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');787}788789export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {790  await usingApi(async (api) => {791792    // Run the transaction793    const tx = api.tx.nft.setMintPermission(collectionId, enabled);794    const events = await submitTransactionAsync(sender, tx);795    const result = getGenericResult(events);796797    // Get the collection798    const collection: any = (await api.query.nft.collection(collectionId)).toJSON();799800    // What to expect801    // tslint:disable-next-line:no-unused-expression802    expect(result.success).to.be.true;803    expect(collection.MintMode).to.be.equal(enabled);804  });805}806807export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {808  await setMintPermissionExpectSuccess(sender, collectionId, true);809}810811export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {812  await usingApi(async (api) => {813    // Run the transaction814    const tx = api.tx.nft.setMintPermission(collectionId, enabled);815    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;816    const result = getCreateCollectionResult(events);817    // tslint:disable-next-line:no-unused-expression818    expect(result.success).to.be.false;819  });820}821822export async function isWhitelisted(collectionId: number, address: string) {823  let whitelisted: boolean = false;824  await usingApi(async (api) => {825    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;826  });827  return whitelisted;828}829830export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {831  await usingApi(async (api) => {832833    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();834835    // Run the transaction836    const tx = api.tx.nft.addToWhiteList(collectionId, address);837    const events = await submitTransactionAsync(sender, tx);838    const result = getGenericResult(events);839840    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();841842    // What to expect843    // tslint:disable-next-line:no-unused-expression844    expect(result.success).to.be.true;845    // tslint:disable-next-line: no-unused-expression846    expect(whiteListedBefore).to.be.false;847    // tslint:disable-next-line: no-unused-expression848    expect(whiteListedAfter).to.be.true;849  });850}851852export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {853  await usingApi(async (api) => {854    // Run the transaction855    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);856    const events = await submitTransactionAsync(sender, tx);857    const result = getGenericResult(events);858859    // What to expect860    // tslint:disable-next-line:no-unused-expression861    expect(result.success).to.be.true;862  });863}864865export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {866  await usingApi(async (api) => {867    // Run the transaction868    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);869    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;870    const result = getGenericResult(events);871872    // What to expect873    // tslint:disable-next-line:no-unused-expression874    expect(result.success).to.be.false;875  });876}877878export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)879  : Promise<ICollectionInterface | null> => {880  return await api.query.nft.collection(collectionId) as unknown as ICollectionInterface;881};882883export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {884  // set global object - collectionsCount885  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();886};887888export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {889  return await usingApi(async (api) => {890    return (await api.query.nft.collection(collectionId)) as unknown as ICollectionInterface;891  });892}