git.delta.rocks / unique-network / refs/commits / 2a441390261c

difftreelog

Scheduler refactored and fixed

str-mv2021-06-15parent: #eb5b535.patch.diff
in: master

8 files changed

modifiedpallets/nft-charge-transaction/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft-charge-transaction/src/lib.rs
+++ b/pallets/nft-charge-transaction/src/lib.rs
@@ -135,6 +135,13 @@
 			.map(|i| (fee, i));
         }
 
+        // check errors
+        let error = <pallet_nft_transaction_payment::Module<T>>::check_error(who, call);
+        match error {
+            Err(error) => return Err(error),
+            Ok(error) => {}
+        };
+
         // Determine who is paying transaction fee based on ecnomic model
 		// Parse call to extract collection ID and access collection sponsor	
 		let sponsor = <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);
addedpallets/nft-transaction-payment/README.mddiffbeforeafterboth
--- /dev/null
+++ b/pallets/nft-transaction-payment/README.md
@@ -0,0 +1,13 @@
+# Nft Transaction Payment
+
+## Overview
+
+A module containing the sponsoring logic for paying for sponsored collections
+
+**NOTE:** The scheduled calls will be dispatched with the default filter
+for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
+except root which will get no filter. And not the filter contained in origin
+use to call `fn schedule`.
+
+If a call is scheduled using proxy or whatever mecanism which adds filter,
+then those filter will not be used when dispatching the schedule call.
modifiedpallets/nft-transaction-payment/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft-transaction-payment/src/lib.rs
+++ b/pallets/nft-transaction-payment/src/lib.rs
@@ -31,6 +31,9 @@
 	traits::{ 
 		Hash, Dispatchable,
 	},
+	transaction_validity::{
+        InvalidTransaction, TransactionValidityError,
+    },
 };
 use pallet_contracts::chain_extension::UncheckedFrom;
 use sp_std::prelude::*;
@@ -85,6 +88,36 @@
 impl<T: Config> Module<T> 
 {
 
+	pub fn check_error(
+		who: &T::AccountId,
+		call: &T::Call
+	) -> Result<bool, TransactionValidityError> where 
+		T::Call: Dispatchable<Info=DispatchInfo>,
+		T::Call: IsSubType<pallet_nft::Call<T>>, 
+		T::Call: IsSubType<pallet_contracts::Call<T>>,
+		T::AccountId: AsRef<[u8]>,
+		T::AccountId: UncheckedFrom<T::Hash>
+		{
+
+			match IsSubType::<pallet_contracts::Call<T>>::is_sub_type(call) {
+				Some(pallet_contracts::Call::call(dest, _value, _gas_limit, _data)) => {
+	
+					let called_contract: T::AccountId = T::Lookup::lookup((*dest).clone()).unwrap_or(T::AccountId::default());
+	
+					let owned_contract = pallet_nft::ContractOwner::<T>::get(called_contract.clone()).as_ref() == Some(who);
+					let white_list_enabled = pallet_nft::ContractWhiteListEnabled::<T>::contains_key(called_contract.clone());
+					  
+					if !owned_contract && white_list_enabled {
+						if !pallet_nft::ContractWhiteList::<T>::contains_key(called_contract.clone(), who) {
+							return Err(InvalidTransaction::Call.into());
+						}
+					}
+					Ok(true)
+				},
+				_ => { Ok(true) },
+			}
+		}
+
 	pub fn withdraw_type(
 		who: &T::AccountId,
 		call: &T::Call
@@ -366,160 +399,4 @@
 
 		None
 	}
-}
-
-// type BalanceOf<T> = <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::Balance;
-
-// /// Require the transactor pay for themselves and maybe include a tip to gain additional priority
-// /// in the queue.
-// #[derive(Encode, Decode, Clone, Eq, PartialEq)]
-// pub struct ChargeTransactionPayment<T: Config>(#[codec(compact)] BalanceOf<T>);
-
-// impl<T: Config + Send + Sync> sp_std::fmt::Debug 
-//     for ChargeTransactionPayment<T>
-// {
-// 	#[cfg(feature = "std")]
-// 	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
-// 		write!(f, "ChargeTransactionPayment<{:?}>", self.0)
-// 	}
-// 	#[cfg(not(feature = "std"))]
-// 	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
-// 		Ok(())
-// 	}
-// }
-
-// impl<T: Config> ChargeTransactionPayment<T>
-// where
-// 	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,
-//     BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
-//     T::AccountId: AsRef<[u8]>,
-//     T::AccountId: UncheckedFrom<T::Hash>,
-// {
-//     fn traditional_fee(
-//         len: usize,
-//         info: &DispatchInfoOf<T::Call>,
-//         tip: BalanceOf<T>,
-//     ) -> BalanceOf<T>
-//     where
-//         T::Call: Dispatchable<Info = DispatchInfo>,
-//     {
-//         <pallet_transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
-//     }
-
-// 	fn get_priority(len: usize, info: &DispatchInfoOf<T::Call>, final_fee: BalanceOf<T>) -> TransactionPriority {
-//         let weight_saturation = T::BlockWeights::get().max_block / info.weight.max(1);
-//         let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Normal);
-//         let len_saturation = max_block_length as u64 / (len as u64).max(1);
-//         let coefficient: BalanceOf<T> = weight_saturation
-//             .min(len_saturation)
-//             .saturated_into::<BalanceOf<T>>();
-//         final_fee
-//             .saturating_mul(coefficient)
-//             .saturated_into::<TransactionPriority>()
-//     }
-
-//     fn withdraw_fee(
-//         &self,
-//         who: &T::AccountId,
-//         call: &T::Call,
-//         info: &DispatchInfoOf<T::Call>,
-//         len: usize,
-// 	) -> Result<
-// 		(
-// 			BalanceOf<T>,
-// 			<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,
-// 		),
-// 		TransactionValidityError,
-// 	> {
-//         let tip = self.0;
-
-//         let fee = Self::traditional_fee(len, info, tip);
-
-//         // Only mess with balances if fee is not zero.
-//         if fee.is_zero() {
-//             return <<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(who, call, info, fee, tip)
-// 			.map(|i| (fee, i));
-//         }
-
-//         // Determine who is paying transaction fee based on ecnomic model
-// 		// Parse call to extract collection ID and access collection sponsor
-		
-// 		let sponsor = pallet_nft_transaction_payment::<T>::withdraw_type(who, call);
-// 		//let sponsor = Self::Module::<T>::withdraw_type(who, call);;
-// 		// <pallet_nft_transaction_payment::Module<T>>::withdraw_type(who, call);
-
-//         let who_pays_fee = sponsor.unwrap_or_else(|| who.clone());
-
-// 		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::withdraw_fee(&who_pays_fee, call, info, fee, tip)
-// 			.map(|i| (fee, i))
-//     }
-// }
-
-
-// impl<T: Config + Send + Sync> SignedExtension
-//     for ChargeTransactionPayment<T>
-// where
-//     BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
-// 	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<pallet_nft::Call<T>> + IsSubType<pallet_contracts::Call<T>>,
-//     T::AccountId: AsRef<[u8]>,
-//     T::AccountId: UncheckedFrom<T::Hash>,
-// {
-//     const IDENTIFIER: &'static str = "ChargeTransactionPayment";
-//     type AccountId = T::AccountId;
-//     type Call = T::Call;
-//     type AdditionalSigned = ();
-//     type Pre = (
-//         // tip
-//         BalanceOf<T>,
-//         // who pays fee
-//         Self::AccountId,
-// 		// imbalance resulting from withdrawing the fee
-// 		<<T as pallet_transaction_payment::Config>::OnChargeTransaction as pallet_transaction_payment::OnChargeTransaction<T>>::LiquidityInfo,
-//     );
-//     fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
-//         Ok(())
-//     }
-
-//     fn validate(
-//         &self,
-//         who: &Self::AccountId,
-//         call: &Self::Call,
-//         info: &DispatchInfoOf<Self::Call>,
-//         len: usize,
-//     ) -> TransactionValidity {
-// 		let (fee, _) = self.withdraw_fee(who, call, info, len)?;
-// 		Ok(ValidTransaction {
-// 			priority: Self::get_priority(len, info, fee),
-// 			..Default::default()
-// 		})
-//     }
-
-//     fn pre_dispatch(
-//         self,
-//         who: &Self::AccountId,
-//         call: &Self::Call,
-//         info: &DispatchInfoOf<Self::Call>,
-//         len: usize,
-//     ) -> Result<Self::Pre, TransactionValidityError> {
-//         let (_fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
-//         Ok((self.0, who.clone(), imbalance))
-//     }
-
-//     fn post_dispatch(
-//         pre: Self::Pre,
-//         info: &DispatchInfoOf<Self::Call>,
-//         post_info: &PostDispatchInfoOf<Self::Call>,
-//         len: usize,
-//         _result: &DispatchResult,
-//     ) -> Result<(), TransactionValidityError> {
-// 		let (tip, who, imbalance) = pre;
-// 		let actual_fee = pallet_transaction_payment::Module::<T>::compute_actual_fee(
-// 			len as u32,
-// 			info,
-// 			post_info,
-// 			tip,
-// 		);
-// 		<T as pallet_transaction_payment::Config>::OnChargeTransaction::correct_and_deposit_fee(&who, info, post_info, actual_fee, tip, imbalance)?;
-// 		Ok(())
-//     }
-// }
\ No newline at end of file
+}
\ No newline at end of file
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -32,10 +32,11 @@
 
 use frame_system::{self as system, ensure_signed, ensure_root};
 use sp_runtime::sp_std::prelude::Vec;
