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
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}