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

difftreelog

refactor revert changing collection owner type

Yaroslav Bolyukin2021-06-02parent: #1824786.patch.diff
in: master
Not necessary yet, we don't have to support evm accounts create
collections

3 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -167,7 +167,7 @@
 #[derive(Encode, Decode, Clone, PartialEq)]
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub struct Collection<T: Config> {
-    pub owner: T::CrossAccountId,
+    pub owner: T::AccountId,
     pub mode: CollectionMode,
     pub access: AccessMode,
     pub decimal_points: DecimalPoints,
@@ -638,6 +638,7 @@
 decl_event!(
     pub enum Event<T>
     where
+        AccountId = <T as frame_system::Config>::AccountId,
         CrossAccountId = <T as Config>::CrossAccountId,
     {
         /// New collection was created
@@ -649,7 +650,7 @@
         /// * mode: [CollectionMode] converted into u8.
         /// 
         /// * account_id: Collection owner.
-        CollectionCreated(CollectionId, u8, CrossAccountId),
+        CollectionCreated(CollectionId, u8, AccountId),
 
         /// New item was created.
         /// 
@@ -734,7 +735,7 @@
                                  mode: CollectionMode) -> DispatchResult {
 
             // Anyone can create a collection
-            let who = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let who = ensure_signed(origin)?;
 
             // Take a (non-refundable) deposit of collection creation
             let mut imbalance = <<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();
@@ -743,7 +744,7 @@
                 T::CollectionCreationPrice::get(),
             ));
             <T as Config>::Currency::settle(
-                who.as_sub(),
+                &who,
                 imbalance,
                 WithdrawReasons::TRANSFER,
                 ExistenceRequirement::KeepAlive,
@@ -820,7 +821,7 @@
         #[transactional]
         pub fn destroy_collection(origin, collection_id: CollectionId) -> DispatchResult {
 
-            let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let sender = ensure_signed(origin)?;
             let collection = Self::get_collection(collection_id)?;
             Self::check_owner_permissions(&collection, &sender)?;
             if !collection.limits.owner_can_destroy {
@@ -925,7 +926,7 @@
         #[transactional]
         pub fn set_public_access_mode(origin, collection_id: CollectionId, mode: AccessMode) -> DispatchResult
         {
-            let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let sender = ensure_signed(origin)?;
 
             let mut target_collection = Self::get_collection(collection_id)?;
             Self::check_owner_permissions(&target_collection, &sender)?;
@@ -952,7 +953,7 @@
         #[transactional]
         pub fn set_mint_permission(origin, collection_id: CollectionId, mint_permission: bool) -> DispatchResult
         {
-            let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let sender = ensure_signed(origin)?;
 
             let mut target_collection = Self::get_collection(collection_id)?;
             Self::check_owner_permissions(&target_collection, &sender)?;
@@ -975,9 +976,9 @@
         /// * new_owner.
         #[weight = <T as Config>::WeightInfo::change_collection_owner()]
         #[transactional]
-        pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::CrossAccountId) -> DispatchResult {
+        pub fn change_collection_owner(origin, collection_id: CollectionId, new_owner: T::AccountId) -> DispatchResult {
 
-            let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let sender = ensure_signed(origin)?;
             let mut target_collection = Self::get_collection(collection_id)?;
             Self::check_owner_permissions(&target_collection, &sender)?;
             target_collection.owner = new_owner;
@@ -1061,7 +1062,7 @@
         #[weight = <T as Config>::WeightInfo::set_collection_sponsor()]
         #[transactional]
         pub fn set_collection_sponsor(origin, collection_id: CollectionId, new_sponsor: T::AccountId) -> DispatchResult {
-            let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+            let sender = ensure_signed(origin)?;
             let mut target_collection = Self::get_collection(collection_id)?;
             Self::check_owner_permissions(&target_collection, &sender)?;
 
@@ -1110,7 +1111,7 @@
             let sender = ensure_signed(origin)?;
 
             let mut target_collection = Self::get_collection(collection_id)?;
-            Self::check_owner_permissions(&target_collection, &T::CrossAccountId::from_sub(sender))?;
+            Self::check_owner_permissions(&target_collection, &sender)?;
 
             target_collection.sponsorship = SponsorshipState::Disabled;
             Self::save_collection(target_collection);
@@ -1650,7 +1651,7 @@
         ) -> DispatchResult {
             let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
             let mut target_collection = Self::get_collection(collection_id)?;
-            Self::check_owner_permissions(&target_collection, &sender)?;
+            Self::check_owner_permissions(&target_collection, &sender.as_sub())?;
             let old_limits = &target_collection.limits;
             let chain_limits = ChainLimit::get();
 
@@ -2239,7 +2240,7 @@
         )
     }
 
-    fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: &T::CrossAccountId) -> DispatchResult {
+    fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: &T::AccountId) -> DispatchResult {
         ensure!(
             *subject == target_collection.owner,
             Error::<T>::NoPermission
@@ -2249,7 +2250,7 @@
     }
 
     fn is_owner_or_admin_permissions(collection: &CollectionHandle<T>, subject: &T::CrossAccountId) -> bool {
-        *subject == collection.owner || <AdminList<T>>::get(collection.id).contains(&subject)
+        *subject.as_sub() == collection.owner || <AdminList<T>>::get(collection.id).contains(&subject)
     }
 
     fn check_owner_or_admin_permissions(
modifiedruntime_types.jsondiffbeforeafterboth
--- a/runtime_types.json
+++ b/runtime_types.json
@@ -45,7 +45,7 @@
       }
     },
     "Collection": {
-      "Owner": "CrossAccountId",
+      "Owner": "AccountId",
       "Mode": "CollectionMode",
       "Access": "AccessMode",
       "DecimalPoints": "DecimalPoints",
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 type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { u128 } from '@polkadot/types/primitive';9import { IKeyringPair } from '@polkadot/types/types';10import { evmToAddress } from '@polkadot/util-crypto';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 type CrossAccountId = {25  substrate: string,26} | {27  ethereum: string,28};29export function normalizeAccountId(input: string | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string')31    return { substrate: input };32  if ('address' in input) {33    return { substrate: input.address };34  }35  if ('ethereum' in input) {36    input.ethereum = input.ethereum.toLowerCase();37  }38  return input;39}40export function toSubstrateAddress(input: CrossAccountId): string {41  input = normalizeAccountId(input);42  if ('substrate' in input) {43    return input.substrate;44  } else {45    return evmToAddress(input.ethereum);46  }47}4849export const U128_MAX = (1n << 128n) - 1n;5051type GenericResult = {52  success: boolean,53};5455interface CreateCollectionResult {56  success: boolean;57  collectionId: number;58}5960interface CreateItemResult {61  success: boolean;62  collectionId: number;63  itemId: number;64  recipient?: CrossAccountId;65}6667interface TransferResult {68  success: boolean;69  collectionId: number;70  itemId: number;71  sender?: CrossAccountId;72  recipient?: CrossAccountId;73  value: bigint;74}7576interface IReFungibleOwner {77  Fraction: BN;78  Owner: number[];79}8081interface ITokenDataType {82  Owner: number[];83  ConstData: number[];84  VariableData: number[];85}8687interface IFungibleTokenDataType {88  Value: BN;89}9091interface IGetMessage {92  checkMsgNftMethod: string;93  checkMsgTrsMethod: string;94  checkMsgSysMethod: string;95}9697export interface IReFungibleTokenDataType {98  Owner: IReFungibleOwner[];99  ConstData: number[];100  VariableData: number[];101}102103export function nftEventMessage(events: EventRecord[]): IGetMessage {104  let checkMsgNftMethod: string = '';105  let checkMsgTrsMethod: string = '';106  let checkMsgSysMethod: string = '';107  events.forEach(({ event: { method, section } }) => {108    if (section === 'nft') {109      checkMsgNftMethod = method;110    } else if (section === 'treasury') {111      checkMsgTrsMethod = method;112    } else if (section === 'system') {113      checkMsgSysMethod = method;114    } else { return null; }115  });116  const result: IGetMessage = {117    checkMsgNftMethod,118    checkMsgTrsMethod,119    checkMsgSysMethod,120  };121  return result;122}123124export function getGenericResult(events: EventRecord[]): GenericResult {125  const result: GenericResult = {126    success: false,127  };128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method === 'ExtrinsicSuccess') {131      result.success = true;132    }133  });134  return result;135}136137138139export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {140  let success = false;141  let collectionId: number = 0;142  events.forEach(({ phase, event: { data, method, section } }) => {143    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);144    if (method == 'ExtrinsicSuccess') {145      success = true;146    } else if ((section == 'nft') && (method == 'CollectionCreated')) {147      collectionId = parseInt(data[0].toString());148    }149  });150  const result: CreateCollectionResult = {151    success,152    collectionId,153  };154  return result;155}156157export function getCreateItemResult(events: EventRecord[]): CreateItemResult {158  let success = false;159  let collectionId: number = 0;160  let itemId: number = 0;161  let recipient;162  events.forEach(({ phase, event: { data, method, section } }) => {163    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);164    if (method == 'ExtrinsicSuccess') {165      success = true;166    } else if ((section == 'nft') && (method == 'ItemCreated')) {167      collectionId = parseInt(data[0].toString());168      itemId = parseInt(data[1].toString());169      recipient = data[2].toJSON();170    }171  });172  const result: CreateItemResult = {173    success,174    collectionId,175    itemId,176    recipient,177  };178  return result;179}180181export function getTransferResult(events: EventRecord[]): TransferResult {182  const result: TransferResult = {183    success: false,184    collectionId: 0,185    itemId: 0,186    value: 0n,187  };188189  events.forEach(({ event: { data, method, section } }) => {190    if (method === 'ExtrinsicSuccess') {191      result.success = true;192    } else if (section === 'nft' && method === 'Transfer') {193      result.collectionId = +data[0].toString();194      result.itemId = +data[1].toString();195      result.sender = data[2].toJSON() as CrossAccountId;196      result.recipient = data[3].toJSON() as CrossAccountId;197      result.value = BigInt(data[4].toString());198    }199  });200201  return result;202}203204interface Invalid {205  type: 'Invalid';206}207208interface Nft {209  type: 'NFT';210}211212interface Fungible {213  type: 'Fungible';214  decimalPoints: number;215}216217interface ReFungible {218  type: 'ReFungible';219}220221type CollectionMode = Nft | Fungible | ReFungible | Invalid;222223export type CreateCollectionParams = {224  mode: CollectionMode,225  name: string,226  description: string,227  tokenPrefix: string,228};229230const defaultCreateCollectionParams: CreateCollectionParams = {231  description: 'description',232  mode: { type: 'NFT' },233  name: 'name',234  tokenPrefix: 'prefix',235}236237export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {238  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };239240  let collectionId: number = 0;241  await usingApi(async (api) => {242    // Get number of collections before the transaction243    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Run the CreateCollection transaction246    const alicePrivateKey = privateKey('//Alice');247248    let modeprm = {};249    if (mode.type === 'NFT') {250      modeprm = { nft: null };251    } else if (mode.type === 'Fungible') {252      modeprm = { fungible: mode.decimalPoints };253    } else if (mode.type === 'ReFungible') {254      modeprm = { refungible: null };255    } else if (mode.type === 'Invalid') {256      modeprm = { invalid: null };257    }258259    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);260    const events = await submitTransactionAsync(alicePrivateKey, tx);261    const result = getCreateCollectionResult(events);262263    // Get number of collections after the transaction264    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);265266    // Get the collection267    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();268269    // What to expect270    // tslint:disable-next-line:no-unused-expression271    expect(result.success).to.be.true;272    expect(result.collectionId).to.be.equal(BcollectionCount);273    // tslint:disable-next-line:no-unused-expression274    expect(collection).to.be.not.null;275    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');276    expect(collection.Owner).to.be.deep.equal(normalizeAccountId(alicesPublicKey));277    expect(utf16ToStr(collection.Name)).to.be.equal(name);278    expect(utf16ToStr(collection.Description)).to.be.equal(description);279    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);280281    collectionId = result.collectionId;282  });283284  return collectionId;285}286287export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {288  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };289290  let modeprm = {};291  if (mode.type === 'NFT') {292    modeprm = { nft: null };293  } else if (mode.type === 'Fungible') {294    modeprm = { fungible: mode.decimalPoints };295  } else if (mode.type === 'ReFungible') {296    modeprm = { refungible: null };297  } else if (mode.type === 'Invalid') {298    modeprm = { invalid: null };299  }300301  await usingApi(async (api) => {302    // Get number of collections before the transaction303    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());304305    // Run the CreateCollection transaction306    const alicePrivateKey = privateKey('//Alice');307    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);308    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;309    const result = getCreateCollectionResult(events);310311    // Get number of collections after the transaction312    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());313314    // What to expect315    // tslint:disable-next-line:no-unused-expression316    expect(result.success).to.be.false;317    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');318  });319}320321export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {322  let bal = new BigNumber(0);323  let unused;324  do {325    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;326    const keyring = new Keyring({ type: 'sr25519' });327    unused = keyring.addFromUri(`//${randomSeed}`);328    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());329  } while (bal.toFixed() != '0');330  return unused;331}332333export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {334  return await usingApi(async (api) => {335    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;336    return BigInt(bn.toString());337  });338}339340export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {341  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));342}343344export async function findNotExistingCollection(api: ApiPromise): Promise<number> {345  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;346  const newCollection: number = totalNumber + 1;347  return newCollection;348}349350function getDestroyResult(events: EventRecord[]): boolean {351  let success: boolean = false;352  events.forEach(({ phase, event: { data, method, section } }) => {353    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {527  await usingApi(async (api) => {528    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {537  await usingApi(async (api) => {538    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);539    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;540    const result = getGenericResult(events);541542    expect(result.success).to.be.false;543  });544}545546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {557  let whitelisted: boolean = false;558  await usingApi(async (api) => {559    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;560  });561  return whitelisted;562}563564export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {565  await usingApi(async (api) => {566    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {575  await usingApi(async (api) => {576    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());577    const events = await submitTransactionAsync(sender, tx);578    const result = getGenericResult(events);579580    expect(result.success).to.be.true;581  });582}583584export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {585  await usingApi(async (api) => {586    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {595  await usingApi(async (api) => {596    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {605  await usingApi(async (api) => {606    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));607    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608  });609}610611export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {612  await usingApi(async (api) => {613    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));614    const events = await submitTransactionAsync(sender, tx);615    const result = getGenericResult(events);616617    expect(result.success).to.be.true;618  });619}620621export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {622  await usingApi(async (api) => {623    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));624    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;625  });626}627628export interface CreateFungibleData {629  readonly Value: bigint;630}631632export interface CreateReFungibleData { }633export interface CreateNftData { }634635export type CreateItemData = {636  NFT: CreateNftData;637} | {638  Fungible: CreateFungibleData;639} | {640  ReFungible: CreateReFungibleData;641};642643export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);646    const events = await submitTransactionAsync(owner, tx);647    const result = getGenericResult(events);648    // Get the item649    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();650    // What to expect651    // tslint:disable-next-line:no-unused-expression652    expect(result.success).to.be.true;653    // tslint:disable-next-line:no-unused-expression654    expect(item).to.be.null;655  });656}657658export async function659  approveExpectSuccess(collectionId: number,660    tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1) {661  await usingApi(async (api: ApiPromise) => {662    approved = normalizeAccountId(approved);663    const allowanceBefore =664      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;665    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);666    const events = await submitTransactionAsync(owner, approveNftTx);667    const result = getCreateItemResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.true;670    const allowanceAfter =671      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;672    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());673  });674}675676export async function677  transferFromExpectSuccess(collectionId: number,678    tokenId: number,679    accountApproved: IKeyringPair,680    accountFrom: IKeyringPair,681    accountTo: IKeyringPair | CrossAccountId,682    value: number | bigint = 1,683    type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    const to = normalizeAccountId(accountTo);686    let balanceBefore = new BN(0);687    if (type === 'Fungible') {688      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;689    }690    const transferFromTx = api.tx.nft.transferFrom(691      normalizeAccountId(accountFrom.address), to, collectionId, tokenId, value);692    const events = await submitTransactionAsync(accountApproved, transferFromTx);693    const result = getCreateItemResult(events);694    // tslint:disable-next-line:no-unused-expression695    expect(result.success).to.be.true;696    if (type === 'NFT') {697      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;698      expect(nftItemData.Owner).to.be.deep.equal(to);699    }700    if (type === 'Fungible') {701      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;702      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());703    }704    if (type === 'ReFungible') {705      const nftItemData =706        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;707      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));708      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);709    }710  });711}712713export async function714  transferFromExpectFail(collectionId: number,715    tokenId: number,716    accountApproved: IKeyringPair,717    accountFrom: IKeyringPair,718    accountTo: IKeyringPair,719    value: number | bigint = 1) {720  await usingApi(async (api: ApiPromise) => {721    const transferFromTx = api.tx.nft.transferFrom(722      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);723    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;724    const result = getCreateCollectionResult(events);725    // tslint:disable-next-line:no-unused-expression726    expect(result.success).to.be.false;727  });728}729730export async function731  transferExpectSuccess(collectionId: number,732    tokenId: number,733    sender: IKeyringPair,734    recipient: IKeyringPair | CrossAccountId,735    value: number | bigint = 1,736    type: string = 'NFT') {737  await usingApi(async (api: ApiPromise) => {738    const to = normalizeAccountId(recipient);739740    let balanceBefore = new BN(0);741    if (type === 'Fungible') {742      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;743    }744    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);745    const events = await submitTransactionAsync(sender, transferTx);746    const result = getTransferResult(events);747    // tslint:disable-next-line:no-unused-expression748    expect(result.success).to.be.true;749    expect(result.collectionId).to.be.equal(collectionId);750    expect(result.itemId).to.be.equal(tokenId);751    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));752    expect(result.recipient).to.be.deep.equal(to);753    expect(result.value.toString()).to.be.equal(value.toString());754    if (type === 'NFT') {755      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;756      expect(nftItemData.Owner).to.be.deep.equal(to);757    }758    if (type === 'Fungible') {759      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;760      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());761    }762    if (type === 'ReFungible') {763      const nftItemData =764        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;765      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);766      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());767    }768  });769}770771export async function772  transferExpectFail(collectionId: number,773    tokenId: number,774    sender: IKeyringPair,775    recipient: IKeyringPair,776    value: number | bigint = 1,777    type: string = 'NFT') {778  await usingApi(async (api: ApiPromise) => {779    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);780    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;781    if (events && Array.isArray(events)) {782      const result = getCreateCollectionResult(events);783      // tslint:disable-next-line:no-unused-expression784      expect(result.success).to.be.false;785    }786  });787}788789export async function790  approveExpectFail(collectionId: number,791    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {792  await usingApi(async (api: ApiPromise) => {793    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);794    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;795    const result = getCreateCollectionResult(events);796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.false;798  });799}800801export async function getFungibleBalance(802  collectionId: number,803  owner: string,804) {805  return await usingApi(async (api) => {806    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };807    return BigInt(response.Value);808  });809}810811export async function createFungibleItemExpectSuccess(812  sender: IKeyringPair,813  collectionId: number,814  data: CreateFungibleData,815  owner: CrossAccountId | string = sender.address,816) {817  return await usingApi(async (api) => {818    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });819820    const events = await submitTransactionAsync(sender, tx);821    const result = getCreateItemResult(events);822823    expect(result.success).to.be.true;824    return result.itemId;825  });826}827828export async function createItemExpectSuccess(829  sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {830  let newItemId: number = 0;831  await usingApi(async (api) => {832    const to = normalizeAccountId(owner);833    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);834    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();835    const AItemBalance = new BigNumber(Aitem.Value);836837    let tx;838    if (createMode === 'Fungible') {839      const createData = { fungible: { value: 10 } };840      tx = api.tx.nft.createItem(collectionId, to, createData);841    } else if (createMode === 'ReFungible') {842      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };843      tx = api.tx.nft.createItem(collectionId, to, createData);844    } else {845      tx = api.tx.nft.createItem(collectionId, to, createMode);846    }847848    const events = await submitTransactionAsync(sender, tx);849    const result = getCreateItemResult(events);850851    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);852    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();853    const BItemBalance = new BigNumber(Bitem.Value);854855    // What to expect856    // tslint:disable-next-line:no-unused-expression857    expect(result.success).to.be.true;858    if (createMode === 'Fungible') {859      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);860    } else {861      expect(BItemCount).to.be.equal(AItemCount + 1);862    }863    expect(collectionId).to.be.equal(result.collectionId);864    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());865    expect(to).to.be.deep.equal(result.recipient);866    newItemId = result.itemId;867  });868  return newItemId;869}870871export async function createItemExpectFailure(872  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {873  await usingApi(async (api) => {874    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);875    876    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;877    const result = getCreateItemResult(events);878879    expect(result.success).to.be.false;880  });881}882883export async function setPublicAccessModeExpectSuccess(884  sender: IKeyringPair, collectionId: number,885  accessMode: 'Normal' | 'WhiteList',886) {887  await usingApi(async (api) => {888889    // Run the transaction890    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);891    const events = await submitTransactionAsync(sender, tx);892    const result = getGenericResult(events);893894    // Get the collection895    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();896897    // What to expect898    // tslint:disable-next-line:no-unused-expression899    expect(result.success).to.be.true;900    expect(collection.Access).to.be.equal(accessMode);901  });902}903904export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {905  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');906}907908export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {909  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');910}911912export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {913  await usingApi(async (api) => {914915    // Run the transaction916    const tx = api.tx.nft.setMintPermission(collectionId, enabled);917    const events = await submitTransactionAsync(sender, tx);918    const result = getGenericResult(events);919920    // Get the collection921    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();922923    // What to expect924    // tslint:disable-next-line:no-unused-expression925    expect(result.success).to.be.true;926    expect(collection.MintMode).to.be.equal(enabled);927  });928}929930export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {931  await setMintPermissionExpectSuccess(sender, collectionId, true);932}933934export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.setMintPermission(collectionId, enabled);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getCreateCollectionResult(events);940    // tslint:disable-next-line:no-unused-expression941    expect(result.success).to.be.false;942  });943}944945export async function isWhitelisted(collectionId: number, address: string) {946  let whitelisted: boolean = false;947  await usingApi(async (api) => {948    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;949  });950  return whitelisted;951}952953export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {954  await usingApi(async (api) => {955956    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();957958    // Run the transaction959    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));960    const events = await submitTransactionAsync(sender, tx);961    const result = getGenericResult(events);962963    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();964965    // What to expect966    // tslint:disable-next-line:no-unused-expression967    expect(result.success).to.be.true;968    // tslint:disable-next-line: no-unused-expression969    expect(whiteListedBefore).to.be.false;970    // tslint:disable-next-line: no-unused-expression971    expect(whiteListedAfter).to.be.true;972  });973}974975export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {976  await usingApi(async (api) => {977    // Run the transaction978    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));979    const events = await submitTransactionAsync(sender, tx);980    const result = getGenericResult(events);981982    // What to expect983    // tslint:disable-next-line:no-unused-expression984    expect(result.success).to.be.true;985  });986}987988export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {989  await usingApi(async (api) => {990    // Run the transaction991    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));992    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;993    const result = getGenericResult(events);994995    // What to expect996    // tslint:disable-next-line:no-unused-expression997    expect(result.success).to.be.false;998  });999}10001001export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1002  : Promise<ICollectionInterface | null> => {1003  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1004};10051006export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1007  // set global object - collectionsCount1008  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1009};10101011export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1012  return await usingApi(async (api) => {1013    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1014  });1015}
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 type { AccountId, EventRecord } from '@polkadot/types/interfaces';8import { u128 } from '@polkadot/types/primitive';9import { IKeyringPair } from '@polkadot/types/types';10import { evmToAddress } from '@polkadot/util-crypto';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 type CrossAccountId = {25  substrate: string,26} | {27  ethereum: string,28};29export function normalizeAccountId(input: string | CrossAccountId | IKeyringPair): CrossAccountId {30  if (typeof input === 'string')31    return { substrate: input };32  if ('address' in input) {33    return { substrate: input.address };34  }35  if ('ethereum' in input) {36    input.ethereum = input.ethereum.toLowerCase();37  }38  return input;39}40export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {41  input = normalizeAccountId(input);42  if ('substrate' in input) {43    return input.substrate;44  } else {45    return evmToAddress(input.ethereum);46  }47}4849export const U128_MAX = (1n << 128n) - 1n;5051type GenericResult = {52  success: boolean,53};5455interface CreateCollectionResult {56  success: boolean;57  collectionId: number;58}5960interface CreateItemResult {61  success: boolean;62  collectionId: number;63  itemId: number;64  recipient?: CrossAccountId;65}6667interface TransferResult {68  success: boolean;69  collectionId: number;70  itemId: number;71  sender?: CrossAccountId;72  recipient?: CrossAccountId;73  value: bigint;74}7576interface IReFungibleOwner {77  Fraction: BN;78  Owner: number[];79}8081interface ITokenDataType {82  Owner: number[];83  ConstData: number[];84  VariableData: number[];85}8687interface IFungibleTokenDataType {88  Value: BN;89}9091interface IGetMessage {92  checkMsgNftMethod: string;93  checkMsgTrsMethod: string;94  checkMsgSysMethod: string;95}9697export interface IReFungibleTokenDataType {98  Owner: IReFungibleOwner[];99  ConstData: number[];100  VariableData: number[];101}102103export function nftEventMessage(events: EventRecord[]): IGetMessage {104  let checkMsgNftMethod: string = '';105  let checkMsgTrsMethod: string = '';106  let checkMsgSysMethod: string = '';107  events.forEach(({ event: { method, section } }) => {108    if (section === 'nft') {109      checkMsgNftMethod = method;110    } else if (section === 'treasury') {111      checkMsgTrsMethod = method;112    } else if (section === 'system') {113      checkMsgSysMethod = method;114    } else { return null; }115  });116  const result: IGetMessage = {117    checkMsgNftMethod,118    checkMsgTrsMethod,119    checkMsgSysMethod,120  };121  return result;122}123124export function getGenericResult(events: EventRecord[]): GenericResult {125  const result: GenericResult = {126    success: false,127  };128  events.forEach(({ phase, event: { data, method, section } }) => {129    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);130    if (method === 'ExtrinsicSuccess') {131      result.success = true;132    }133  });134  return result;135}136137138139export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {140  let success = false;141  let collectionId: number = 0;142  events.forEach(({ phase, event: { data, method, section } }) => {143    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);144    if (method == 'ExtrinsicSuccess') {145      success = true;146    } else if ((section == 'nft') && (method == 'CollectionCreated')) {147      collectionId = parseInt(data[0].toString());148    }149  });150  const result: CreateCollectionResult = {151    success,152    collectionId,153  };154  return result;155}156157export function getCreateItemResult(events: EventRecord[]): CreateItemResult {158  let success = false;159  let collectionId: number = 0;160  let itemId: number = 0;161  let recipient;162  events.forEach(({ phase, event: { data, method, section } }) => {163    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);164    if (method == 'ExtrinsicSuccess') {165      success = true;166    } else if ((section == 'nft') && (method == 'ItemCreated')) {167      collectionId = parseInt(data[0].toString());168      itemId = parseInt(data[1].toString());169      recipient = data[2].toJSON();170    }171  });172  const result: CreateItemResult = {173    success,174    collectionId,175    itemId,176    recipient,177  };178  return result;179}180181export function getTransferResult(events: EventRecord[]): TransferResult {182  const result: TransferResult = {183    success: false,184    collectionId: 0,185    itemId: 0,186    value: 0n,187  };188189  events.forEach(({ event: { data, method, section } }) => {190    if (method === 'ExtrinsicSuccess') {191      result.success = true;192    } else if (section === 'nft' && method === 'Transfer') {193      result.collectionId = +data[0].toString();194      result.itemId = +data[1].toString();195      result.sender = data[2].toJSON() as CrossAccountId;196      result.recipient = data[3].toJSON() as CrossAccountId;197      result.value = BigInt(data[4].toString());198    }199  });200201  return result;202}203204interface Invalid {205  type: 'Invalid';206}207208interface Nft {209  type: 'NFT';210}211212interface Fungible {213  type: 'Fungible';214  decimalPoints: number;215}216217interface ReFungible {218  type: 'ReFungible';219}220221type CollectionMode = Nft | Fungible | ReFungible | Invalid;222223export type CreateCollectionParams = {224  mode: CollectionMode,225  name: string,226  description: string,227  tokenPrefix: string,228};229230const defaultCreateCollectionParams: CreateCollectionParams = {231  description: 'description',232  mode: { type: 'NFT' },233  name: 'name',234  tokenPrefix: 'prefix',235}236237export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {238  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };239240  let collectionId: number = 0;241  await usingApi(async (api) => {242    // Get number of collections before the transaction243    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Run the CreateCollection transaction246    const alicePrivateKey = privateKey('//Alice');247248    let modeprm = {};249    if (mode.type === 'NFT') {250      modeprm = { nft: null };251    } else if (mode.type === 'Fungible') {252      modeprm = { fungible: mode.decimalPoints };253    } else if (mode.type === 'ReFungible') {254      modeprm = { refungible: null };255    } else if (mode.type === 'Invalid') {256      modeprm = { invalid: null };257    }258259    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);260    const events = await submitTransactionAsync(alicePrivateKey, tx);261    const result = getCreateCollectionResult(events);262263    // Get number of collections after the transaction264    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);265266    // Get the collection267    const collection: any = (await api.query.nft.collectionById(result.collectionId) as any).toJSON();268269    // What to expect270    // tslint:disable-next-line:no-unused-expression271    expect(result.success).to.be.true;272    expect(result.collectionId).to.be.equal(BcollectionCount);273    // tslint:disable-next-line:no-unused-expression274    expect(collection).to.be.not.null;275    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');276    expect(collection.Owner).to.be.equal(toSubstrateAddress(alicesPublicKey));277    expect(utf16ToStr(collection.Name)).to.be.equal(name);278    expect(utf16ToStr(collection.Description)).to.be.equal(description);279    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);280281    collectionId = result.collectionId;282  });283284  return collectionId;285}286287export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {288  const { name, description, mode, tokenPrefix } = { ...defaultCreateCollectionParams, ...params };289290  let modeprm = {};291  if (mode.type === 'NFT') {292    modeprm = { nft: null };293  } else if (mode.type === 'Fungible') {294    modeprm = { fungible: mode.decimalPoints };295  } else if (mode.type === 'ReFungible') {296    modeprm = { refungible: null };297  } else if (mode.type === 'Invalid') {298    modeprm = { invalid: null };299  }300301  await usingApi(async (api) => {302    // Get number of collections before the transaction303    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());304305    // Run the CreateCollection transaction306    const alicePrivateKey = privateKey('//Alice');307    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);308    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;309    const result = getCreateCollectionResult(events);310311    // Get number of collections after the transaction312    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());313314    // What to expect315    // tslint:disable-next-line:no-unused-expression316    expect(result.success).to.be.false;317    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');318  });319}320321export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {322  let bal = new BigNumber(0);323  let unused;324  do {325    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;326    const keyring = new Keyring({ type: 'sr25519' });327    unused = keyring.addFromUri(`//${randomSeed}`);328    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());329  } while (bal.toFixed() != '0');330  return unused;331}332333export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {334  return await usingApi(async (api) => {335    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;336    return BigInt(bn.toString());337  });338}339340export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {341  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));342}343344export async function findNotExistingCollection(api: ApiPromise): Promise<number> {345  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;346  const newCollection: number = totalNumber + 1;347  return newCollection;348}349350function getDestroyResult(events: EventRecord[]): boolean {351  let success: boolean = false;352  events.forEach(({ phase, event: { data, method, section } }) => {353    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);354    if (method == 'ExtrinsicSuccess') {355      success = true;356    }357  });358  return success;359}360361export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {362  await usingApi(async (api) => {363    // Run the DestroyCollection transaction364    const alicePrivateKey = privateKey(senderSeed);365    const tx = api.tx.nft.destroyCollection(collectionId);366    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;367  });368}369370export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {371  await usingApi(async (api) => {372    // Run the DestroyCollection transaction373    const alicePrivateKey = privateKey(senderSeed);374    const tx = api.tx.nft.destroyCollection(collectionId);375    const events = await submitTransactionAsync(alicePrivateKey, tx);376    const result = getDestroyResult(events);377378    // Get the collection379    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();380381    // What to expect382    expect(result).to.be.true;383    expect(collection).to.be.null;384  });385}386387export async function queryCollectionLimits(collectionId: number) {388  return await usingApi(async (api) => {389    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;390  });391}392393export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {394  await usingApi(async (api) => {395    const oldLimits = await queryCollectionLimits(collectionId);396    const newLimits = { ...oldLimits as any, ...limits };397    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);398    const events = await submitTransactionAsync(sender, tx);399    const result = getGenericResult(events);400401    expect(result.success).to.be.true;402  });403}404405export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const oldLimits = await queryCollectionLimits(collectionId);408    const newLimits = { ...oldLimits as any, ...limits };409    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);410    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;411    const result = getGenericResult(events);412413    expect(result.success).to.be.false;414  });415}416417export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {418  await usingApi(async (api) => {419420    // Run the transaction421    const alicePrivateKey = privateKey('//Alice');422    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);423    const events = await submitTransactionAsync(alicePrivateKey, tx);424    const result = getGenericResult(events);425426    // Get the collection427    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();428429    // What to expect430    expect(result.success).to.be.true;431    expect(collection.Sponsorship).to.deep.equal({432      unconfirmed: sponsor,433    });434  });435}436437export async function removeCollectionSponsorExpectSuccess(collectionId: number) {438  await usingApi(async (api) => {439440    // Run the transaction441    const alicePrivateKey = privateKey('//Alice');442    const tx = api.tx.nft.removeCollectionSponsor(collectionId);443    const events = await submitTransactionAsync(alicePrivateKey, tx);444    const result = getGenericResult(events);445446    // Get the collection447    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();448449    // What to expect450    expect(result.success).to.be.true;451    expect(collection.Sponsorship).to.be.deep.equal({ disabled: null });452  });453}454455export async function removeCollectionSponsorExpectFailure(collectionId: number) {456  await usingApi(async (api) => {457458    // Run the transaction459    const alicePrivateKey = privateKey('//Alice');460    const tx = api.tx.nft.removeCollectionSponsor(collectionId);461    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;462  });463}464465export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {466  await usingApi(async (api) => {467468    // Run the transaction469    const alicePrivateKey = privateKey(senderSeed);470    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);471    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;472  });473}474475export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {476  await usingApi(async (api) => {477478    // Run the transaction479    const sender = privateKey(senderSeed);480    const tx = api.tx.nft.confirmSponsorship(collectionId);481    const events = await submitTransactionAsync(sender, tx);482    const result = getGenericResult(events);483484    // Get the collection485    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();486487    // What to expect488    expect(result.success).to.be.true;489    expect(collection.Sponsorship).to.be.deep.equal({490      confirmed: sender.address,491    });492  });493}494495496export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {497  await usingApi(async (api) => {498499    // Run the transaction500    const sender = privateKey(senderSeed);501    const tx = api.tx.nft.confirmSponsorship(collectionId);502    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;503  });504}505506export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {507  await usingApi(async (api) => {508    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);509    const events = await submitTransactionAsync(sender, tx);510    const result = getGenericResult(events);511512    expect(result.success).to.be.true;513  });514}515516export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {517  await usingApi(async (api) => {518    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);519    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;520    const result = getGenericResult(events);521522    expect(result.success).to.be.false;523  });524}525526export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {527  await usingApi(async (api) => {528    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);529    const events = await submitTransactionAsync(sender, tx);530    const result = getGenericResult(events);531532    expect(result.success).to.be.true;533  });534}535536export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {537  await usingApi(async (api) => {538    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);539    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;540    const result = getGenericResult(events);541542    expect(result.success).to.be.false;543  });544}545546export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);549    const events = await submitTransactionAsync(sender, tx);550    const result = getGenericResult(events);551552    expect(result.success).to.be.true;553  });554}555556export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {557  let whitelisted: boolean = false;558  await usingApi(async (api) => {559    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;560  });561  return whitelisted;562}563564export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {565  await usingApi(async (api) => {566    const tx = api.tx.nft.addToContractWhiteList(contractAddress.toString(), user.toString());567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {575  await usingApi(async (api) => {576    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());577    const events = await submitTransactionAsync(sender, tx);578    const result = getGenericResult(events);579580    expect(result.success).to.be.true;581  });582}583584export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {585  await usingApi(async (api) => {586    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress.toString(), user.toString());587    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;588    const result = getGenericResult(events);589590    expect(result.success).to.be.false;591  });592}593594export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {595  await usingApi(async (api) => {596    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));597    const events = await submitTransactionAsync(sender, tx);598    const result = getGenericResult(events);599600    expect(result.success).to.be.true;601  });602}603604export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {605  await usingApi(async (api) => {606    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));607    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;608  });609}610611export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {612  await usingApi(async (api) => {613    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));614    const events = await submitTransactionAsync(sender, tx);615    const result = getGenericResult(events);616617    expect(result.success).to.be.true;618  });619}620621export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {622  await usingApi(async (api) => {623    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));624    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;625  });626}627628export interface CreateFungibleData {629  readonly Value: bigint;630}631632export interface CreateReFungibleData { }633export interface CreateNftData { }634635export type CreateItemData = {636  NFT: CreateNftData;637} | {638  Fungible: CreateFungibleData;639} | {640  ReFungible: CreateReFungibleData;641};642643export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {644  await usingApi(async (api) => {645    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);646    const events = await submitTransactionAsync(owner, tx);647    const result = getGenericResult(events);648    // Get the item649    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();650    // What to expect651    // tslint:disable-next-line:no-unused-expression652    expect(result.success).to.be.true;653    // tslint:disable-next-line:no-unused-expression654    expect(item).to.be.null;655  });656}657658export async function659  approveExpectSuccess(collectionId: number,660    tokenId: number, owner: IKeyringPair, approved: IKeyringPair | CrossAccountId | string, amount: number | bigint = 1) {661  await usingApi(async (api: ApiPromise) => {662    approved = normalizeAccountId(approved);663    const allowanceBefore =664      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;665    const approveNftTx = api.tx.nft.approve(approved, collectionId, tokenId, amount);666    const events = await submitTransactionAsync(owner, approveNftTx);667    const result = getCreateItemResult(events);668    // tslint:disable-next-line:no-unused-expression669    expect(result.success).to.be.true;670    const allowanceAfter =671      await api.query.nft.allowances(collectionId, [tokenId, owner.address, toSubstrateAddress(approved)]) as unknown as BN;672    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());673  });674}675676export async function677  transferFromExpectSuccess(collectionId: number,678    tokenId: number,679    accountApproved: IKeyringPair,680    accountFrom: IKeyringPair,681    accountTo: IKeyringPair | CrossAccountId,682    value: number | bigint = 1,683    type: string = 'NFT') {684  await usingApi(async (api: ApiPromise) => {685    const to = normalizeAccountId(accountTo);686    let balanceBefore = new BN(0);687    if (type === 'Fungible') {688      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;689    }690    const transferFromTx = api.tx.nft.transferFrom(691      normalizeAccountId(accountFrom.address), to, collectionId, tokenId, value);692    const events = await submitTransactionAsync(accountApproved, transferFromTx);693    const result = getCreateItemResult(events);694    // tslint:disable-next-line:no-unused-expression695    expect(result.success).to.be.true;696    if (type === 'NFT') {697      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).toJSON() as ITokenDataType;698      expect(nftItemData.Owner).to.be.deep.equal(to);699    }700    if (type === 'Fungible') {701      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;702      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());703    }704    if (type === 'ReFungible') {705      const nftItemData =706        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).toJSON() as IReFungibleTokenDataType;707      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(normalizeAccountId(to));708      expect(nftItemData.Owner[0].Fraction).to.be.equal(value);709    }710  });711}712713export async function714  transferFromExpectFail(collectionId: number,715    tokenId: number,716    accountApproved: IKeyringPair,717    accountFrom: IKeyringPair,718    accountTo: IKeyringPair,719    value: number | bigint = 1) {720  await usingApi(async (api: ApiPromise) => {721    const transferFromTx = api.tx.nft.transferFrom(722      normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);723    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;724    const result = getCreateCollectionResult(events);725    // tslint:disable-next-line:no-unused-expression726    expect(result.success).to.be.false;727  });728}729730export async function731  transferExpectSuccess(collectionId: number,732    tokenId: number,733    sender: IKeyringPair,734    recipient: IKeyringPair | CrossAccountId,735    value: number | bigint = 1,736    type: string = 'NFT') {737  await usingApi(async (api: ApiPromise) => {738    const to = normalizeAccountId(recipient);739740    let balanceBefore = new BN(0);741    if (type === 'Fungible') {742      balanceBefore = await api.query.nft.balance(collectionId, toSubstrateAddress(to)) as unknown as BN;743    }744    const transferTx = api.tx.nft.transfer(to, collectionId, tokenId, value);745    const events = await submitTransactionAsync(sender, transferTx);746    const result = getTransferResult(events);747    // tslint:disable-next-line:no-unused-expression748    expect(result.success).to.be.true;749    expect(result.collectionId).to.be.equal(collectionId);750    expect(result.itemId).to.be.equal(tokenId);751    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));752    expect(result.recipient).to.be.deep.equal(to);753    expect(result.value.toString()).to.be.equal(value.toString());754    if (type === 'NFT') {755      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;756      expect(nftItemData.Owner).to.be.deep.equal(to);757    }758    if (type === 'Fungible') {759      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to)) as any).Value as unknown as BN;760      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());761    }762    if (type === 'ReFungible') {763      const nftItemData =764        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;765      expect(nftItemData.Owner[0].Owner).to.be.deep.equal(to);766      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());767    }768  });769}770771export async function772  transferExpectFail(collectionId: number,773    tokenId: number,774    sender: IKeyringPair,775    recipient: IKeyringPair,776    value: number | bigint = 1,777    type: string = 'NFT') {778  await usingApi(async (api: ApiPromise) => {779    const transferTx = api.tx.nft.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);780    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;781    if (events && Array.isArray(events)) {782      const result = getCreateCollectionResult(events);783      // tslint:disable-next-line:no-unused-expression784      expect(result.success).to.be.false;785    }786  });787}788789export async function790  approveExpectFail(collectionId: number,791    tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {792  await usingApi(async (api: ApiPromise) => {793    const approveNftTx = api.tx.nft.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);794    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;795    const result = getCreateCollectionResult(events);796    // tslint:disable-next-line:no-unused-expression797    expect(result.success).to.be.false;798  });799}800801export async function getFungibleBalance(802  collectionId: number,803  owner: string,804) {805  return await usingApi(async (api) => {806    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as { Value: string };807    return BigInt(response.Value);808  });809}810811export async function createFungibleItemExpectSuccess(812  sender: IKeyringPair,813  collectionId: number,814  data: CreateFungibleData,815  owner: CrossAccountId | string = sender.address,816) {817  return await usingApi(async (api) => {818    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), { Fungible: data });819820    const events = await submitTransactionAsync(sender, tx);821    const result = getCreateItemResult(events);822823    expect(result.success).to.be.true;824    return result.itemId;825  });826}827828export async function createItemExpectSuccess(829  sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {830  let newItemId: number = 0;831  await usingApi(async (api) => {832    const to = normalizeAccountId(owner);833    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);834    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();835    const AItemBalance = new BigNumber(Aitem.Value);836837    let tx;838    if (createMode === 'Fungible') {839      const createData = { fungible: { value: 10 } };840      tx = api.tx.nft.createItem(collectionId, to, createData);841    } else if (createMode === 'ReFungible') {842      const createData = { refungible: { const_data: [], variable_data: [], pieces: 100 } };843      tx = api.tx.nft.createItem(collectionId, to, createData);844    } else {845      tx = api.tx.nft.createItem(collectionId, to, createMode);846    }847848    const events = await submitTransactionAsync(sender, tx);849    const result = getCreateItemResult(events);850851    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);852    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, toSubstrateAddress(to))).toJSON();853    const BItemBalance = new BigNumber(Bitem.Value);854855    // What to expect856    // tslint:disable-next-line:no-unused-expression857    expect(result.success).to.be.true;858    if (createMode === 'Fungible') {859      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);860    } else {861      expect(BItemCount).to.be.equal(AItemCount + 1);862    }863    expect(collectionId).to.be.equal(result.collectionId);864    expect(BItemCount.toString()).to.be.equal(result.itemId.toString());865    expect(to).to.be.deep.equal(result.recipient);866    newItemId = result.itemId;867  });868  return newItemId;869}870871export async function createItemExpectFailure(872  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {873  await usingApi(async (api) => {874    const tx = api.tx.nft.createItem(collectionId, normalizeAccountId(owner), createMode);875    876    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;877    const result = getCreateItemResult(events);878879    expect(result.success).to.be.false;880  });881}882883export async function setPublicAccessModeExpectSuccess(884  sender: IKeyringPair, collectionId: number,885  accessMode: 'Normal' | 'WhiteList',886) {887  await usingApi(async (api) => {888889    // Run the transaction890    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);891    const events = await submitTransactionAsync(sender, tx);892    const result = getGenericResult(events);893894    // Get the collection895    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();896897    // What to expect898    // tslint:disable-next-line:no-unused-expression899    expect(result.success).to.be.true;900    expect(collection.Access).to.be.equal(accessMode);901  });902}903904export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {905  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');906}907908export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {909  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');910}911912export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {913  await usingApi(async (api) => {914915    // Run the transaction916    const tx = api.tx.nft.setMintPermission(collectionId, enabled);917    const events = await submitTransactionAsync(sender, tx);918    const result = getGenericResult(events);919920    // Get the collection921    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();922923    // What to expect924    // tslint:disable-next-line:no-unused-expression925    expect(result.success).to.be.true;926    expect(collection.MintMode).to.be.equal(enabled);927  });928}929930export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {931  await setMintPermissionExpectSuccess(sender, collectionId, true);932}933934export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {935  await usingApi(async (api) => {936    // Run the transaction937    const tx = api.tx.nft.setMintPermission(collectionId, enabled);938    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;939    const result = getCreateCollectionResult(events);940    // tslint:disable-next-line:no-unused-expression941    expect(result.success).to.be.false;942  });943}944945export async function isWhitelisted(collectionId: number, address: string) {946  let whitelisted: boolean = false;947  await usingApi(async (api) => {948    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;949  });950  return whitelisted;951}952953export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {954  await usingApi(async (api) => {955956    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();957958    // Run the transaction959    const tx = api.tx.nft.addToWhiteList(collectionId, normalizeAccountId(address));960    const events = await submitTransactionAsync(sender, tx);961    const result = getGenericResult(events);962963    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();964965    // What to expect966    // tslint:disable-next-line:no-unused-expression967    expect(result.success).to.be.true;968    // tslint:disable-next-line: no-unused-expression969    expect(whiteListedBefore).to.be.false;970    // tslint:disable-next-line: no-unused-expression971    expect(whiteListedAfter).to.be.true;972  });973}974975export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {976  await usingApi(async (api) => {977    // Run the transaction978    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));979    const events = await submitTransactionAsync(sender, tx);980    const result = getGenericResult(events);981982    // What to expect983    // tslint:disable-next-line:no-unused-expression984    expect(result.success).to.be.true;985  });986}987988export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {989  await usingApi(async (api) => {990    // Run the transaction991    const tx = api.tx.nft.removeFromWhiteList(collectionId, normalizeAccountId(address));992    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;993    const result = getGenericResult(events);994995    // What to expect996    // tslint:disable-next-line:no-unused-expression997    expect(result.success).to.be.false;998  });999}10001001export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1002  : Promise<ICollectionInterface | null> => {1003  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1004};10051006export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1007  // set global object - collectionsCount1008  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1009};10101011export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1012  return await usingApi(async (api) => {1013    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1014  });1015}