+use core::ops::{Deref, DerefMut};
 use nft_data_structs::{
     MAX_DECIMAL_POINTS, MAX_SPONSOR_TIMEOUT, MAX_TOKEN_OWNERSHIP, MAX_REFUNGIBLE_PIECES,
 	AccessMode, ChainLimits, Collection, CreateItemData, CollectionLimits,
-    CollectionId, CollectionMode, CollectionHandle, TokenId, 
+    CollectionId, CollectionMode, TokenId, 
     SchemaVersion, SponsorshipState, Ownership,
     NftItemType, FungibleItemType, ReFungibleItemType
 };
@@ -164,7 +165,25 @@
 	}
 }
 
-// + pallet_transaction_payment::Config  + pallet_nft_transaction_payment::Config + pallet_contracts::Config
+pub struct CollectionHandle<T: frame_system::Config> {
+    pub id: CollectionId,
+    pub collection: Collection<T>,
+}
+
+impl<T: frame_system::Config> Deref for CollectionHandle<T> {
+    type Target = Collection<T>;
+
+    fn deref(&self) -> &Self::Target {
+        &self.collection
+    }
+}
+
+impl<T: frame_system::Config> DerefMut for CollectionHandle<T> {
+    fn deref_mut(&mut self) -> &mut Self::Target {
+        &mut self.collection
+    }
+}
+
 
 
 pub trait Config: system::Config + Sized {
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -102,7 +102,7 @@
 	/// Not strictly enforced, but used for weight estimation.
 	type MaxScheduledPerBlock: Get<u32>;
 
-	/// TODO
+	/// Sponsoring function
 	type Sponsoring: SponsoringResolve<Self::AccountId, <Self as Config>::Call>;
 
 	/// Weight information for extrinsics in this pallet.
@@ -230,8 +230,7 @@
 		///     - Write: Agenda
 		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls
 		/// # </weight>
-		// #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
-		#[weight = 0]
+		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
 		fn schedule(origin,
 			when: T::BlockNumber,
 			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
@@ -367,7 +366,7 @@
 			}
 			queued.sort_by_key(|(_, s)| s.priority);
 			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)
-			let mut total_weight: Weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get());
+			let mut total_weight: Weight = 0;
 			queued.into_iter()
 				.enumerate()
 				.scan(base_weight, |cumulative_weight, (order, (index, s))| {
@@ -407,7 +406,7 @@
 						).into();
 						let sender = ensure_signed(origin).unwrap_or(T::AccountId::default());
 						let who_will_pay = T::Sponsoring::resolve(&sender, &s.call.clone()).unwrap_or(
-							T::AccountId::default());
+							sender);
 						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
 						let r = s.call.clone().dispatch(sponsor.into());
 						let maybe_id = s.maybe_id.clone();
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -13,7 +13,8 @@
 
 // Pallets that must always be present
 const requiredPallets = [
-  'nft', 'inflation', 'balances', 'contracts', 'randomnesscollectiveflip', 'system', 'timestamp', 'transactionpayment', 'treasury', 'vesting'
+  'nft', 'inflation', 'balances', 'contracts', 'randomnesscollectiveflip', 'system', 'timestamp', 'transactionpayment', 'treasury', 'vesting',
+  'scheduler', 'nftpayment', 'charging'
 ];
 
 // Pallets that depend on consensus and governance configuration
addedtests/src/scheduler.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/scheduler.test.ts
@@ -0,0 +1,94 @@
+//
+// This file is subject to the terms and conditions defined in
+// file 'LICENSE', which is part of this source code package.
+//
+
+import { IKeyringPair } from '@polkadot/types/types';
+import chai from 'chai';
+import chaiAsPromised from 'chai-as-promised';
+import privateKey from './substrate/privateKey';
+import usingApi from './substrate/substrate-api';
+import {
+  createItemExpectSuccess,
+  createCollectionExpectSuccess,
+  destroyCollectionExpectSuccess,
+  findNotExistingCollection,
+  queryCollectionExpectSuccess,
+  setOffchainSchemaExpectFailure,
+  setOffchainSchemaExpectSuccess,
+  transferExpectSuccess,
+  scheduleTransferExpectSuccess,
+  setCollectionSponsorExpectSuccess,
+  confirmSponsorshipExpectSuccess
+} from './util/helpers';
+
+
+chai.use(chaiAsPromised);
+const expect = chai.expect;
+
+const DATA = [1, 2, 3, 4];
+
+describe('Integration Test scheduler base transaction', () => {
+  let alice: IKeyringPair;
+
+  before(async () => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+    });
+  });
+
+  it('User can transfer owned token with delay (scheduler)', async () => {
+    await usingApi(async (api) => {
+      const Alice = privateKey('//Alice');
+      const Bob = privateKey('//Bob');
+      // nft
+      const nftCollectionId = await createCollectionExpectSuccess();
+      const newNftTokenId = await createItemExpectSuccess(Alice, nftCollectionId, 'NFT');
+      await setCollectionSponsorExpectSuccess(nftCollectionId, Alice.address);
+      await confirmSponsorshipExpectSuccess(nftCollectionId);
+
+      await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, Alice, Bob, 1, 'NFT');
+    });
+  });
+
+  
+});
+
+// describe('Negative Integration Test setOffchainSchema', () => {
+//   let alice: IKeyringPair;
+//   let bob: IKeyringPair;
+
+//   let validCollectionId: number;
+
+//   before(async () => {
+//     await usingApi(async () => {
+//       alice = privateKey('//Alice');
+//       bob = privateKey('//Bob');
+
+//       validCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+//     });
+//   });
+
+//   it('fails on not existing collection id', async () => {
+//     const nonExistingCollectionId = await usingApi(findNotExistingCollection);
+
+//     await setOffchainSchemaExpectFailure(alice, nonExistingCollectionId, DATA);
+//   });
+
+//   it('fails on destroyed collection id', async () => {
+//     const destroyedCollectionId = await createCollectionExpectSuccess({ mode: { type: 'NFT' } });
+//     await destroyCollectionExpectSuccess(destroyedCollectionId);
+
+//     await setOffchainSchemaExpectFailure(alice, destroyedCollectionId, DATA);
+//   });
+
+//   it('fails on too long data', async () => {
+//     const tooLongData = new Array(4097).fill(0xff);
+
+//     await setOffchainSchemaExpectFailure(alice, validCollectionId, tooLongData);
+//   });
+
+//   it('fails on execution by non-owner', async () => {
+//     await setOffchainSchemaExpectFailure(bob, validCollectionId, DATA);
+//   });
+// });
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  recipient: string;40}4142interface TransferResult {43  success: boolean;44  collectionId: number;45  itemId: number;46  sender: string;47  recipient: string;48  value: bigint;49}5051interface IReFungibleOwner {52  Fraction: BN;53  Owner: number[];54}5556interface ITokenDataType {57  Owner: number[];58  ConstData: number[];59  VariableData: number[];60}6162interface IFungibleTokenDataType {63  Value: BN;64}6566interface IGetMessage {67  checkMsgNftMethod: string;68  checkMsgTrsMethod: string;69  checkMsgSysMethod: string;70}7172export interface IReFungibleTokenDataType {73  Owner: IReFungibleOwner[];74  ConstData: number[];75  VariableData: number[];76}7778export function nftEventMessage(events: EventRecord[]): IGetMessage {79  let checkMsgNftMethod: string = '';80  let checkMsgTrsMethod: string = '';81  let checkMsgSysMethod: string = '';82  events.forEach(({ event: { method, section } }) => {83    if (section === 'nft') {84      checkMsgNftMethod = method;85    } else if (section === 'treasury') {86      checkMsgTrsMethod = method;87    } else if (section === 'system') {88      checkMsgSysMethod = method;89    } else { return null; }90  });91  const result: IGetMessage = {92    checkMsgNftMethod,93    checkMsgTrsMethod,94    checkMsgSysMethod,95  };96  return result;97}9899export function getGenericResult(events: EventRecord[]): GenericResult {100  const result: GenericResult = {101    success: false,102  };103  events.forEach(({ phase, event: { data, method, section } }) => {104    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);105    if (method === 'ExtrinsicSuccess') {106      result.success = true;107    }108  });109  return result;110}111112113114export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {115  let success = false;116  let collectionId: number = 0;117  events.forEach(({ phase, event: { data, method, section } }) => {118    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);119    if (method == 'ExtrinsicSuccess') {120      success = true;121    } else if ((section == 'nft')  && (method == 'CollectionCreated')) {122      collectionId = parseInt(data[0].toString());123    }124  });125  const result: CreateCollectionResult = {126    success,127    collectionId,128  };129  return result;130}131132export function getCreateItemResult(events: EventRecord[]): CreateItemResult {133  let success = false;134  let collectionId: number = 0;135  let itemId: number = 0;136  let recipient: string = '';137  events.forEach(({ phase, event: { data, method, section } }) => {138    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);139    if (method == 'ExtrinsicSuccess') {140      success = true;141    } else if ((section == 'nft') && (method == 'ItemCreated')) {142      collectionId = parseInt(data[0].toString());143      itemId = parseInt(data[1].toString());144      recipient = data[2].toString();145    }146  });147  const result: CreateItemResult = {148    success,149    collectionId,150    itemId,151    recipient,152  };153  return result;154}155156export function getTransferResult(events: EventRecord[]): TransferResult {157  const result: TransferResult = {158    success: false,159    collectionId: 0,160    itemId: 0,161    sender: '',162    recipient: '',163    value: 0n,164  };165166  events.forEach(({event: {data, method, section}}) => {167    if (method === 'ExtrinsicSuccess') {168      result.success = true;169    } else if (section === 'nft' && method === 'Transfer') {170      result.collectionId = +data[0].toString();171      result.itemId = +data[1].toString();172      result.sender = data[2].toString();173      result.recipient = data[3].toString();174      result.value = BigInt(data[4].toString());175    }176  });177178  return result;179}180181interface Invalid {182  type: 'Invalid';183}184185interface Nft {186  type: 'NFT';187}188189interface Fungible {190  type: 'Fungible';191  decimalPoints: number;192}193194interface ReFungible {195  type: 'ReFungible';196}197198type CollectionMode = Nft | Fungible | ReFungible | Invalid;199200export type CreateCollectionParams = {201  mode: CollectionMode,202  name: string,203  description: string,204  tokenPrefix: string,205};206207const defaultCreateCollectionParams: CreateCollectionParams = {208  description: 'description',209  mode: { type: 'NFT' },210  name: 'name',211  tokenPrefix: 'prefix',212}213214export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {215  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};216217  let collectionId: number = 0;218  await usingApi(async (api) => {219    // Get number of collections before the transaction220    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);221222    // Run the CreateCollection transaction223    const alicePrivateKey = privateKey('//Alice');224225    let modeprm = {};226    if (mode.type === 'NFT') {227      modeprm = {nft: null};228    } else if (mode.type === 'Fungible') {229      modeprm = {fungible: mode.decimalPoints};230    } else if (mode.type === 'ReFungible') {231      modeprm = {refungible: null};232    } else if (mode.type === 'Invalid') {233      modeprm = {invalid: null};234    }235236    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);237    const events = await submitTransactionAsync(alicePrivateKey, tx);238    const result = getCreateCollectionResult(events);239240    // Get number of collections after the transaction241    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);242243    // Get the collection244    const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();245246    // What to expect247    // tslint:disable-next-line:no-unused-expression248    expect(result.success).to.be.true;249    expect(result.collectionId).to.be.equal(BcollectionCount);250    // tslint:disable-next-line:no-unused-expression251    expect(collection).to.be.not.null;252    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');253    expect(collection.Owner).to.be.equal(alicesPublicKey);254    expect(utf16ToStr(collection.Name)).to.be.equal(name);255    expect(utf16ToStr(collection.Description)).to.be.equal(description);256    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);257258    collectionId = result.collectionId;259  });260261  return collectionId;262}263264export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {265  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};266267  let modeprm = {};268  if (mode.type === 'NFT') {269    modeprm = {nft: null};270  } else if (mode.type === 'Fungible') {271    modeprm = {fungible: mode.decimalPoints};272  } else if (mode.type === 'ReFungible') {273    modeprm = {refungible: null};274  } else if (mode.type === 'Invalid') {275    modeprm = {invalid: null};276  }277278  await usingApi(async (api) => {279    // Get number of collections before the transaction280    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());281282    // Run the CreateCollection transaction283    const alicePrivateKey = privateKey('//Alice');284    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);285    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;286    const result = getCreateCollectionResult(events);287288    // Get number of collections after the transaction289    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());290291    // What to expect292    // tslint:disable-next-line:no-unused-expression293    expect(result.success).to.be.false;294    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');295  });296}297298export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {299  let bal = new BigNumber(0);300  let unused;301  do {302    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;303    const keyring = new Keyring({ type: 'sr25519' });304    unused = keyring.addFromUri(`//${randomSeed}`);305    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());306  } while (bal.toFixed() != '0');307  return unused;308}309310export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {311  return await usingApi(async (api) => {312    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;313    return BigInt(bn.toString());314  });315}316317export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {318  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));319}320321export async function findNotExistingCollection(api: ApiPromise): Promise<number> {322  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;323  const newCollection: number = totalNumber + 1;324  return newCollection;325}326327function getDestroyResult(events: EventRecord[]): boolean {328  let success: boolean = false;329  events.forEach(({ phase, event: { data, method, section } }) => {330    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);331    if (method == 'ExtrinsicSuccess') {332      success = true;333    }334  });335  return success;336}337338export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {339  await usingApi(async (api) => {340    // Run the DestroyCollection transaction341    const alicePrivateKey = privateKey(senderSeed);342    const tx = api.tx.nft.destroyCollection(collectionId);343    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;344  });345}346347export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {348  await usingApi(async (api) => {349    // Run the DestroyCollection transaction350    const alicePrivateKey = privateKey(senderSeed);351    const tx = api.tx.nft.destroyCollection(collectionId);352    const events = await submitTransactionAsync(alicePrivateKey, tx);353    const result = getDestroyResult(events);354355    // Get the collection356    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();357358    // What to expect359    expect(result).to.be.true;360    expect(collection).to.be.null;361  });362}363364export async function queryCollectionLimits(collectionId: number) {365  return await usingApi(async (api) => {366    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;367  });368}369370export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {371  await usingApi(async (api) => {372    const oldLimits = await queryCollectionLimits(collectionId);373    const newLimits = { ...oldLimits as any, ...limits };374    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);375    const events = await submitTransactionAsync(sender, tx);376    const result = getGenericResult(events);377378    expect(result.success).to.be.true;379  });380}381382export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {383  await usingApi(async (api) => {384    const oldLimits = await queryCollectionLimits(collectionId);385    const newLimits = { ...oldLimits as any, ...limits };386    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);387    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;388    const result = getGenericResult(events);389390    expect(result.success).to.be.false;391  });392}393394export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {395  await usingApi(async (api) => {396397    // Run the transaction398    const alicePrivateKey = privateKey('//Alice');399    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);400    const events = await submitTransactionAsync(alicePrivateKey, tx);401    const result = getGenericResult(events);402403    // Get the collection404    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();405406    // What to expect407    expect(result.success).to.be.true;408    expect(collection.Sponsorship).to.deep.equal({409      Unconfirmed: sponsor.toString(),410    });411  });412}413414export async function removeCollectionSponsorExpectSuccess(collectionId: number) {415  await usingApi(async (api) => {416417    // Run the transaction418    const alicePrivateKey = privateKey('//Alice');419    const tx = api.tx.nft.removeCollectionSponsor(collectionId);420    const events = await submitTransactionAsync(alicePrivateKey, tx);421    const result = getGenericResult(events);422423    // Get the collection424    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();425426    // What to expect427    expect(result.success).to.be.true;428    expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });429  });430}431432export async function removeCollectionSponsorExpectFailure(collectionId: number) {433  await usingApi(async (api) => {434435    // Run the transaction436    const alicePrivateKey = privateKey('//Alice');437    const tx = api.tx.nft.removeCollectionSponsor(collectionId);438    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;439  });440}441442export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {443  await usingApi(async (api) => {444445    // Run the transaction446    const alicePrivateKey = privateKey(senderSeed);447    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);448    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;449  });450}451452export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {453  await usingApi(async (api) => {454455    // Run the transaction456    const sender = privateKey(senderSeed);457    const tx = api.tx.nft.confirmSponsorship(collectionId);458    const events = await submitTransactionAsync(sender, tx);459    const result = getGenericResult(events);460461    // Get the collection462    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();463464    // What to expect465    expect(result.success).to.be.true;466    expect(collection.Sponsorship).to.be.deep.equal({467      Confirmed: sender.address,468    });469  });470}471472473export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed: string = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const sender = privateKey(senderSeed);478    const tx = api.tx.nft.confirmSponsorship(collectionId);479    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;480  });481}482483export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {484  await usingApi(async (api) => {485    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);486    const events = await submitTransactionAsync(sender, tx);487    const result = getGenericResult(events);488489    expect(result.success).to.be.true;490  });491}492493export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {494  await usingApi(async (api) => {495    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);496    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;497    const result = getGenericResult(events);498499    expect(result.success).to.be.false;500  });501}502503export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {504  await usingApi(async (api) => {505    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);506    const events = await submitTransactionAsync(sender, tx);507    const result = getGenericResult(events);508509    expect(result.success).to.be.true;510  });511}512513export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {514  await usingApi(async (api) => {515    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);516    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;517    const result = getGenericResult(events);518519    expect(result.success).to.be.false;520  });521}522523export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {524  await usingApi(async (api) => {525    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);526    const events = await submitTransactionAsync(sender, tx);527    const result = getGenericResult(events);528529    expect(result.success).to.be.true;530  });531}532533export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {534  let whitelisted: boolean = false;535  await usingApi(async (api) => {536    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;537  });538  return whitelisted;539}540541export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {542  await usingApi(async (api) => {543    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);544    const events = await submitTransactionAsync(sender, tx);545    const result = getGenericResult(events);546547    expect(result.success).to.be.true;548  });549}550551export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {552  await usingApi(async (api) => {553    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);554    const events = await submitTransactionAsync(sender, tx);555    const result = getGenericResult(events);556557    expect(result.success).to.be.true;558  });559}560561export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {562  await usingApi(async (api) => {563    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);564    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;565    const result = getGenericResult(events);566567    expect(result.success).to.be.false;568  });569}570571export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {572  await usingApi(async (api) => {573    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));574    const events = await submitTransactionAsync(sender, tx);575    const result = getGenericResult(events);576577    expect(result.success).to.be.true;578  });579}580581export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {582  await usingApi(async (api) => {583    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));584    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;585  });586}587588export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {589  await usingApi(async (api) => {590    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));591    const events = await submitTransactionAsync(sender, tx);592    const result = getGenericResult(events);593594    expect(result.success).to.be.true;595  });596}597598export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {599  await usingApi(async (api) => {600    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));601    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;602  });603}604605export interface CreateFungibleData {606  readonly Value: bigint;607}608609export interface CreateReFungibleData { }610export interface CreateNftData { }611612export type CreateItemData = {613  NFT: CreateNftData;614} | {615  Fungible: CreateFungibleData;616} | {617  ReFungible: CreateReFungibleData;618};619620export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {621  await usingApi(async (api) => {622    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);623    const events = await submitTransactionAsync(owner, tx);624    const result = getGenericResult(events);625    // Get the item626    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();627    // What to expect628    // tslint:disable-next-line:no-unused-expression629    expect(result.success).to.be.true;630    // tslint:disable-next-line:no-unused-expression631    expect(item).to.be.null;632  });633}634635export async function636approveExpectSuccess(collectionId: number,637                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {638  await usingApi(async (api: ApiPromise) => {639    const allowanceBefore =640      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;641    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);642    const events = await submitTransactionAsync(owner, approveNftTx);643    const result = getCreateItemResult(events);644    // tslint:disable-next-line:no-unused-expression645    expect(result.success).to.be.true;646    const allowanceAfter =647      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;648    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());649  });650}651652export async function653transferFromExpectSuccess(collectionId: number,654                          tokenId: number,655                          accountApproved: IKeyringPair,656                          accountFrom: IKeyringPair,657                          accountTo: IKeyringPair,658                          value: number | bigint = 1,659                          type: string = 'NFT') {660  await usingApi(async (api: ApiPromise) => {661    let balanceBefore = new BN(0);662    if (type === 'Fungible') {663      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;664    }665    const transferFromTx = await api.tx.nft.transferFrom(666      accountFrom.address, accountTo.address, collectionId, tokenId, value);667    const events = await submitTransactionAsync(accountApproved, transferFromTx);668    const result = getCreateItemResult(events);669    // tslint:disable-next-line:no-unused-expression670    expect(result.success).to.be.true;671    if (type === 'NFT') {672      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;673      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);674    }675    if (type === 'Fungible') {676      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;677      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());678    }679    if (type === 'ReFungible') {680      const nftItemData =681        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;682      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);683      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);684    }685  });686}687688export async function689transferFromExpectFail(collectionId: number,690                       tokenId: number,691                       accountApproved: IKeyringPair,692                       accountFrom: IKeyringPair,693                       accountTo: IKeyringPair,694                       value: number | bigint = 1) {695  await usingApi(async (api: ApiPromise) => {696    const transferFromTx = await api.tx.nft.transferFrom(697      accountFrom.address, accountTo.address, collectionId, tokenId, value);698    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;699    const result = getCreateCollectionResult(events);700    // tslint:disable-next-line:no-unused-expression701    expect(result.success).to.be.false;702  });703}704705export async function706transferExpectSuccess(collectionId: number,707                      tokenId: number,708                      sender: IKeyringPair,709                      recipient: IKeyringPair,710                      value: number | bigint = 1,711                      type: string = 'NFT') {712  await usingApi(async (api: ApiPromise) => {713    let balanceBefore = new BN(0);714    if (type === 'Fungible') {715      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;716    }717    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);718    const events = await submitTransactionAsync(sender, transferTx);719    const result = getTransferResult(events);720    // tslint:disable-next-line:no-unused-expression721    expect(result.success).to.be.true;722    expect(result.collectionId).to.be.equal(collectionId);723    expect(result.itemId).to.be.equal(tokenId);724    expect(result.sender).to.be.equal(sender.address);725    expect(result.recipient).to.be.equal(recipient.address);726    expect(result.value.toString()).to.be.equal(value.toString());727    if (type === 'NFT') {728      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;729      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);730    }731    if (type === 'Fungible') {732      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;733      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());734    }735    if (type === 'ReFungible') {736      const nftItemData =737        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;738      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);739      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());740    }741  });742}743744export async function745transferExpectFail(collectionId: number,746                   tokenId: number,747                   sender: IKeyringPair,748                   recipient: IKeyringPair,749                   value: number | bigint = 1,750                   type: string = 'NFT') {751  await usingApi(async (api: ApiPromise) => {752    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);753    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;754    if (events && Array.isArray(events)) {755      const result = getCreateCollectionResult(events);756      // tslint:disable-next-line:no-unused-expression757      expect(result.success).to.be.false;758    }759  });760}761762export async function763approveExpectFail(collectionId: number,764                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {765  await usingApi(async (api: ApiPromise) => {766    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);767    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;768    const result = getCreateCollectionResult(events);769    // tslint:disable-next-line:no-unused-expression770    expect(result.success).to.be.false;771  });772}773774export async function getFungibleBalance(775  collectionId: number,776  owner: string,777) {778  return await usingApi(async (api) => {779    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};780    return BigInt(response.Value);781  });782}783784export async function createFungibleItemExpectSuccess(785  sender: IKeyringPair,786  collectionId: number,787  data: CreateFungibleData,788  owner: string = sender.address,789) {790  return await usingApi(async (api) => {791    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });792793    const events = await submitTransactionAsync(sender, tx);794    const result = getCreateItemResult(events);795796    expect(result.success).to.be.true;797    return result.itemId;798  });799}800801export async function createItemExpectSuccess(802  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {803  let newItemId: number = 0;804  await usingApi(async (api) => {805    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);806    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();807    const AItemBalance = new BigNumber(Aitem.Value);808809    if (owner === '') {810      owner = sender.address;811    }812813    let tx;814    if (createMode === 'Fungible') {815      const createData = {fungible: {value: 10}};816      tx = api.tx.nft.createItem(collectionId, owner, createData);817    } else if (createMode === 'ReFungible') {818      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};819      tx = api.tx.nft.createItem(collectionId, owner, createData);820    } else {821      tx = api.tx.nft.createItem(collectionId, owner, createMode);822    }823    const events = await submitTransactionAsync(sender, tx);824    const result = getCreateItemResult(events);825826    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);827    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();828    const BItemBalance = new BigNumber(Bitem.Value);829830    // What to expect831    // tslint:disable-next-line:no-unused-expression832    expect(result.success).to.be.true;833    if (createMode === 'Fungible') {834      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);835    } else {836      expect(BItemCount).to.be.equal(AItemCount + 1);837    }838    expect(collectionId).to.be.equal(result.collectionId);839    expect(BItemCount).to.be.equal(result.itemId);840    expect(owner).to.be.equal(result.recipient);841    newItemId = result.itemId;842  });843  return newItemId;844}845846export async function createItemExpectFailure(847  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {848  await usingApi(async (api) => {849    const tx = api.tx.nft.createItem(collectionId, owner, createMode);850    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;851    const result = getCreateItemResult(events);852853    expect(result.success).to.be.false;854  });855}856857export async function setPublicAccessModeExpectSuccess(858  sender: IKeyringPair, collectionId: number,859  accessMode: 'Normal' | 'WhiteList',860) {861  await usingApi(async (api) => {862863    // Run the transaction864    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);865    const events = await submitTransactionAsync(sender, tx);866    const result = getGenericResult(events);867868    // Get the collection869    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();870871    // What to expect872    // tslint:disable-next-line:no-unused-expression873    expect(result.success).to.be.true;874    expect(collection.Access).to.be.equal(accessMode);875  });876}877878export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {879  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');880}881882export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {883  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');884}885886export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {887  await usingApi(async (api) => {888889    // Run the transaction890    const tx = api.tx.nft.setMintPermission(collectionId, enabled);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.MintMode).to.be.equal(enabled);901  });902}903904export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {905  await setMintPermissionExpectSuccess(sender, collectionId, true);906}907908export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {909  await usingApi(async (api) => {910    // Run the transaction911    const tx = api.tx.nft.setMintPermission(collectionId, enabled);912    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;913    const result = getCreateCollectionResult(events);914    // tslint:disable-next-line:no-unused-expression915    expect(result.success).to.be.false;916  });917}918919export async function isWhitelisted(collectionId: number, address: string) {920  let whitelisted: boolean = false;921  await usingApi(async (api) => {922    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;923  });924  return whitelisted;925}926927export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {928  await usingApi(async (api) => {929930    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();931932    // Run the transaction933    const tx = api.tx.nft.addToWhiteList(collectionId, address);934    const events = await submitTransactionAsync(sender, tx);935    const result = getGenericResult(events);936937    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();938939    // What to expect940    // tslint:disable-next-line:no-unused-expression941    expect(result.success).to.be.true;942    // tslint:disable-next-line: no-unused-expression943    expect(whiteListedBefore).to.be.false;944    // tslint:disable-next-line: no-unused-expression945    expect(whiteListedAfter).to.be.true;946  });947}948949export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {950  await usingApi(async (api) => {951    // Run the transaction952    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);953    const events = await submitTransactionAsync(sender, tx);954    const result = getGenericResult(events);955956    // What to expect957    // tslint:disable-next-line:no-unused-expression958    expect(result.success).to.be.true;959  });960}961962export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {963  await usingApi(async (api) => {964    // Run the transaction965    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);966    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;967    const result = getGenericResult(events);968969    // What to expect970    // tslint:disable-next-line:no-unused-expression971    expect(result.success).to.be.false;972  });973}974975export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)976  : Promise<ICollectionInterface | null> => {977  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;978};979980export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {981  // set global object - collectionsCount982  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();983};984985export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {986  return await usingApi(async (api) => {987    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;988  });989}
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, BlockNumber, Call, 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';20import { Compact, Option, Raw, Vec } from '@polkadot/types/codec';21// import { AccountId, AccountIdOf, AccountIndex, Address, AssetId, Balance, BalanceOf, Block, BlockNumber, Call, ChangesTrieConfiguration, Consensus, ConsensusEngineId, Digest, DigestItem, DispatchClass, DispatchInfo, DispatchInfoTo190, EcdsaSignature, Ed25519Signature, Extrinsic, ExtrinsicEra, ExtrinsicPayload, ExtrinsicPayloadUnknown, ExtrinsicPayloadV1, ExtrinsicPayloadV2, ExtrinsicPayloadV3, ExtrinsicPayloadV4, ExtrinsicSignatureV1, ExtrinsicSignatureV2, ExtrinsicSignatureV3, ExtrinsicSignatureV4, ExtrinsicUnknown, ExtrinsicV1, ExtrinsicV2, ExtrinsicV3, ExtrinsicV4, Hash, Header, ImmortalEra, Index, Justification, KeyTypeId, KeyValue, LockIdentifier, LookupSource, LookupTarget, Moment, MortalEra, MultiSignature, Origin, Perbill, Percent, Permill, Perquintill, Phantom, PhantomData, PreRuntime, Seal, SealV0, Signature, SignedBlock, SignerPayload, Sr25519Signature, ValidatorId, Weight, WeightMultiplier } from '@polkadot/types/interfaces/runtime';2223chai.use(chaiAsPromised);24const expect = chai.expect;2526export const U128_MAX = (1n << 128n) - 1n;2728type GenericResult = {29  success: boolean,30};3132interface CreateCollectionResult {33  success: boolean;34  collectionId: number;35}3637interface CreateItemResult {38  success: boolean;39  collectionId: number;40  itemId: number;41  recipient: string;42}4344interface TransferResult {45  success: boolean;46  collectionId: number;47  itemId: number;48  sender: string;49  recipient: string;50  value: bigint;51}5253interface IReFungibleOwner {54  Fraction: BN;55  Owner: number[];56}5758interface ITokenDataType {59  Owner: number[];60  ConstData: number[];61  VariableData: number[];62}6364interface IFungibleTokenDataType {65  Value: BN;66}6768interface IGetMessage {69  checkMsgNftMethod: string;70  checkMsgTrsMethod: string;71  checkMsgSysMethod: string;72}7374export interface IReFungibleTokenDataType {75  Owner: IReFungibleOwner[];76  ConstData: number[];77  VariableData: number[];78}7980export function nftEventMessage(events: EventRecord[]): IGetMessage {81  let checkMsgNftMethod: string = '';82  let checkMsgTrsMethod: string = '';83  let checkMsgSysMethod: string = '';84  events.forEach(({ event: { method, section } }) => {85    if (section === 'nft') {86      checkMsgNftMethod = method;87    } else if (section === 'treasury') {88      checkMsgTrsMethod = method;89    } else if (section === 'system') {90      checkMsgSysMethod = method;91    } else { return null; }92  });93  const result: IGetMessage = {94    checkMsgNftMethod,95    checkMsgTrsMethod,96    checkMsgSysMethod,97  };98  return result;99}100101export function getGenericResult(events: EventRecord[]): GenericResult {102  const result: GenericResult = {103    success: false,104  };105  events.forEach(({ phase, event: { data, method, section } }) => {106    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);107    if (method === 'ExtrinsicSuccess') {108      result.success = true;109    }110  });111  return result;112}113114115116export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {117  let success = false;118  let collectionId: number = 0;119  events.forEach(({ phase, event: { data, method, section } }) => {120    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);121    if (method == 'ExtrinsicSuccess') {122      success = true;123    } else if ((section == 'nft')  && (method == 'CollectionCreated')) {124      collectionId = parseInt(data[0].toString());125    }126  });127  const result: CreateCollectionResult = {128    success,129    collectionId,130  };131  return result;132}133134export function getCreateItemResult(events: EventRecord[]): CreateItemResult {135  let success = false;136  let collectionId: number = 0;137  let itemId: number = 0;138  let recipient: string = '';139  events.forEach(({ phase, event: { data, method, section } }) => {140    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);141    if (method == 'ExtrinsicSuccess') {142      success = true;143    } else if ((section == 'nft') && (method == 'ItemCreated')) {144      collectionId = parseInt(data[0].toString());145      itemId = parseInt(data[1].toString());146      recipient = data[2].toString();147    }148  });149  const result: CreateItemResult = {150    success,151    collectionId,152    itemId,153    recipient,154  };155  return result;156}157158export function getTransferResult(events: EventRecord[]): TransferResult {159  const result: TransferResult = {160    success: false,161    collectionId: 0,162    itemId: 0,163    sender: '',164    recipient: '',165    value: 0n,166  };167168  events.forEach(({event: {data, method, section}}) => {169    if (method === 'ExtrinsicSuccess') {170      result.success = true;171    } else if (section === 'nft' && method === 'Transfer') {172      result.collectionId = +data[0].toString();173      result.itemId = +data[1].toString();174      result.sender = data[2].toString();175      result.recipient = data[3].toString();176      result.value = BigInt(data[4].toString());177    }178  });179180  return result;181}182183interface Invalid {184  type: 'Invalid';185}186187interface Nft {188  type: 'NFT';189}190191interface Fungible {192  type: 'Fungible';193  decimalPoints: number;194}195196interface ReFungible {197  type: 'ReFungible';198}199200type CollectionMode = Nft | Fungible | ReFungible | Invalid;201202export type CreateCollectionParams = {203  mode: CollectionMode,204  name: string,205  description: string,206  tokenPrefix: string,207};208209const defaultCreateCollectionParams: CreateCollectionParams = {210  description: 'description',211  mode: { type: 'NFT' },212  name: 'name',213  tokenPrefix: 'prefix',214}215216export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {217  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};218219  let collectionId: number = 0;220  await usingApi(async (api) => {221    // Get number of collections before the transaction222    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);223224    // Run the CreateCollection transaction225    const alicePrivateKey = privateKey('//Alice');226227    let modeprm = {};228    if (mode.type === 'NFT') {229      modeprm = {nft: null};230    } else if (mode.type === 'Fungible') {231      modeprm = {fungible: mode.decimalPoints};232    } else if (mode.type === 'ReFungible') {233      modeprm = {refungible: null};234    } else if (mode.type === 'Invalid') {235      modeprm = {invalid: null};236    }237238    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);239    const events = await submitTransactionAsync(alicePrivateKey, tx);240    const result = getCreateCollectionResult(events);241242    // Get number of collections after the transaction243    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10);244245    // Get the collection246    const collection: any = (await api.query.nft.collectionById(result.collectionId)).toJSON();247248    // What to expect249    // tslint:disable-next-line:no-unused-expression250    expect(result.success).to.be.true;251    expect(result.collectionId).to.be.equal(BcollectionCount);252    // tslint:disable-next-line:no-unused-expression253    expect(collection).to.be.not.null;254    expect(BcollectionCount).to.be.equal(AcollectionCount + 1, 'Error: NFT collection NOT created.');255    expect(collection.Owner).to.be.equal(alicesPublicKey);256    expect(utf16ToStr(collection.Name)).to.be.equal(name);257    expect(utf16ToStr(collection.Description)).to.be.equal(description);258    expect(hexToStr(collection.TokenPrefix)).to.be.equal(tokenPrefix);259260    collectionId = result.collectionId;261  });262263  return collectionId;264}265266export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {267  const {name, description, mode, tokenPrefix } = {...defaultCreateCollectionParams, ...params};268269  let modeprm = {};270  if (mode.type === 'NFT') {271    modeprm = {nft: null};272  } else if (mode.type === 'Fungible') {273    modeprm = {fungible: mode.decimalPoints};274  } else if (mode.type === 'ReFungible') {275    modeprm = {refungible: null};276  } else if (mode.type === 'Invalid') {277    modeprm = {invalid: null};278  }279280  await usingApi(async (api) => {281    // Get number of collections before the transaction282    const AcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());283284    // Run the CreateCollection transaction285    const alicePrivateKey = privateKey('//Alice');286    const tx = api.tx.nft.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm);287    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const BcollectionCount = parseInt((await api.query.nft.createdCollectionCount()).toString());292293    // What to expect294    // tslint:disable-next-line:no-unused-expression295    expect(result.success).to.be.false;296    expect(BcollectionCount).to.be.equal(AcollectionCount, 'Error: Collection with incorrect data created.');297  });298}299300export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {301  let bal = new BigNumber(0);302  let unused;303  do {304    const randomSeed = 'seed' +  Math.floor(Math.random() * Math.floor(10000)) + seedAddition;305    const keyring = new Keyring({ type: 'sr25519' });306    unused = keyring.addFromUri(`//${randomSeed}`);307    bal = new BigNumber((await api.query.system.account(unused.address)).data.free.toString());308  } while (bal.toFixed() != '0');309  return unused;310}311312export async function getAllowance(collectionId: number, tokenId: number, owner: string, approved: string) {313  return await usingApi(async (api) => {314    const bn = await api.query.nft.allowances(collectionId, [tokenId, owner, approved]) as unknown as BN;315    return BigInt(bn.toString());316  });317}318319export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {320  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));321}322323export async function findNotExistingCollection(api: ApiPromise): Promise<number> {324  const totalNumber = parseInt((await api.query.nft.createdCollectionCount()).toString(), 10) as unknown as number;325  const newCollection: number = totalNumber + 1;326  return newCollection;327}328329function getDestroyResult(events: EventRecord[]): boolean {330  let success: boolean = false;331  events.forEach(({ phase, event: { data, method, section } }) => {332    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);333    if (method == 'ExtrinsicSuccess') {334      success = true;335    }336  });337  return success;338}339340export async function destroyCollectionExpectFailure(collectionId: number, senderSeed: string = '//Alice') {341  await usingApi(async (api) => {342    // Run the DestroyCollection transaction343    const alicePrivateKey = privateKey(senderSeed);344    const tx = api.tx.nft.destroyCollection(collectionId);345    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;346  });347}348349export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {350  await usingApi(async (api) => {351    // Run the DestroyCollection transaction352    const alicePrivateKey = privateKey(senderSeed);353    const tx = api.tx.nft.destroyCollection(collectionId);354    const events = await submitTransactionAsync(alicePrivateKey, tx);355    const result = getDestroyResult(events);356357    // Get the collection358    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();359360    // What to expect361    expect(result).to.be.true;362    expect(collection).to.be.null;363  });364}365366export async function queryCollectionLimits(collectionId: number) {367  return await usingApi(async (api) => {368    return ((await api.query.nft.collectionById(collectionId)).toJSON() as any).Limits;369  });370}371372export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {373  await usingApi(async (api) => {374    const oldLimits = await queryCollectionLimits(collectionId);375    const newLimits = { ...oldLimits as any, ...limits };376    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);377    const events = await submitTransactionAsync(sender, tx);378    const result = getGenericResult(events);379380    expect(result.success).to.be.true;381  });382}383384export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {385  await usingApi(async (api) => {386    const oldLimits = await queryCollectionLimits(collectionId);387    const newLimits = { ...oldLimits as any, ...limits };388    const tx = api.tx.nft.setCollectionLimits(collectionId, newLimits);389    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;390    const result = getGenericResult(events);391392    expect(result.success).to.be.false;393  });394}395396export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string) {397  await usingApi(async (api) => {398399    // Run the transaction400    const alicePrivateKey = privateKey('//Alice');401    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);402    const events = await submitTransactionAsync(alicePrivateKey, tx);403    const result = getGenericResult(events);404405    // Get the collection406    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();407408    // What to expect409    expect(result.success).to.be.true;410    expect(collection.Sponsorship).to.deep.equal({411      Unconfirmed: sponsor.toString(),412    });413  });414}415416export async function removeCollectionSponsorExpectSuccess(collectionId: number) {417  await usingApi(async (api) => {418419    // Run the transaction420    const alicePrivateKey = privateKey('//Alice');421    const tx = api.tx.nft.removeCollectionSponsor(collectionId);422    const events = await submitTransactionAsync(alicePrivateKey, tx);423    const result = getGenericResult(events);424425    // Get the collection426    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();427428    // What to expect429    expect(result.success).to.be.true;430    expect(collection.Sponsorship).to.be.deep.equal({ Disabled: null });431  });432}433434export async function removeCollectionSponsorExpectFailure(collectionId: number) {435  await usingApi(async (api) => {436437    // Run the transaction438    const alicePrivateKey = privateKey('//Alice');439    const tx = api.tx.nft.removeCollectionSponsor(collectionId);440    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;441  });442}443444export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed: string = '//Alice') {445  await usingApi(async (api) => {446447    // Run the transaction448    const alicePrivateKey = privateKey(senderSeed);449    const tx = api.tx.nft.setCollectionSponsor(collectionId, sponsor);450    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;451  });452}453454export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed: string = '//Alice') {455  await usingApi(async (api) => {456457    // Run the transaction458    const sender = privateKey(senderSeed);459    const tx = api.tx.nft.confirmSponsorship(collectionId);460    const events = await submitTransactionAsync(sender, tx);461    const result = getGenericResult(events);462463    // Get the collection464    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();465466    // What to expect467    expect(result.success).to.be.true;468    expect(collection.Sponsorship).to.be.deep.equal({469      Confirmed: sender.address,470    });471  });472}473474475export async function confirmSponsorshipExpectFailure(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    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;482  });483}484485export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {486  await usingApi(async (api) => {487    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);488    const events = await submitTransactionAsync(sender, tx);489    const result = getGenericResult(events);490491    expect(result.success).to.be.true;492  });493}494495export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {496  await usingApi(async (api) => {497    const tx = api.tx.nft.enableContractSponsoring(contractAddress, enable);498    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;499    const result = getGenericResult(events);500501    expect(result.success).to.be.false;502  });503}504505export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {506  await usingApi(async (api) => {507    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);508    const events = await submitTransactionAsync(sender, tx);509    const result = getGenericResult(events);510511    expect(result.success).to.be.true;512  });513}514515export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {516  await usingApi(async (api) => {517    const tx = api.tx.nft.setContractSponsoringRateLimit(contractAddress, rateLimit);518    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;519    const result = getGenericResult(events);520521    expect(result.success).to.be.false;522  });523}524525export async function toggleContractWhitelistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enabled: boolean) {526  await usingApi(async (api) => {527    const tx = api.tx.nft.toggleContractWhiteList(contractAddress, true);528    const events = await submitTransactionAsync(sender, tx);529    const result = getGenericResult(events);530531    expect(result.success).to.be.true;532  });533}534535export async function isWhitelistedInContract(contractAddress: AccountId | string, user: string) {536  let whitelisted: boolean = false;537  await usingApi(async (api) => {538    whitelisted = (await api.query.nft.contractWhiteList(contractAddress, user)).toJSON() as boolean;539  });540  return whitelisted;541}542543export async function addToContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {544  await usingApi(async (api) => {545    const tx = api.tx.nft.addToContractWhiteList(contractAddress, user);546    const events = await submitTransactionAsync(sender, tx);547    const result = getGenericResult(events);548549    expect(result.success).to.be.true;550  });551}552553export async function removeFromContractWhiteListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {554  await usingApi(async (api) => {555    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);556    const events = await submitTransactionAsync(sender, tx);557    const result = getGenericResult(events);558559    expect(result.success).to.be.true;560  });561}562563export async function removeFromContractWhiteListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: string) {564  await usingApi(async (api) => {565    const tx = api.tx.nft.removeFromContractWhiteList(contractAddress, user);566    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;567    const result = getGenericResult(events);568569    expect(result.success).to.be.false;570  });571}572573export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {574  await usingApi(async (api) => {575    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));576    const events = await submitTransactionAsync(sender, tx);577    const result = getGenericResult(events);578579    expect(result.success).to.be.true;580  });581}582583export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {584  await usingApi(async (api) => {585    const tx = api.tx.nft.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));586    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;587  });588}589590export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {591  await usingApi(async (api) => {592    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));593    const events = await submitTransactionAsync(sender, tx);594    const result = getGenericResult(events);595596    expect(result.success).to.be.true;597  });598}599600export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {601  await usingApi(async (api) => {602    const tx = api.tx.nft.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));603    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;604  });605}606607export interface CreateFungibleData {608  readonly Value: bigint;609}610611export interface CreateReFungibleData { }612export interface CreateNftData { }613614export type CreateItemData = {615  NFT: CreateNftData;616} | {617  Fungible: CreateFungibleData;618} | {619  ReFungible: CreateReFungibleData;620};621622export async function burnItemExpectSuccess(owner: IKeyringPair, collectionId: number, tokenId: number, value = 0) {623  await usingApi(async (api) => {624    const tx = api.tx.nft.burnItem(collectionId, tokenId, value);625    const events = await submitTransactionAsync(owner, tx);626    const result = getGenericResult(events);627    // Get the item628    const item: any = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON();629    // What to expect630    // tslint:disable-next-line:no-unused-expression631    expect(result.success).to.be.true;632    // tslint:disable-next-line:no-unused-expression633    expect(item).to.be.null;634  });635}636637export async function638approveExpectSuccess(collectionId: number,639                     tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {640  await usingApi(async (api: ApiPromise) => {641    const allowanceBefore =642      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;643    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);644    const events = await submitTransactionAsync(owner, approveNftTx);645    const result = getCreateItemResult(events);646    // tslint:disable-next-line:no-unused-expression647    expect(result.success).to.be.true;648    const allowanceAfter =649      await api.query.nft.allowances(collectionId, [tokenId, owner.address, approved.address]) as unknown as BN;650    expect(allowanceAfter.sub(allowanceBefore).toString()).to.be.equal(amount.toString());651  });652}653654export async function655transferFromExpectSuccess(collectionId: number,656                          tokenId: number,657                          accountApproved: IKeyringPair,658                          accountFrom: IKeyringPair,659                          accountTo: IKeyringPair,660                          value: number | bigint = 1,661                          type: string = 'NFT') {662  await usingApi(async (api: ApiPromise) => {663    let balanceBefore = new BN(0);664    if (type === 'Fungible') {665      balanceBefore = await api.query.nft.balance(collectionId, accountTo.address) as unknown as BN;666    }667    const transferFromTx = await api.tx.nft.transferFrom(668      accountFrom.address, accountTo.address, collectionId, tokenId, value);669    const events = await submitTransactionAsync(accountApproved, transferFromTx);670    const result = getCreateItemResult(events);671    // tslint:disable-next-line:no-unused-expression672    expect(result.success).to.be.true;673    if (type === 'NFT') {674      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId) as any).unwrap() as ITokenDataType;675      expect(nftItemData.Owner.toString()).to.be.equal(accountTo.address);676    }677    if (type === 'Fungible') {678      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, accountTo.address) as any).Value as unknown as BN;679      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());680    }681    if (type === 'ReFungible') {682      const nftItemData =683        (await api.query.nft.reFungibleItemList(collectionId, tokenId) as any).unwrap() as IReFungibleTokenDataType;684      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(accountTo.address);685      expect(nftItemData.Owner[0].Fraction.toNumber()).to.be.equal(value);686    }687  });688}689690export async function691transferFromExpectFail(collectionId: number,692                       tokenId: number,693                       accountApproved: IKeyringPair,694                       accountFrom: IKeyringPair,695                       accountTo: IKeyringPair,696                       value: number | bigint = 1) {697  await usingApi(async (api: ApiPromise) => {698    const transferFromTx = await api.tx.nft.transferFrom(699      accountFrom.address, accountTo.address, collectionId, tokenId, value);700    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;701    const result = getCreateCollectionResult(events);702    // tslint:disable-next-line:no-unused-expression703    expect(result.success).to.be.false;704  });705}706707async function getBlockNumber(api: ApiPromise): Promise<number> {708  return new Promise<number>(async (resolve, reject) => {709    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {710        unsubscribe();711        resolve(head.number.toNumber());712    });713  });714}715716export async function717scheduleTransferExpectSuccess(collectionId: number,718                      tokenId: number,719                      sender: IKeyringPair,720                      recipient: IKeyringPair,721                      value: number | bigint = 1,722                      type: string = 'NFT') {723  await usingApi(async (api: ApiPromise) => {724    let balanceBefore = new BN(0);725726727    let blockNumber: number | undefined = await getBlockNumber(api);728    let expectedBlockNumber = blockNumber + 2;729730    expect(blockNumber).to.be.greaterThan(0);731    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value); 732    const scheduleTx = await api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx);733734    const events = await submitTransactionAsync(sender, scheduleTx);735736    const sponsorBalanceBefore = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());737    const recipientBalanceBefore = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());738739    const nftItemDataBefore = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;740    expect(nftItemDataBefore.Owner.toString()).to.be.equal(sender.address);741742    // sleep for 2 blocks743    await new Promise(resolve => setTimeout(resolve, 6000 * 2));744745    const sponsorBalanceAfter = new BigNumber((await api.query.system.account(sender.address)).data.free.toString());746    const recipientBalanceAfter = new BigNumber((await api.query.system.account(recipient.address)).data.free.toString());747748    const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;749    expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);750    expect(recipientBalanceAfter.toNumber()).to.be.equal(recipientBalanceBefore.toNumber());751  });752}753754755export async function756transferExpectSuccess(collectionId: number,757                      tokenId: number,758                      sender: IKeyringPair,759                      recipient: IKeyringPair,760                      value: number | bigint = 1,761                      type: string = 'NFT') {762  await usingApi(async (api: ApiPromise) => {763    let balanceBefore = new BN(0);764    if (type === 'Fungible') {765      balanceBefore = await api.query.nft.balance(collectionId, recipient.address) as unknown as BN;766    }767    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);768    const events = await submitTransactionAsync(sender, transferTx);769    const result = getTransferResult(events);770    // tslint:disable-next-line:no-unused-expression771    expect(result.success).to.be.true;772    expect(result.collectionId).to.be.equal(collectionId);773    expect(result.itemId).to.be.equal(tokenId);774    expect(result.sender).to.be.equal(sender.address);775    expect(result.recipient).to.be.equal(recipient.address);776    expect(result.value.toString()).to.be.equal(value.toString());777    if (type === 'NFT') {778      const nftItemData = (await api.query.nft.nftItemList(collectionId, tokenId)).toJSON() as unknown as ITokenDataType;779      expect(nftItemData.Owner.toString()).to.be.equal(recipient.address);780    }781    if (type === 'Fungible') {782      const balanceAfter = (await api.query.nft.fungibleItemList(collectionId, recipient.address) as any).Value as unknown as BN;783      expect(balanceAfter.sub(balanceBefore).toString()).to.be.equal(value.toString());784    }785    if (type === 'ReFungible') {786      const nftItemData =787        (await api.query.nft.reFungibleItemList(collectionId, tokenId)).toJSON() as unknown as IReFungibleTokenDataType;788      expect(nftItemData.Owner[0].Owner.toString()).to.be.equal(recipient.address);789      expect(nftItemData.Owner[0].Fraction.toString()).to.be.equal(value.toString());790    }791  });792}793794export async function795transferExpectFail(collectionId: number,796                   tokenId: number,797                   sender: IKeyringPair,798                   recipient: IKeyringPair,799                   value: number | bigint = 1,800                   type: string = 'NFT') {801  await usingApi(async (api: ApiPromise) => {802    const transferTx = await api.tx.nft.transfer(recipient.address, collectionId, tokenId, value);803    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;804    if (events && Array.isArray(events)) {805      const result = getCreateCollectionResult(events);806      // tslint:disable-next-line:no-unused-expression807      expect(result.success).to.be.false;808    }809  });810}811812export async function813approveExpectFail(collectionId: number,814                  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1) {815  await usingApi(async (api: ApiPromise) => {816    const approveNftTx = await api.tx.nft.approve(approved.address, collectionId, tokenId, amount);817    const events = await expect(submitTransactionExpectFailAsync(owner, approveNftTx)).to.be.rejected;818    const result = getCreateCollectionResult(events);819    // tslint:disable-next-line:no-unused-expression820    expect(result.success).to.be.false;821  });822}823824export async function getFungibleBalance(825  collectionId: number,826  owner: string,827) {828  return await usingApi(async (api) => {829    const response = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON() as unknown as {Value: string};830    return BigInt(response.Value);831  });832}833834export async function createFungibleItemExpectSuccess(835  sender: IKeyringPair,836  collectionId: number,837  data: CreateFungibleData,838  owner: string = sender.address,839) {840  return await usingApi(async (api) => {841    const tx = api.tx.nft.createItem(collectionId, owner, { Fungible: data });842843    const events = await submitTransactionAsync(sender, tx);844    const result = getCreateItemResult(events);845846    expect(result.success).to.be.true;847    return result.itemId;848  });849}850851export async function createItemExpectSuccess(852  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = '') {853  let newItemId: number = 0;854  await usingApi(async (api) => {855    const AItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);856    const Aitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();857    const AItemBalance = new BigNumber(Aitem.Value);858859    if (owner === '') {860      owner = sender.address;861    }862863    let tx;864    if (createMode === 'Fungible') {865      const createData = {fungible: {value: 10}};866      tx = api.tx.nft.createItem(collectionId, owner, createData);867    } else if (createMode === 'ReFungible') {868      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};869      tx = api.tx.nft.createItem(collectionId, owner, createData);870    } else {871      tx = api.tx.nft.createItem(collectionId, owner, createMode);872    }873    const events = await submitTransactionAsync(sender, tx);874    const result = getCreateItemResult(events);875876    const BItemCount = parseInt((await api.query.nft.itemListIndex(collectionId)).toString(), 10);877    const Bitem: any = (await api.query.nft.fungibleItemList(collectionId, owner)).toJSON();878    const BItemBalance = new BigNumber(Bitem.Value);879880    // What to expect881    // tslint:disable-next-line:no-unused-expression882    expect(result.success).to.be.true;883    if (createMode === 'Fungible') {884      expect(BItemBalance.minus(AItemBalance).toNumber()).to.be.equal(10);885    } else {886      expect(BItemCount).to.be.equal(AItemCount + 1);887    }888    expect(collectionId).to.be.equal(result.collectionId);889    expect(BItemCount).to.be.equal(result.itemId);890    expect(owner).to.be.equal(result.recipient);891    newItemId = result.itemId;892  });893  return newItemId;894}895896export async function createItemExpectFailure(897  sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {898  await usingApi(async (api) => {899    const tx = api.tx.nft.createItem(collectionId, owner, createMode);900    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;901    const result = getCreateItemResult(events);902903    expect(result.success).to.be.false;904  });905}906907export async function setPublicAccessModeExpectSuccess(908  sender: IKeyringPair, collectionId: number,909  accessMode: 'Normal' | 'WhiteList',910) {911  await usingApi(async (api) => {912913    // Run the transaction914    const tx = api.tx.nft.setPublicAccessMode(collectionId, accessMode);915    const events = await submitTransactionAsync(sender, tx);916    const result = getGenericResult(events);917918    // Get the collection919    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();920921    // What to expect922    // tslint:disable-next-line:no-unused-expression923    expect(result.success).to.be.true;924    expect(collection.Access).to.be.equal(accessMode);925  });926}927928export async function enableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {929  await setPublicAccessModeExpectSuccess(sender, collectionId, 'WhiteList');930}931932export async function disableWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number) {933  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');934}935936export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {937  await usingApi(async (api) => {938939    // Run the transaction940    const tx = api.tx.nft.setMintPermission(collectionId, enabled);941    const events = await submitTransactionAsync(sender, tx);942    const result = getGenericResult(events);943944    // Get the collection945    const collection: any = (await api.query.nft.collectionById(collectionId)).toJSON();946947    // What to expect948    // tslint:disable-next-line:no-unused-expression949    expect(result.success).to.be.true;950    expect(collection.MintMode).to.be.equal(enabled);951  });952}953954export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {955  await setMintPermissionExpectSuccess(sender, collectionId, true);956}957958export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {959  await usingApi(async (api) => {960    // Run the transaction961    const tx = api.tx.nft.setMintPermission(collectionId, enabled);962    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;963    const result = getCreateCollectionResult(events);964    // tslint:disable-next-line:no-unused-expression965    expect(result.success).to.be.false;966  });967}968969export async function isWhitelisted(collectionId: number, address: string) {970  let whitelisted: boolean = false;971  await usingApi(async (api) => {972    whitelisted = (await api.query.nft.whiteList(collectionId, address)).toJSON() as unknown as boolean;973  });974  return whitelisted;975}976977export async function addToWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {978  await usingApi(async (api) => {979980    const whiteListedBefore = (await api.query.nft.whiteList(collectionId, address)).toJSON();981982    // Run the transaction983    const tx = api.tx.nft.addToWhiteList(collectionId, address);984    const events = await submitTransactionAsync(sender, tx);985    const result = getGenericResult(events);986987    const whiteListedAfter = (await api.query.nft.whiteList(collectionId, address)).toJSON();988989    // What to expect990    // tslint:disable-next-line:no-unused-expression991    expect(result.success).to.be.true;992    // tslint:disable-next-line: no-unused-expression993    expect(whiteListedBefore).to.be.false;994    // tslint:disable-next-line: no-unused-expression995    expect(whiteListedAfter).to.be.true;996  });997}998999export async function removeFromWhiteListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string) {1000  await usingApi(async (api) => {1001    // Run the transaction1002    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1003    const events = await submitTransactionAsync(sender, tx);1004    const result = getGenericResult(events);10051006    // What to expect1007    // tslint:disable-next-line:no-unused-expression1008    expect(result.success).to.be.true;1009  });1010}10111012export async function removeFromWhiteListExpectFailure(sender: IKeyringPair, collectionId: number, address: string) {1013  await usingApi(async (api) => {1014    // Run the transaction1015    const tx = api.tx.nft.removeFromWhiteList(collectionId, address);1016    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1017    const result = getGenericResult(events);10181019    // What to expect1020    // tslint:disable-next-line:no-unused-expression1021    expect(result.success).to.be.false;1022  });1023}10241025export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1026  : Promise<ICollectionInterface | null> => {1027  return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1028};10291030export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1031  // set global object - collectionsCount1032  return (await api.query.nft.createdCollectionCount() as unknown as BN).toNumber();1033};10341035export async function queryCollectionExpectSuccess(collectionId: number): Promise<ICollectionInterface> {1036  return await usingApi(async (api) => {1037    return (await api.query.nft.collectionById(collectionId)).toJSON() as unknown as ICollectionInterface;1038  });1039}