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

difftreelog

feat(Scheduler) most critical improvements done, polishing needed

Fahrrader2022-02-21parents: #1f0f713 #58ec388.patch.diff
in: master

6 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6108,7 +6108,7 @@
 [[package]]
 name = "pallet-template-transaction-payment"
 version = "3.0.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
@@ -6272,7 +6272,6 @@
  "parity-scale-codec",
  "scale-info",
  "serde",
- "sp-api",
  "sp-core",
  "sp-io",
  "sp-runtime",
@@ -11313,7 +11312,7 @@
  "chrono",
  "lazy_static",
  "matchers",
- "parking_lot 0.11.2",
+ "parking_lot 0.10.2",
  "regex",
  "serde",
  "serde_json",
@@ -11443,7 +11442,7 @@
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"
 dependencies = [
- "cfg-if 1.0.0",
+ "cfg-if 0.1.10",
  "rand 0.8.4",
  "static_assertions",
 ]
@@ -11812,7 +11811,7 @@
 [[package]]
 name = "up-sponsorship"
 version = "0.1.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
 dependencies = [
  "impl-trait-for-tuples",
 ]
modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -20,11 +20,11 @@
 sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
 frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
 
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
 up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }
 log = { version = "0.4.14", default-features = false }
 
 [dev-dependencies]
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
 substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
 
 [features]
@@ -38,6 +38,7 @@
 	"up-sponsorship/std",
 	"sp-io/std",
 	"sp-std/std",
+	"sp-core/std",
 	"log/std",
 ]
 runtime-benchmarks = [
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -60,6 +60,8 @@
 use sp_runtime::{
 	RuntimeDebug,
 	traits::{Zero, One, BadOrigin, Saturating},
+	transaction_validity::TransactionValidityError,
+	DispatchErrorWithPostInfo,
 };
 use frame_support::{
 	decl_module, decl_storage, decl_event, decl_error,
@@ -69,23 +71,13 @@
 		schedule::{self, DispatchTime},
 		OriginTrait, EnsureOrigin, IsType,
 	},
-	weights::{GetDispatchInfo, Weight},
+	weights::{GetDispatchInfo, Weight, PostDispatchInfo},
 };
 use frame_system::{self as system, ensure_signed};
 pub use weights::WeightInfo;
+use up_sponsorship::SponsorshipHandler;
 use scale_info::TypeInfo;
-use sp_runtime::ApplyExtrinsicResult;
-use sp_runtime::traits::{IdentifyAccount, Verify};
-use sp_runtime::{MultiSignature};
-
-pub trait ApplyExtrinsic<C: Dispatchable> {
-	fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;
-}
-
-/// The address format for describing accounts.
-pub type Signature = MultiSignature;
-pub type Address = sp_runtime::MultiAddress<AccountId, ()>;
-pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
+use sp_core::H160;
 
 /// Our pallet's configuration trait. All our types and constants go in here. If the
 /// pallet is dependent on specific other pallets, then their configuration traits
@@ -122,10 +114,38 @@
 	/// Not strictly enforced, but used for weight estimation.
 	type MaxScheduledPerBlock: Get<u32>;
 
+	/// Sponsoring function.
+	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
+
 	/// Weight information for extrinsics in this pallet.
 	type WeightInfo: WeightInfo;
 
-	type Executor: ApplyExtrinsic<<Self as Config>::Call>;
+	/// The helper type used for custom transaction fee logic.
+	type CallExecutor: DispatchCall<Self, H160>;
+}
+
+/// A Scheduler-Runtime interface for finer payment handling.
+pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
+	/// The type that encodes information that can be passed from pre_dispatch to post-dispatch.
+	type Pre: Default + Codec + Clone + TypeInfo;
+
+	/// Resolve the call dispatch, including any post-dispatch operations.
+	fn dispatch_call(
+		pre_dispatch: Self::Pre,
+		function: <T as Config>::Call,
+	) -> Result<
+		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+		TransactionValidityError,
+	>;
+
+	/// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).
+	fn pre_dispatch(
+		signer: T::AccountId,
+		function: <T as Config>::Call,
+	) -> Result<Self::Pre, TransactionValidityError>;
+
+	/// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).
+	fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;
 }
 
 pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;
@@ -139,19 +159,19 @@
 /// The location of a scheduled task that can be used to remove it.
 pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
 
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
+/*#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))] todo remove completely?
 #[derive(Clone, RuntimeDebug, Encode, Decode)]
 struct ScheduledV1<Call, BlockNumber> {
 	maybe_id: Option<Vec<u8>>,
 	priority: schedule::Priority,
 	call: Call,
 	maybe_periodic: Option<schedule::Period<BlockNumber>>,
-}
+}*/
 
 /// Information regarding an item to be executed in the future.
 #[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
 #[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]
-pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {
+pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {
 	/// The unique identity for this task, if there is one.
 	maybe_id: Option<Vec<u8>>,
 	/// This task's priority.
@@ -162,17 +182,19 @@
 	maybe_periodic: Option<schedule::Period<BlockNumber>>,
 	/// The origin to dispatch the call.
 	origin: PalletsOrigin,
+	/// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.
+	pre_dispatch: PreDispatch,
 	_phantom: PhantomData<AccountId>,
 }
 
 /// The current version of Scheduled struct.
-pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =
-	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;
+/*pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> =
+	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch>;*/
 
 // A value placed in storage that represents the current version of the Scheduler storage.
 // This value is used by the `on_runtime_upgrade` logic to determine whether we run
 // storage migration logic.
-#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
+/*#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] todo remove completely?
 enum Releases {
 	V1,
 	V2,
@@ -182,7 +204,7 @@
 	fn default() -> Self {
 		Releases::V1
 	}
-}
+}*/
 
 #[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
 pub struct CallSpec {
@@ -194,18 +216,24 @@
 	trait Store for Module<T: Config> as Scheduler {
 		/// Items to be executed, indexed by the block number that they should be executed on.
 		pub Agenda: map hasher(twox_64_concat) T::BlockNumber
-			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;
+			=> Vec<Option<Scheduled<
+				<T as Config>::Call,
+				T::BlockNumber,
+				T::PalletsOrigin,
+				T::AccountId,
+				<<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre
+			>>>;
 
-		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber
-			=> Vec<Option<CallSpec>>;
+		/*pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber todo remove completely?
+			=> Vec<Option<CallSpec>>;*/
 
 		/// Lookup from identity to the block number and index of the task.
 		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;
 
-		/// Storage version of the pallet.
-		///
-		/// New networks start with last version.
-		StorageVersion build(|_| Releases::V2): Releases;
+		// / Storage version of the pallet.
+		// /
+		// / New networks start with last version.
+		//StorageVersion build(|_| Releases::V2): Releases; todo remove completely?
 	}
 }
 
@@ -418,19 +446,25 @@
 					Some((order, index, *cumulative_weight, s))
 				})
 				.filter_map(|(order, index, cumulative_weight, mut s)| {
-					// We allow a scheduled call if any is true:
+					// We allow a scheduled call if:
 					// - It's priority is `HARD_DEADLINE`
-					// - It does not push the weight past the limit.
+					// - It does not push the weight past the limit
+					// or, alternatively,
 					// - It is the first item in the schedule
-					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
+					if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {
+						let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());
+
+						if let Err(_) = r {
+							log::warn!(
+								target: "runtime::scheduler",
+								"Warning: Scheduler has failed to execute a post-dispatch transaction. \
+								This block might have become invalid.",
+							);
+							// todo possibly force a skip/return here, do something with the error
+						}
+
+						let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?
 
-						// let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
-						// 	s.origin.clone()
-						// ).into();
-						// let sender = ensure_signed(origin).unwrap_or_default();
-						// let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(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();
 						if let Some((period, count)) = s.maybe_periodic {
 							if count > 1 {
@@ -451,7 +485,7 @@
 						Self::deposit_event(RawEvent::Dispatched(
 							(now, index),
 							maybe_id,
-							Ok(())// r.map(|_| ()).map_err(|e| e.error)
+							r.map(|_| ()).map_err(|e| e.error)
 						));
 						total_weight = cumulative_weight;
 						None
@@ -500,13 +534,19 @@
 		let sender = ensure_signed(
 			<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),
 		)
-		.unwrap_or_default();
-		let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);
-		let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
-		let r = call.clone().dispatch(sponsor.into());
+		.unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment
+					  //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);
+					  //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));
+					  //let r = call.clone().dispatch(sponsor.into());
+
+		let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {
+			Ok(pre_dispatch) => pre_dispatch,
+			Err(_) => return Err(Error::<T>::FailedToSchedule.into()),
+		};
 
-		//T::PaymentHandler::apply();
-		//T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch extrinsic here
+		// todo continually pre-dispatch according to maybe_periodic -- but it's called only once?
+		// no, reschedule and cancel rely on scheduled being only the next instance
+		// actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee
 
 		// sanitize maybe_periodic
 		let maybe_periodic = maybe_periodic
@@ -514,12 +554,21 @@
 			// Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.
 			.map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));
 
+		if let Some(periodic) = maybe_periodic {
+			for _i in 0..=periodic.1 {
+				// displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment
+				// send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?
+				// roadblock - they will return on post_dispatch -- oh! tips?
+			}
+		}
+
 		let s = Some(Scheduled {
 			maybe_id,
 			priority,
 			call,
 			maybe_periodic,
 			origin,
+			pre_dispatch,
 			_phantom: PhantomData::<T::AccountId>::default(),
 		});
 		Agenda::<T>::append(when, s);
@@ -557,7 +606,7 @@
 		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {
 			agenda.get_mut(index as usize).map_or(
 				Ok(None),
-				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
+				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
 					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
 						if *o != s.origin {
 							return Err(BadOrigin.into());
@@ -570,8 +619,14 @@
 		if let Some(s) = scheduled {
 			if let Some(id) = s.maybe_id {
 				Lookup::<T>::remove(id);
-				// todo add back money / displace to another function for consistency
 			}
+			if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {
+				log::warn!(
+					target: "runtime::scheduler",
+					"Warning: Scheduler has failed to execute a post-dispatch transaction. \
+					This block might have become invalid.",
+				);
+			} // maybe do something with the error?
 			Self::deposit_event(RawEvent::Canceled(when, index));
 			Ok(())
 		} else {
@@ -643,12 +698,19 @@
 							if *o != s.origin {
 								return Err(BadOrigin.into());
 							}
+							if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())
+							{
+								log::warn!(
+									target: "runtime::scheduler",
+									"Warning: Scheduler has failed to execute a post-dispatch transaction. \
+									This block might have become invalid.",
+								);
+							} // maybe do something with the error?
 						}
 						*s = None;
 					}
 					Ok(())
 				})?;
-				// todo add money back / displace to another function
 				Self::deposit_event(RawEvent::Canceled(when, index));
 				Ok(())
 			} else {
@@ -842,11 +904,32 @@
 		}
 	}
 
-	pub struct DummyExecutor; // todo do something with naming and function body
-	impl<C: Dispatchable> ApplyExtrinsic<C> for DummyExecutor {
-		fn apply_extrinsic(_signer: Address, _function: C) -> ApplyExtrinsicResult {
+	pub struct DummyExecutor;
+	impl<T: frame_system::Config + Config, SelfContainedSignedInfo>
+		DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor
+	{
+		type Pre = ();
+
+		fn dispatch_call(
+			_pre: Self::Pre,
+			_call: <T as Config>::Call,
+		) -> Result<
+			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+			TransactionValidityError,
+		> {
 			todo!()
 		}
+
+		fn pre_dispatch(
+			_signer: <T as frame_system::Config>::AccountId,
+			_call: <T as Config>::Call,
+		) -> Result<Self::Pre, TransactionValidityError> {
+			todo!()
+		}
+
+		fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {
+			todo!()
+		}
 	}
 
 	parameter_types! {
@@ -898,7 +981,8 @@
 		type MaximumWeight = MaximumSchedulerWeight;
 		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
 		type MaxScheduledPerBlock = MaxScheduledPerBlock;
+		type SponsorshipHandler = ();
 		type WeightInfo = ();
-		type Executor = DummyExecutor;
+		type CallExecutor = DummyExecutor;
 	}
 }
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -17,6 +17,8 @@
 use sp_api::impl_runtime_apis;
 use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};
 use sp_runtime::DispatchError;
+use fp_self_contained::*;
+use sp_runtime::traits::{SignedExtension, Member};
 // #[cfg(any(feature = "std", test))]
 // pub use sp_runtime::BuildStorage;
 
@@ -54,7 +56,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
 	},
 };
-use pallet_unq_scheduler::ApplyExtrinsic;
+use pallet_unq_scheduler::DispatchCall;
 use up_data_structs::*;
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
@@ -66,6 +68,7 @@
 	traits::{BaseArithmetic, Unsigned},
 };
 use smallvec::smallvec;
+use scale_info::TypeInfo;
 use codec::{Encode, Decode};
 use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
 use fp_rpc::TransactionStatus;
@@ -73,6 +76,7 @@
 use sp_runtime::{
 	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
 	transaction_validity::TransactionValidityError,
+	DispatchErrorWithPostInfo,
 };
 
 // pub use pallet_timestamp::Call as TimestampCall;
@@ -805,30 +809,114 @@
 	pub const MaxScheduledPerBlock: u32 = 50;
 }
 
-type EvmSponsorshipHandler = (
-	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
-	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
-);
-type SponsorshipHandler = (
-	pallet_unique::UniqueSponsorshipHandler<Runtime>,
-	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
-	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
-);
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+
+/*fn get_signed_extra(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {
+	(
+		frame_system::CheckSpecVersion::<Runtime>::new(),
+		frame_system::CheckGenesis::<Runtime>::new(),
+		frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+		frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+			from,
+		)),
+		frame_system::CheckWeight::<Runtime>::new(),
+		ChargeTransactionPayment::new(0),
+	)
+}*/
 
-// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {
-// 	node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)
-// }
+#[derive(Default, Encode, Decode, Clone, TypeInfo)]
+pub struct SchedulerPreDispatch {
+	tip: Balance,
+	signer: AccountId,
+	fee: Option<Balance>,
+}
 
 pub struct SchedulerPaymentExecutor;
-impl<C: Dispatchable> ApplyExtrinsic<C> for SchedulerPaymentExecutor {
-	fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {
-		/*let extrinsic = sign(fp_self_contained::CheckedExtrinsic {
-			signed: fp_self_contained::CheckedSignature::SelfContained(None),
-			function,
-		});
+impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+where
+	<T as frame_system::Config>::Call: Member
+		+ Dispatchable<Origin = Origin, Info = DispatchInfo>
+		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+		+ GetDispatchInfo
+		+ From<frame_system::Call<Runtime>>,
+	SelfContainedSignedInfo: Send + Sync + 'static,
+	Call: From<<T as frame_system::Config>::Call>
+		+ From<<T as pallet_unq_scheduler::Config>::Call>
+		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+	type Pre = SchedulerPreDispatch;
+
+	fn dispatch_call(
+		//signer: <T as frame_system::Config>::AccountId,
+		pre_dispatch: Self::Pre,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<
+		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+		TransactionValidityError,
+	> {
+		/*let dispatch_info = call.get_dispatch_info();
+
+		let extrinsic = fp_self_contained::CheckedExtrinsic::<
+			AccountId,
+			Call,
+			SignedExtra,
+			SelfContainedSignedInfo,
+		> {
+			signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(
+				signer.clone().into(),
+				get_signed_extra(signer.clone().into()),
+			),
+			function: call.clone().into(),
+		};
+
+		extrinsic.apply::<Runtime>(&dispatch_info, 0)*/
+		let dispatch_info = call.get_dispatch_info();
+		let pre = (
+			pre_dispatch.tip,
+			pre_dispatch.signer.clone().into(),
+			pre_dispatch.fee.map(|fee| NegativeImbalance::new(fee)),
+		);
+
+		let maybe_who = Some(pre_dispatch.signer.clone().into());
+		let res = Call::from(call.clone()).dispatch(Origin::from(maybe_who));
+		let post_info = match res {
+			Ok(dispatch_info) => dispatch_info,
+			Err(err) => err.post_info,
+		};
+		SignedExtra::post_dispatch(
+			((), (), (), (), (), pre),
+			&dispatch_info,
+			&post_info,
+			0,
+			&res.map(|_| ()).map_err(|e| e.error),
+		)?;
+		Ok(res)
+	}
+
+	fn pre_dispatch(
+		signer: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<Self::Pre, TransactionValidityError> {
+		let dispatch_info = call.get_dispatch_info();
+		//<T as Config>::OnChargeTransaction::withdraw_fee();
+		let fee_charger = ChargeTransactionPayment::new(
+			// Linear scaling of the fee tip if the priority is high enough
+			0, //if priority > HARD_DEADLINE { 0 } else { (HARD_DEADLINE - priority + 1) / HARD_DEADLINE * PRIORITY_TIP_MULTIPLIER * total_fee }
+		);
+		let pre = fee_charger.pre_dispatch(&signer.into(), &call.into(), &dispatch_info, 0)?;
+
+		Ok(SchedulerPreDispatch {
+			tip: pre.0,
+			signer: pre.1,
+			fee: pre.2.map(|imbalance| imbalance.peek()),
+		})
+	}
 
-		Executive::apply_extrinsic(extrinsic)*/
+	fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError> {
 		todo!()
+		// simply call post_dispatch with 0 actual fee and the whole remaining, already withdrawn, fee
 	}
 }
 
@@ -840,10 +928,22 @@
 	type MaximumWeight = MaximumSchedulerWeight;
 	type ScheduleOrigin = EnsureSigned<AccountId>;
 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
+	type SponsorshipHandler = SponsorshipHandler;
 	type WeightInfo = ();
-	type Executor = SchedulerPaymentExecutor;
+	type CallExecutor = SchedulerPaymentExecutor;
 }
 
+type EvmSponsorshipHandler = (
+	pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
+	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
+);
+
+type SponsorshipHandler = (
+	pallet_unique::UniqueSponsorshipHandler<Runtime>,
+	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
+	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
+);
+
 impl pallet_evm_transaction_payment::Config for Runtime {
 	type EvmSponsorshipHandler = EvmSponsorshipHandler;
 	type Currency = Balances;
@@ -965,7 +1065,7 @@
 	frame_system::CheckEra<Runtime>,
 	frame_system::CheckNonce<Runtime>,
 	frame_system::CheckWeight<Runtime>,
-	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+	ChargeTransactionPayment,
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 );
 /// Unchecked extrinsic type as expected by this runtime.
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -3,22 +3,41 @@
 // file 'LICENSE', which is part of this source code package.
 //
 
-import chai from 'chai';
+import chai, { expect } from 'chai';
 import chaiAsPromised from 'chai-as-promised';
 import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
 import {
+  default as usingApi, 
+  submitTransactionAsync,
+  submitTransactionExpectFailAsync,
+} from './substrate/substrate-api';
+import {
   createItemExpectSuccess,
   createCollectionExpectSuccess,
   scheduleTransferExpectSuccess,
+  scheduleTransferAndWaitExpectSuccess,
   setCollectionSponsorExpectSuccess,
   confirmSponsorshipExpectSuccess,
+  findUnusedAddress,
+  UNIQUE,
+  enablePublicMintingExpectSuccess,
+  addToAllowListExpectSuccess,
+  waitNewBlocks,
+  normalizeAccountId,
+  getTokenOwner,
+  getGenericResult,
+  scheduleTransferFundsPeriodicExpectSuccess,
+  setCollectionLimitsExpectSuccess,
+  getDetailedCollectionInfo,
+  getFreeBalance,
+  confirmSponsorshipByKeyExpectSuccess,
 } from './util/helpers';
 import {IKeyringPair} from '@polkadot/types/types';
+import {getBalanceSingle} from './substrate/get-balance';
 
 chai.use(chaiAsPromised);
 
-describe('Integration Test scheduler base transaction', () => {
+describe('Scheduling token and balance transfers', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
 
@@ -29,7 +48,7 @@
     });
   });
 
-  it('User can transfer owned token with delay (scheduler)', async () => {
+  it('Can schedule a transfer of an owned token with delay', async () => {
     await usingApi(async () => {
       // nft
       const nftCollectionId = await createCollectionExpectSuccess();
@@ -37,7 +56,219 @@
       await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
       await confirmSponsorshipExpectSuccess(nftCollectionId);
 
-      await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+    });
+  });
+
+  it('Can transfer funds periodically', async () => {
+    await usingApi(async (api) => {
+      const waitForBlocks = 4;
+      const period = 2;
+      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
+      const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+
+      // discounting already waited-for operations
+      await waitNewBlocks(waitForBlocks - 2);
+      const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+      expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+      await waitNewBlocks(period);
+      const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+      expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+    });
+  });
+
+  it('Can sponsor scheduling a transaction', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+    await usingApi(async () => {
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+      const aliceBalanceBefore = await getFreeBalance(alice);
+      // no need to wait to check, fees must be deducted on scheduling, immediately
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
+      const aliceBalanceAfter = await getFreeBalance(alice);
+      expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+    });
+  });
+
+  /*it('Can\'t schedule a transaction with no funds', async () => {
+    await usingApi(async (api) => {
+      // Find an empty, unused account
+      const zeroBalance = await findUnusedAddress(api);
+
+      const collectionId = await createCollectionExpectSuccess();
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+
+      await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
+
+      await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+    });
+  });*/
+
+  it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+    await usingApi(async (api) => {
+      // Find an empty, unused account
+      const zeroBalance = await findUnusedAddress(api);
+
+      const collectionId = await createCollectionExpectSuccess();
+
+      // Add zeroBalance address to allow list
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+      // Grace zeroBalance with money, enough to cover future transactions
+      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+      await submitTransactionAsync(alice, balanceTx);
+
+      // Mint a fresh NFT
+      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+      // Schedule transfer of the NFT a few blocks ahead
+      const waitForBlocks = 5;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
+
+      // Get rid of the account's funds before the scheduled transaction takes place
+      const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+      const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+      const events = await submitTransactionAsync(alice, sudoTx);
+      expect(getGenericResult(events).success).to.be.true;
+
+      // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+      await waitNewBlocks(waitForBlocks - 3);
+
+      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+    });
+  });
+
+  /*it.skip('Going bankrupt after sponsoring a scheduled transaction does not nullify the transaction', async () => {
+    await usingApi(async (api) => {
+      // Find two empty, unused accounts
+      const zeroBalance = await findUnusedAddress(api);
+      const zeroBalanceSponsor = await findUnusedAddress(api);
+
+      const collectionId = await createCollectionExpectSuccess();
+
+      // Grace these with money, enough to cover future transactions
+      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+      await submitTransactionAsync(alice, balanceTx);
+
+      // Grace these with money, enough to cover future transactions
+      const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);
+      await submitTransactionAsync(alice, balanceSponsorTx);
+
+      // Set a collection sponsor
+      await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);
+      await confirmSponsorshipExpectSuccess(collectionId);
+
+      // Add zeroBalance address to allow list
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+      // Mint a fresh NFT
+      const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+      // Schedule transfer of the NFT a few blocks ahead
+      // const waitForBlocks = 4;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+      //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);
+
+      // Get rid of the account's funds before the scheduled transaction takes place
+      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalanceSponsor.address, 0, 0);
+      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+      const events = await submitTransactionAsync(alice, sudoTx);
+      expect(getGenericResult(events).success).to.be.true;
+
+      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+      await waitNewBlocks(4);
+
+      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+    });
+  });*/
+
+  it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+
+    await usingApi(async (api) => {
+      const zeroBalance = await findUnusedAddress(api);
+
+      /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
+        sponsoredDataRateLimit: 2,
+      });*/
+      //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
+      const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+      await submitTransactionAsync(alice, balanceTx);
+
+      await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+      await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+
+      const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+      const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+      const events = await submitTransactionAsync(alice, sudoTx);
+      expect(getGenericResult(events).success).to.be.true;
+
+      // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+      await waitNewBlocks(2);
+
+      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+    });
+  });
+});
+
+describe.skip('Scheduling EVM smart contracts', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+
+  before(async() => {
+    await usingApi(async () => {
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+    });
+  });
+
+  // todo contract testing
+  it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+    await usingApi(async (api) => {
+      // Find unused address
+      const zeroBalance = await findUnusedAddress(api);
+
+      // Mint token for alice
+      const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+      // Transfer this token from Alice to unused address and back
+      // Alice to Zero gets sponsored
+      const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
+      const events1 = await submitTransactionAsync(alice, aliceToZero);
+      const result1 = getGenericResult(events1);
+
+      // Second transfer should fail
+      const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
+      const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
+      const badTransaction = async function () {
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+      };
+      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+      const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+
+      // Try again after Zero gets some balance - now it should succeed
+      const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+      await submitTransactionAsync(alice, balancetx);
+      const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
+      const result2 = getGenericResult(events2);
+
+      expect(result1.success).to.be.true;
+      expect(result2.success).to.be.true;
+      expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
     });
   });
 });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {UpDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23  Substrate: string,24} | {25  Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28  if (typeof input === 'string') {29    if (input.length === 48 || input.length === 47) {30      return {Substrate: input};31    } else if (input.length === 42 && input.startsWith('0x')) {32      return {Ethereum: input.toLowerCase()};33    } else if (input.length === 40 && !input.startsWith('0x')) {34      return {Ethereum: '0x' + input.toLowerCase()};35    } else {36      throw new Error(`Unknown address format: "${input}"`);37    }38  }39  if ('address' in input) {40    return {Substrate: input.address};41  }42  if ('Ethereum' in input) {43    return {44      Ethereum: input.Ethereum.toLowerCase(),45    };46  } else if ('ethereum' in input) {47    return {48      Ethereum: (input as any).ethereum.toLowerCase(),49    };50  } else if ('Substrate' in input) {51    return input;52  }else if ('substrate' in input) {53    return {54      Substrate: (input as any).substrate,55    };56  }5758  // AccountId59  return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62  input = normalizeAccountId(input);63  if ('Substrate' in input) {64    return input.Substrate;65  } else {66    return evmToAddress(input.Ethereum);67  }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78  success: boolean,79};8081interface CreateCollectionResult {82  success: boolean;83  collectionId: number;84}8586interface CreateItemResult {87  success: boolean;88  collectionId: number;89  itemId: number;90  recipient?: CrossAccountId;91}9293interface TransferResult {94  success: boolean;95  collectionId: number;96  itemId: number;97  sender?: CrossAccountId;98  recipient?: CrossAccountId;99  value: bigint;100}101102interface IReFungibleOwner {103  fraction: BN;104  owner: number[];105}106107interface IGetMessage {108  checkMsgUnqMethod: string;109  checkMsgTrsMethod: string;110  checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114  value: number;115}116117export interface IChainLimits {118  collectionNumbersLimit: number;119	accountTokenOwnershipLimit: number;120	collectionsAdminsLimit: number;121	customDataLimit: number;122	nftSponsorTransferTimeout: number;123	fungibleSponsorTransferTimeout: number;124	refungibleSponsorTransferTimeout: number;125	offchainSchemaLimit: number;126	variableOnChainSchemaLimit: number;127	constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131  owner: IReFungibleOwner[];132  constData: number[];133  variableData: number[];134}135136export function uniqueEventMessage(events: EventRecord[]): IGetMessage {137  let checkMsgUnqMethod = '';138  let checkMsgTrsMethod = '';139  let checkMsgSysMethod = '';140  events.forEach(({event: {method, section}}) => {141    if (section === 'common') {142      checkMsgUnqMethod = method;143    } else if (section === 'treasury') {144      checkMsgTrsMethod = method;145    } else if (section === 'system') {146      checkMsgSysMethod = method;147    } else { return null; }148  });149  const result: IGetMessage = {150    checkMsgUnqMethod,151    checkMsgTrsMethod,152    checkMsgSysMethod,153  };154  return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158  const result: GenericResult = {159    success: false,160  };161  events.forEach(({event: {method}}) => {162    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);163    if (method === 'ExtrinsicSuccess') {164      result.success = true;165    }166  });167  return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173  let success = false;174  let collectionId = 0;175  events.forEach(({event: {data, method, section}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method == 'ExtrinsicSuccess') {178      success = true;179    } else if ((section == 'common') && (method == 'CollectionCreated')) {180      collectionId = parseInt(data[0].toString(), 10);181    }182  });183  const result: CreateCollectionResult = {184    success,185    collectionId,186  };187  return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191  let success = false;192  let collectionId = 0;193  let itemId = 0;194  let recipient;195  events.forEach(({event: {data, method, section}}) => {196    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);197    if (method == 'ExtrinsicSuccess') {198      success = true;199    } else if ((section == 'common') && (method == 'ItemCreated')) {200      collectionId = parseInt(data[0].toString(), 10);201      itemId = parseInt(data[1].toString(), 10);202      recipient = normalizeAccountId(data[2].toJSON() as any);203    }204  });205  const result: CreateItemResult = {206    success,207    collectionId,208    itemId,209    recipient,210  };211  return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215  const result: TransferResult = {216    success: false,217    collectionId: 0,218    itemId: 0,219    value: 0n,220  };221222  events.forEach(({event: {data, method, section}}) => {223    if (method === 'ExtrinsicSuccess') {224      result.success = true;225    } else if (section === 'common' && method === 'Transfer') {226      result.collectionId = +data[0].toString();227      result.itemId = +data[1].toString();228      result.sender = normalizeAccountId(data[2].toJSON() as any);229      result.recipient = normalizeAccountId(data[3].toJSON() as any);230      result.value = BigInt(data[4].toString());231    }232  });233234  return result;235}236237interface Nft {238  type: 'NFT';239}240241interface Fungible {242  type: 'Fungible';243  decimalPoints: number;244}245246interface ReFungible {247  type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253  mode: CollectionMode,254  name: string,255  description: string,256  tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260  description: 'description',261  mode: {type: 'NFT'},262  name: 'name',263  tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269  let collectionId = 0;270  await usingApi(async (api) => {271    // Get number of collections before the transaction272    const collectionCountBefore = await getCreatedCollectionCount(api);273274    // Run the CreateCollection transaction275    const alicePrivateKey = privateKey('//Alice');276277    let modeprm = {};278    if (mode.type === 'NFT') {279      modeprm = {nft: null};280    } else if (mode.type === 'Fungible') {281      modeprm = {fungible: mode.decimalPoints};282    } else if (mode.type === 'ReFungible') {283      modeprm = {refungible: null};284    }285286    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287    const events = await submitTransactionAsync(alicePrivateKey, tx);288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const collectionCountAfter = await getCreatedCollectionCount(api);292293    // Get the collection294    const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296    // What to expect297    // tslint:disable-next-line:no-unused-expression298    expect(result.success).to.be.true;299    expect(result.collectionId).to.be.equal(collectionCountAfter);300    // tslint:disable-next-line:no-unused-expression301    expect(collection).to.be.not.null;302    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308    collectionId = result.collectionId;309  });310311  return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317  let modeprm = {};318  if (mode.type === 'NFT') {319    modeprm = {nft: null};320  } else if (mode.type === 'Fungible') {321    modeprm = {fungible: mode.decimalPoints};322  } else if (mode.type === 'ReFungible') {323    modeprm = {refungible: null};324  }325326  await usingApi(async (api) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334    const result = getCreateCollectionResult(events);335336    // Get number of collections after the transaction337    const collectionCountAfter = await getCreatedCollectionCount(api);338339    // What to expect340    // tslint:disable-next-line:no-unused-expression341    expect(result.success).to.be.false;342    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343  });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347  let bal = 0n;348  let unused;349  do {350    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351    const keyring = new Keyring({type: 'sr25519'});352    unused = keyring.addFromUri(`//${randomSeed}`);353    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354  } while (bal !== 0n);355  return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367  const totalNumber = await getCreatedCollectionCount(api);368  const newCollection: number = totalNumber + 1;369  return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373  let success = false;374  events.forEach(({event: {method}}) => {375    if (method == 'ExtrinsicSuccess') {376      success = true;377    }378  });379  return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383  await usingApi(async (api) => {384    // Run the DestroyCollection transaction385    const alicePrivateKey = privateKey(senderSeed);386    const tx = api.tx.unique.destroyCollection(collectionId);387    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388  });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392  await usingApi(async (api) => {393    // Run the DestroyCollection transaction394    const alicePrivateKey = privateKey(senderSeed);395    const tx = api.tx.unique.destroyCollection(collectionId);396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getDestroyResult(events);398    expect(result).to.be.true;399400    // What to expect401    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402  });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);408    const events = await submitTransactionAsync(sender, tx);409    const result = getGenericResult(events);410411    expect(result.success).to.be.true;412  });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416  await usingApi(async (api) => {417    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);418    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419    const result = getGenericResult(events);420421    expect(result.success).to.be.false;422  });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426  await usingApi(async (api) => {427428    // Run the transaction429    const senderPrivateKey = privateKey(sender);430    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);431    const events = await submitTransactionAsync(senderPrivateKey, tx);432    const result = getGenericResult(events);433434    // Get the collection435    const collection = await queryCollectionExpectSuccess(api, collectionId);436437    // What to expect438    expect(result.success).to.be.true;439    expect(collection.sponsorship.toJSON()).to.deep.equal({440      unconfirmed: sponsor,441    });442  });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446  await usingApi(async (api) => {447448    // Run the transaction449    const alicePrivateKey = privateKey(sender);450    const tx = api.tx.unique.removeCollectionSponsor(collectionId);451    const events = await submitTransactionAsync(alicePrivateKey, tx);452    const result = getGenericResult(events);453454    // Get the collection455    const collection = await queryCollectionExpectSuccess(api, collectionId);456457    // What to expect458    expect(result.success).to.be.true;459    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460  });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464  await usingApi(async (api) => {465466    // Run the transaction467    const alicePrivateKey = privateKey(senderSeed);468    const tx = api.tx.unique.removeCollectionSponsor(collectionId);469    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470  });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const alicePrivateKey = privateKey(senderSeed);478    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480  });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484  await usingApi(async (api) => {485486    // Run the transaction487    const sender = privateKey(senderSeed);488    const tx = api.tx.unique.confirmSponsorship(collectionId);489    const events = await submitTransactionAsync(sender, tx);490    const result = getGenericResult(events);491492    // Get the collection493    const collection = await queryCollectionExpectSuccess(api, collectionId);494495    // What to expect496    expect(result.success).to.be.true;497    expect(collection.sponsorship.toJSON()).to.be.deep.equal({498      confirmed: sender.address,499    });500  });501}502503504export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {505  await usingApi(async (api) => {506507    // Run the transaction508    const sender = privateKey(senderSeed);509    const tx = api.tx.unique.confirmSponsorship(collectionId);510    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;511  });512}513514export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {515516  await usingApi(async (api) => {517    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);518    const events = await submitTransactionAsync(sender, tx);519    const result = getGenericResult(events);520521    expect(result.success).to.be.true;522  });523}524525export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {526527  await usingApi(async (api) => {528    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);529    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;530    const result = getGenericResult(events);531532    expect(result.success).to.be.false;533  });534}535536export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {537  await usingApi(async (api) => {538    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);539    const events = await submitTransactionAsync(sender, tx);540    const result = getGenericResult(events);541542    expect(result.success).to.be.true;543  });544}545546export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {547  await usingApi(async (api) => {548    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);549    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;550    const result = getGenericResult(events);551552    expect(result.success).to.be.false;553  });554}555556export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {557558  await usingApi(async (api) => {559560    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);561    const events = await submitTransactionAsync(sender, tx);562    const result = getGenericResult(events);563564    expect(result.success).to.be.true;565  });566}567568export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {569570  await usingApi(async (api) => {571572    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);573    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;574    const result = getGenericResult(events);575576    expect(result.success).to.be.false;577  });578}579580export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {581  await usingApi(async (api) => {582    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);583    const events = await submitTransactionAsync(sender, tx);584    const result = getGenericResult(events);585586    expect(result.success).to.be.true;587  });588}589590export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {591  await usingApi(async (api) => {592    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);593    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;594    const result = getGenericResult(events);595596    expect(result.success).to.be.false;597  });598}599600export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {601  await usingApi(async (api) => {602    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);603    const events = await submitTransactionAsync(sender, tx);604    const result = getGenericResult(events);605606    expect(result.success).to.be.true;607  });608}609610export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {611  let allowlisted = false;612  await usingApi(async (api) => {613    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;614  });615  return allowlisted;616}617618export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {619  await usingApi(async (api) => {620    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());621    const events = await submitTransactionAsync(sender, tx);622    const result = getGenericResult(events);623624    expect(result.success).to.be.true;625  });626}627628export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {629  await usingApi(async (api) => {630    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());631    const events = await submitTransactionAsync(sender, tx);632    const result = getGenericResult(events);633634    expect(result.success).to.be.true;635  });636}637638export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {639  await usingApi(async (api) => {640    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());641    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;642    const result = getGenericResult(events);643644    expect(result.success).to.be.false;645  });646}647648export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {649  await usingApi(async (api) => {650    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));651    const events = await submitTransactionAsync(sender, tx);652    const result = getGenericResult(events);653654    expect(result.success).to.be.true;655  });656}657658export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {659  await usingApi(async (api) => {660    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));661    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;662  });663}664665export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {666  await usingApi(async (api) => {667    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));668    const events = await submitTransactionAsync(sender, tx);669    const result = getGenericResult(events);670671    expect(result.success).to.be.true;672  });673}674675export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {676  await usingApi(async (api) => {677    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));678    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;679  });680}681682export interface CreateFungibleData {683  readonly Value: bigint;684}685686export interface CreateReFungibleData { }687export interface CreateNftData { }688689export type CreateItemData = {690  NFT: CreateNftData;691} | {692  Fungible: CreateFungibleData;693} | {694  ReFungible: CreateReFungibleData;695};696697export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {698  await usingApi(async (api) => {699    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);700    // if burning token by admin - use adminButnItemExpectSuccess701    expect(balanceBefore >= BigInt(value)).to.be.true;702703    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);704    const events = await submitTransactionAsync(sender, tx);705    const result = getGenericResult(events);706    expect(result.success).to.be.true;707708    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);709    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);710  });711}712713export async function714approveExpectSuccess(715  collectionId: number,716  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,717) {718  await usingApi(async (api: ApiPromise) => {719    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);720    const events = await submitTransactionAsync(owner, approveUniqueTx);721    const result = getGenericResult(events);722    expect(result.success).to.be.true;723724    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));725  });726}727728export async function adminApproveFromExpectSuccess(729  collectionId: number,730  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,731) {732  await usingApi(async (api: ApiPromise) => {733    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);734    const events = await submitTransactionAsync(admin, approveUniqueTx);735    const result = getGenericResult(events);736    expect(result.success).to.be.true;737738    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));739  });740}741742export async function743transferFromExpectSuccess(744  collectionId: number,745  tokenId: number,746  accountApproved: IKeyringPair,747  accountFrom: IKeyringPair | CrossAccountId,748  accountTo: IKeyringPair | CrossAccountId,749  value: number | bigint = 1,750  type = 'NFT',751) {752  await usingApi(async (api: ApiPromise) => {753    const to = normalizeAccountId(accountTo);754    let balanceBefore = 0n;755    if (type === 'Fungible') {756      balanceBefore = await getBalance(api, collectionId, to, tokenId);757    }758    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);759    const events = await submitTransactionAsync(accountApproved, transferFromTx);760    const result = getCreateItemResult(events);761    // tslint:disable-next-line:no-unused-expression762    expect(result.success).to.be.true;763    if (type === 'NFT') {764      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);765    }766    if (type === 'Fungible') {767      const balanceAfter = await getBalance(api, collectionId, to, tokenId);768      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));769    }770    if (type === 'ReFungible') {771      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));772    }773  });774}775776export async function777transferFromExpectFail(778  collectionId: number,779  tokenId: number,780  accountApproved: IKeyringPair,781  accountFrom: IKeyringPair,782  accountTo: IKeyringPair,783  value: number | bigint = 1,784) {785  await usingApi(async (api: ApiPromise) => {786    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);787    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;788    const result = getCreateCollectionResult(events);789    // tslint:disable-next-line:no-unused-expression790    expect(result.success).to.be.false;791  });792}793794/* eslint no-async-promise-executor: "off" */795async function getBlockNumber(api: ApiPromise): Promise<number> {796  return new Promise<number>(async (resolve) => {797    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {798      unsubscribe();799      resolve(head.number.toNumber());800    });801  });802}803804export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {805  await usingApi(async (api) => {806    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));807    const events = await submitTransactionAsync(sender, changeAdminTx);808    const result = getCreateCollectionResult(events);809    expect(result.success).to.be.true;810  });811}812813export async function814getFreeBalance(account: IKeyringPair) : Promise<bigint>815{816  let balance = 0n;817  await usingApi(async (api) => {818    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());819  });820821  return balance;822}823824export async function825scheduleTransferExpectSuccess(826  collectionId: number,827  tokenId: number,828  sender: IKeyringPair,829  recipient: IKeyringPair,830  value: number | bigint = 1,831  blockSchedule: number,832) {833  await usingApi(async (api: ApiPromise) => {834    const blockNumber: number | undefined = await getBlockNumber(api);835    const expectedBlockNumber = blockNumber + blockSchedule;836837    expect(blockNumber).to.be.greaterThan(0);838    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);839    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);840841    await submitTransactionAsync(sender, scheduleTx);842843    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();844845    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));846847    // sleep for 4 blocks848    await waitNewBlocks(blockSchedule + 1);849850    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();851852    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));853    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);854  });855}856857858export async function859transferExpectSuccess(860  collectionId: number,861  tokenId: number,862  sender: IKeyringPair,863  recipient: IKeyringPair | CrossAccountId,864  value: number | bigint = 1,865  type = 'NFT',866) {867  await usingApi(async (api: ApiPromise) => {868    const to = normalizeAccountId(recipient);869870    let balanceBefore = 0n;871    if (type === 'Fungible') {872      balanceBefore = await getBalance(api, collectionId, to, tokenId);873    }874    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);875    const events = await submitTransactionAsync(sender, transferTx);876    const result = getTransferResult(events);877    // tslint:disable-next-line:no-unused-expression878    expect(result.success).to.be.true;879    expect(result.collectionId).to.be.equal(collectionId);880    expect(result.itemId).to.be.equal(tokenId);881    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));882    expect(result.recipient).to.be.deep.equal(to);883    expect(result.value).to.be.equal(BigInt(value));884    if (type === 'NFT') {885      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);886    }887    if (type === 'Fungible') {888      const balanceAfter = await getBalance(api, collectionId, to, tokenId);889      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));890    }891    if (type === 'ReFungible') {892      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;893    }894  });895}896897export async function898transferExpectFailure(899  collectionId: number,900  tokenId: number,901  sender: IKeyringPair,902  recipient: IKeyringPair,903  value: number | bigint = 1,904) {905  await usingApi(async (api: ApiPromise) => {906    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);907    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;908    const result = getGenericResult(events);909    // if (events && Array.isArray(events)) {910    //   const result = getCreateCollectionResult(events);911    // tslint:disable-next-line:no-unused-expression912    expect(result.success).to.be.false;913    //}914  });915}916917export async function918approveExpectFail(919  collectionId: number,920  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,921) {922  await usingApi(async (api: ApiPromise) => {923    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);924    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;925    const result = getCreateCollectionResult(events);926    // tslint:disable-next-line:no-unused-expression927    expect(result.success).to.be.false;928  });929}930931export async function getBalance(932  api: ApiPromise,933  collectionId: number,934  owner: string | CrossAccountId,935  token: number,936): Promise<bigint> {937  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();938}939export async function getTokenOwner(940  api: ApiPromise,941  collectionId: number,942  token: number,943): Promise<CrossAccountId> {944  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);945}946export async function isTokenExists(947  api: ApiPromise,948  collectionId: number,949  token: number,950): Promise<boolean> {951  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();952}953export async function getLastTokenId(954  api: ApiPromise,955  collectionId: number,956): Promise<number> {957  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();958}959export async function getAdminList(960  api: ApiPromise,961  collectionId: number,962): Promise<string[]> {963  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;964}965export async function getVariableMetadata(966  api: ApiPromise,967  collectionId: number,968  tokenId: number,969): Promise<number[]> {970  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];971}972export async function getConstMetadata(973  api: ApiPromise,974  collectionId: number,975  tokenId: number,976): Promise<number[]> {977  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];978}979980export async function createFungibleItemExpectSuccess(981  sender: IKeyringPair,982  collectionId: number,983  data: CreateFungibleData,984  owner: CrossAccountId | string = sender.address,985) {986  return await usingApi(async (api) => {987    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});988989    const events = await submitTransactionAsync(sender, tx);990    const result = getCreateItemResult(events);991992    expect(result.success).to.be.true;993    return result.itemId;994  });995}996997export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {998  let newItemId = 0;999  await usingApi(async (api) => {1000    const to = normalizeAccountId(owner);1001    const itemCountBefore = await getLastTokenId(api, collectionId);1002    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10031004    let tx;1005    if (createMode === 'Fungible') {1006      const createData = {fungible: {value: 10}};1007      tx = api.tx.unique.createItem(collectionId, to, createData as any);1008    } else if (createMode === 'ReFungible') {1009      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1010      tx = api.tx.unique.createItem(collectionId, to, createData as any);1011    } else {1012      const createData = {nft: {const_data: [], variable_data: []}};1013      tx = api.tx.unique.createItem(collectionId, to, createData as any);1014    }10151016    const events = await submitTransactionAsync(sender, tx);1017    const result = getCreateItemResult(events);10181019    const itemCountAfter = await getLastTokenId(api, collectionId);1020    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10211022    // What to expect1023    // tslint:disable-next-line:no-unused-expression1024    expect(result.success).to.be.true;1025    if (createMode === 'Fungible') {1026      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1027    } else {1028      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1029    }1030    expect(collectionId).to.be.equal(result.collectionId);1031    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1032    expect(to).to.be.deep.equal(result.recipient);1033    newItemId = result.itemId;1034  });1035  return newItemId;1036}10371038export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1039  await usingApi(async (api) => {1040    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10411042    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1043    const result = getCreateItemResult(events);10441045    expect(result.success).to.be.false;1046  });1047}10481049export async function setPublicAccessModeExpectSuccess(1050  sender: IKeyringPair, collectionId: number,1051  accessMode: 'Normal' | 'AllowList',1052) {1053  await usingApi(async (api) => {10541055    // Run the transaction1056    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1057    const events = await submitTransactionAsync(sender, tx);1058    const result = getGenericResult(events);10591060    // Get the collection1061    const collection = await queryCollectionExpectSuccess(api, collectionId);10621063    // What to expect1064    // tslint:disable-next-line:no-unused-expression1065    expect(result.success).to.be.true;1066    expect(collection.access.toHuman()).to.be.equal(accessMode);1067  });1068}10691070export async function setPublicAccessModeExpectFail(1071  sender: IKeyringPair, collectionId: number,1072  accessMode: 'Normal' | 'AllowList',1073) {1074  await usingApi(async (api) => {10751076    // Run the transaction1077    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1078    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1079    const result = getGenericResult(events);10801081    // What to expect1082    // tslint:disable-next-line:no-unused-expression1083    expect(result.success).to.be.false;1084  });1085}10861087export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1088  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1089}10901091export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1092  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1093}10941095export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1096  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1097}10981099export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1100  await usingApi(async (api) => {11011102    // Run the transaction1103    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1104    const events = await submitTransactionAsync(sender, tx);1105    const result = getGenericResult(events);1106    expect(result.success).to.be.true;11071108    // Get the collection1109    const collection = await queryCollectionExpectSuccess(api, collectionId);11101111    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1112  });1113}11141115export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1116  await setMintPermissionExpectSuccess(sender, collectionId, true);1117}11181119export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1120  await usingApi(async (api) => {1121    // Run the transaction1122    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1123    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1124    const result = getCreateCollectionResult(events);1125    // tslint:disable-next-line:no-unused-expression1126    expect(result.success).to.be.false;1127  });1128}11291130export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1131  await usingApi(async (api) => {1132    // Run the transaction1133    const tx = api.tx.unique.setChainLimits(limits);1134    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1135    const result = getCreateCollectionResult(events);1136    // tslint:disable-next-line:no-unused-expression1137    expect(result.success).to.be.false;1138  });1139}11401141export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1142  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1143}11441145export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1146  await usingApi(async (api) => {1147    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11481149    // Run the transaction1150    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1151    const events = await submitTransactionAsync(sender, tx);1152    const result = getGenericResult(events);1153    expect(result.success).to.be.true;11541155    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1156  });1157}11581159export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1160  await usingApi(async (api) => {11611162    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;11631164    // Run the transaction1165    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1166    const events = await submitTransactionAsync(sender, tx);1167    const result = getGenericResult(events);1168    expect(result.success).to.be.true;11691170    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1171  });1172}11731174export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1175  await usingApi(async (api) => {11761177    // Run the transaction1178    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1179    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1180    const result = getGenericResult(events);11811182    // What to expect1183    // tslint:disable-next-line:no-unused-expression1184    expect(result.success).to.be.false;1185  });1186}11871188export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1189  await usingApi(async (api) => {1190    // Run the transaction1191    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1192    const events = await submitTransactionAsync(sender, tx);1193    const result = getGenericResult(events);11941195    // What to expect1196    // tslint:disable-next-line:no-unused-expression1197    expect(result.success).to.be.true;1198  });1199}12001201export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1202  await usingApi(async (api) => {1203    // Run the transaction1204    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1205    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1206    const result = getGenericResult(events);12071208    // What to expect1209    // tslint:disable-next-line:no-unused-expression1210    expect(result.success).to.be.false;1211  });1212}12131214export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1215  : Promise<UpDataStructsCollection | null> => {1216  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1217};12181219export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1220  // set global object - collectionsCount1221  return (await api.rpc.unique.collectionStats()).created.toNumber();1222};12231224export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1225  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1226}12271228export async function waitNewBlocks(blocksCount = 1): Promise<void> {1229  await usingApi(async (api) => {1230    const promise = new Promise<void>(async (resolve) => {1231      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1232        if (blocksCount > 0) {1233          blocksCount--;1234        } else {1235          unsubscribe();1236          resolve();1237        }1238      });1239    });1240    return promise;1241  });1242}
after · tests/src/util/helpers.ts
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56import {ApiPromise, Keyring} from '@polkadot/api';7import type {AccountId, EventRecord} from '@polkadot/types/interfaces';8import {IKeyringPair} from '@polkadot/types/types';9import {evmToAddress} from '@polkadot/util-crypto';10import BN from 'bn.js';11import chai from 'chai';12import chaiAsPromised from 'chai-as-promised';13import {alicesPublicKey} from '../accounts';14import {UpDataStructsCollection} from '../interfaces';15import privateKey from '../substrate/privateKey';16import {default as usingApi, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';17import {hexToStr, strToUTF16, utf16ToStr} from './util';1819chai.use(chaiAsPromised);20const expect = chai.expect;2122export type CrossAccountId = {23  Substrate: string,24} | {25  Ethereum: string,26};27export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {28  if (typeof input === 'string') {29    if (input.length === 48 || input.length === 47) {30      return {Substrate: input};31    } else if (input.length === 42 && input.startsWith('0x')) {32      return {Ethereum: input.toLowerCase()};33    } else if (input.length === 40 && !input.startsWith('0x')) {34      return {Ethereum: '0x' + input.toLowerCase()};35    } else {36      throw new Error(`Unknown address format: "${input}"`);37    }38  }39  if ('address' in input) {40    return {Substrate: input.address};41  }42  if ('Ethereum' in input) {43    return {44      Ethereum: input.Ethereum.toLowerCase(),45    };46  } else if ('ethereum' in input) {47    return {48      Ethereum: (input as any).ethereum.toLowerCase(),49    };50  } else if ('Substrate' in input) {51    return input;52  }else if ('substrate' in input) {53    return {54      Substrate: (input as any).substrate,55    };56  }5758  // AccountId59  return {Substrate: input.toString()};60}61export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {62  input = normalizeAccountId(input);63  if ('Substrate' in input) {64    return input.Substrate;65  } else {66    return evmToAddress(input.Ethereum);67  }68}6970export const U128_MAX = (1n << 128n) - 1n;7172const MICROUNIQUE = 1_000_000_000_000n;73const MILLIUNIQUE = 1_000n * MICROUNIQUE;74const CENTIUNIQUE = 10n * MILLIUNIQUE;75export const UNIQUE = 100n * CENTIUNIQUE;7677type GenericResult = {78  success: boolean,79};8081interface CreateCollectionResult {82  success: boolean;83  collectionId: number;84}8586interface CreateItemResult {87  success: boolean;88  collectionId: number;89  itemId: number;90  recipient?: CrossAccountId;91}9293interface TransferResult {94  success: boolean;95  collectionId: number;96  itemId: number;97  sender?: CrossAccountId;98  recipient?: CrossAccountId;99  value: bigint;100}101102interface IReFungibleOwner {103  fraction: BN;104  owner: number[];105}106107interface IGetMessage {108  checkMsgUnqMethod: string;109  checkMsgTrsMethod: string;110  checkMsgSysMethod: string;111}112113export interface IFungibleTokenDataType {114  value: number;115}116117export interface IChainLimits {118  collectionNumbersLimit: number;119	accountTokenOwnershipLimit: number;120	collectionsAdminsLimit: number;121	customDataLimit: number;122	nftSponsorTransferTimeout: number;123	fungibleSponsorTransferTimeout: number;124	refungibleSponsorTransferTimeout: number;125	offchainSchemaLimit: number;126	variableOnChainSchemaLimit: number;127	constOnChainSchemaLimit: number;128}129130export interface IReFungibleTokenDataType {131  owner: IReFungibleOwner[];132  constData: number[];133  variableData: number[];134}135136export function uniqueEventMessage(events: EventRecord[]): IGetMessage {137  let checkMsgUnqMethod = '';138  let checkMsgTrsMethod = '';139  let checkMsgSysMethod = '';140  events.forEach(({event: {method, section}}) => {141    if (section === 'common') {142      checkMsgUnqMethod = method;143    } else if (section === 'treasury') {144      checkMsgTrsMethod = method;145    } else if (section === 'system') {146      checkMsgSysMethod = method;147    } else { return null; }148  });149  const result: IGetMessage = {150    checkMsgUnqMethod,151    checkMsgTrsMethod,152    checkMsgSysMethod,153  };154  return result;155}156157export function getGenericResult(events: EventRecord[]): GenericResult {158  const result: GenericResult = {159    success: false,160  };161  events.forEach(({event: {method}}) => {162    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);163    if (method === 'ExtrinsicSuccess') {164      result.success = true;165    }166  });167  return result;168}169170171172export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {173  let success = false;174  let collectionId = 0;175  events.forEach(({event: {data, method, section}}) => {176    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);177    if (method == 'ExtrinsicSuccess') {178      success = true;179    } else if ((section == 'common') && (method == 'CollectionCreated')) {180      collectionId = parseInt(data[0].toString(), 10);181    }182  });183  const result: CreateCollectionResult = {184    success,185    collectionId,186  };187  return result;188}189190export function getCreateItemResult(events: EventRecord[]): CreateItemResult {191  let success = false;192  let collectionId = 0;193  let itemId = 0;194  let recipient;195  events.forEach(({event: {data, method, section}}) => {196    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);197    if (method == 'ExtrinsicSuccess') {198      success = true;199    } else if ((section == 'common') && (method == 'ItemCreated')) {200      collectionId = parseInt(data[0].toString(), 10);201      itemId = parseInt(data[1].toString(), 10);202      recipient = normalizeAccountId(data[2].toJSON() as any);203    }204  });205  const result: CreateItemResult = {206    success,207    collectionId,208    itemId,209    recipient,210  };211  return result;212}213214export function getTransferResult(events: EventRecord[]): TransferResult {215  const result: TransferResult = {216    success: false,217    collectionId: 0,218    itemId: 0,219    value: 0n,220  };221222  events.forEach(({event: {data, method, section}}) => {223    if (method === 'ExtrinsicSuccess') {224      result.success = true;225    } else if (section === 'common' && method === 'Transfer') {226      result.collectionId = +data[0].toString();227      result.itemId = +data[1].toString();228      result.sender = normalizeAccountId(data[2].toJSON() as any);229      result.recipient = normalizeAccountId(data[3].toJSON() as any);230      result.value = BigInt(data[4].toString());231    }232  });233234  return result;235}236237interface Nft {238  type: 'NFT';239}240241interface Fungible {242  type: 'Fungible';243  decimalPoints: number;244}245246interface ReFungible {247  type: 'ReFungible';248}249250type CollectionMode = Nft | Fungible | ReFungible;251252export type CreateCollectionParams = {253  mode: CollectionMode,254  name: string,255  description: string,256  tokenPrefix: string,257};258259const defaultCreateCollectionParams: CreateCollectionParams = {260  description: 'description',261  mode: {type: 'NFT'},262  name: 'name',263  tokenPrefix: 'prefix',264};265266export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {267  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};268269  let collectionId = 0;270  await usingApi(async (api) => {271    // Get number of collections before the transaction272    const collectionCountBefore = await getCreatedCollectionCount(api);273274    // Run the CreateCollection transaction275    const alicePrivateKey = privateKey('//Alice');276277    let modeprm = {};278    if (mode.type === 'NFT') {279      modeprm = {nft: null};280    } else if (mode.type === 'Fungible') {281      modeprm = {fungible: mode.decimalPoints};282    } else if (mode.type === 'ReFungible') {283      modeprm = {refungible: null};284    }285286    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);287    const events = await submitTransactionAsync(alicePrivateKey, tx);288    const result = getCreateCollectionResult(events);289290    // Get number of collections after the transaction291    const collectionCountAfter = await getCreatedCollectionCount(api);292293    // Get the collection294    const collection = await queryCollectionExpectSuccess(api, result.collectionId);295296    // What to expect297    // tslint:disable-next-line:no-unused-expression298    expect(result.success).to.be.true;299    expect(result.collectionId).to.be.equal(collectionCountAfter);300    // tslint:disable-next-line:no-unused-expression301    expect(collection).to.be.not.null;302    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');303    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));304    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);305    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);306    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);307308    collectionId = result.collectionId;309  });310311  return collectionId;312}313314export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {315  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};316317  let modeprm = {};318  if (mode.type === 'NFT') {319    modeprm = {nft: null};320  } else if (mode.type === 'Fungible') {321    modeprm = {fungible: mode.decimalPoints};322  } else if (mode.type === 'ReFungible') {323    modeprm = {refungible: null};324  }325326  await usingApi(async (api) => {327    // Get number of collections before the transaction328    const collectionCountBefore = await getCreatedCollectionCount(api);329330    // Run the CreateCollection transaction331    const alicePrivateKey = privateKey('//Alice');332    const tx = api.tx.unique.createCollection(strToUTF16(name), strToUTF16(description), strToUTF16(tokenPrefix), modeprm as any);333    const events = await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;334    const result = getCreateCollectionResult(events);335336    // Get number of collections after the transaction337    const collectionCountAfter = await getCreatedCollectionCount(api);338339    // What to expect340    // tslint:disable-next-line:no-unused-expression341    expect(result.success).to.be.false;342    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');343  });344}345346export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {347  let bal = 0n;348  let unused;349  do {350    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;351    const keyring = new Keyring({type: 'sr25519'});352    unused = keyring.addFromUri(`//${randomSeed}`);353    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();354  } while (bal !== 0n);355  return unused;356}357358export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {359  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();360}361362export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {363  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));364}365366export async function findNotExistingCollection(api: ApiPromise): Promise<number> {367  const totalNumber = await getCreatedCollectionCount(api);368  const newCollection: number = totalNumber + 1;369  return newCollection;370}371372function getDestroyResult(events: EventRecord[]): boolean {373  let success = false;374  events.forEach(({event: {method}}) => {375    if (method == 'ExtrinsicSuccess') {376      success = true;377    }378  });379  return success;380}381382export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {383  await usingApi(async (api) => {384    // Run the DestroyCollection transaction385    const alicePrivateKey = privateKey(senderSeed);386    const tx = api.tx.unique.destroyCollection(collectionId);387    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;388  });389}390391export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {392  await usingApi(async (api) => {393    // Run the DestroyCollection transaction394    const alicePrivateKey = privateKey(senderSeed);395    const tx = api.tx.unique.destroyCollection(collectionId);396    const events = await submitTransactionAsync(alicePrivateKey, tx);397    const result = getDestroyResult(events);398    expect(result).to.be.true;399400    // What to expect401    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;402  });403}404405export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {406  await usingApi(async (api) => {407    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);408    const events = await submitTransactionAsync(sender, tx);409    const result = getGenericResult(events);410411    expect(result.success).to.be.true;412  });413}414415export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {416  await usingApi(async (api) => {417    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);418    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;419    const result = getGenericResult(events);420421    expect(result.success).to.be.false;422  });423}424425export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {426  await usingApi(async (api) => {427428    // Run the transaction429    const senderPrivateKey = privateKey(sender);430    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);431    const events = await submitTransactionAsync(senderPrivateKey, tx);432    const result = getGenericResult(events);433434    // Get the collection435    const collection = await queryCollectionExpectSuccess(api, collectionId);436437    // What to expect438    expect(result.success).to.be.true;439    expect(collection.sponsorship.toJSON()).to.deep.equal({440      unconfirmed: sponsor,441    });442  });443}444445export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {446  await usingApi(async (api) => {447448    // Run the transaction449    const alicePrivateKey = privateKey(sender);450    const tx = api.tx.unique.removeCollectionSponsor(collectionId);451    const events = await submitTransactionAsync(alicePrivateKey, tx);452    const result = getGenericResult(events);453454    // Get the collection455    const collection = await queryCollectionExpectSuccess(api, collectionId);456457    // What to expect458    expect(result.success).to.be.true;459    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});460  });461}462463export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {464  await usingApi(async (api) => {465466    // Run the transaction467    const alicePrivateKey = privateKey(senderSeed);468    const tx = api.tx.unique.removeCollectionSponsor(collectionId);469    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;470  });471}472473export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {474  await usingApi(async (api) => {475476    // Run the transaction477    const alicePrivateKey = privateKey(senderSeed);478    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);479    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;480  });481}482483export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {484  await usingApi(async () => {485    const sender = privateKey(senderSeed);486    await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);487  });488}489490export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {491  await usingApi(async (api) => {492493    // Run the transaction494    const tx = api.tx.unique.confirmSponsorship(collectionId);495    const events = await submitTransactionAsync(sender, tx);496    const result = getGenericResult(events);497498    // Get the collection499    const collection = await queryCollectionExpectSuccess(api, collectionId);500501    // What to expect502    expect(result.success).to.be.true;503    expect(collection.sponsorship.toJSON()).to.be.deep.equal({504      confirmed: sender.address,505    });506  });507}508509510export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {511  await usingApi(async (api) => {512513    // Run the transaction514    const sender = privateKey(senderSeed);515    const tx = api.tx.unique.confirmSponsorship(collectionId);516    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;517  });518}519520export async function setMetadataUpdatePermissionFlagExpectSuccess(sender: IKeyringPair, collectionId: number, flag: string) {521522  await usingApi(async (api) => {523    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);524    const events = await submitTransactionAsync(sender, tx);525    const result = getGenericResult(events);526527    expect(result.success).to.be.true;528  });529}530531export async function setMetadataUpdatePermissionFlagExpectFailure(sender: IKeyringPair, collectionId: number, flag: string) {532533  await usingApi(async (api) => {534    const tx = api.tx.unique.setMetaUpdatePermissionFlag(collectionId, flag as any);535    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;536    const result = getGenericResult(events);537538    expect(result.success).to.be.false;539  });540}541542export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {543  await usingApi(async (api) => {544    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);545    const events = await submitTransactionAsync(sender, tx);546    const result = getGenericResult(events);547548    expect(result.success).to.be.true;549  });550}551552export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {553  await usingApi(async (api) => {554    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);555    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;556    const result = getGenericResult(events);557558    expect(result.success).to.be.false;559  });560}561562export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {563564  await usingApi(async (api) => {565566    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);567    const events = await submitTransactionAsync(sender, tx);568    const result = getGenericResult(events);569570    expect(result.success).to.be.true;571  });572}573574export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {575576  await usingApi(async (api) => {577578    const tx = api.tx.unique.setTransfersEnabledFlag (collectionId, enabled);579    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;580    const result = getGenericResult(events);581582    expect(result.success).to.be.false;583  });584}585586export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {587  await usingApi(async (api) => {588    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);589    const events = await submitTransactionAsync(sender, tx);590    const result = getGenericResult(events);591592    expect(result.success).to.be.true;593  });594}595596export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {597  await usingApi(async (api) => {598    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);599    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;600    const result = getGenericResult(events);601602    expect(result.success).to.be.false;603  });604}605606export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {607  await usingApi(async (api) => {608    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);609    const events = await submitTransactionAsync(sender, tx);610    const result = getGenericResult(events);611612    expect(result.success).to.be.true;613  });614}615616export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {617  let allowlisted = false;618  await usingApi(async (api) => {619    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;620  });621  return allowlisted;622}623624export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {625  await usingApi(async (api) => {626    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());627    const events = await submitTransactionAsync(sender, tx);628    const result = getGenericResult(events);629630    expect(result.success).to.be.true;631  });632}633634export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {635  await usingApi(async (api) => {636    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());637    const events = await submitTransactionAsync(sender, tx);638    const result = getGenericResult(events);639640    expect(result.success).to.be.true;641  });642}643644export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {645  await usingApi(async (api) => {646    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());647    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;648    const result = getGenericResult(events);649650    expect(result.success).to.be.false;651  });652}653654export async function setVariableMetaDataExpectSuccess(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {655  await usingApi(async (api) => {656    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));657    const events = await submitTransactionAsync(sender, tx);658    const result = getGenericResult(events);659660    expect(result.success).to.be.true;661  });662}663664export async function setVariableMetaDataExpectFailure(sender: IKeyringPair, collectionId: number, itemId: number, data: number[]) {665  await usingApi(async (api) => {666    const tx = api.tx.unique.setVariableMetaData(collectionId, itemId, '0x' + Buffer.from(data).toString('hex'));667    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;668  });669}670671export async function setOffchainSchemaExpectSuccess(sender: IKeyringPair, collectionId: number, data: number[]) {672  await usingApi(async (api) => {673    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));674    const events = await submitTransactionAsync(sender, tx);675    const result = getGenericResult(events);676677    expect(result.success).to.be.true;678  });679}680681export async function setOffchainSchemaExpectFailure(sender: IKeyringPair, collectionId: number, data: number[]) {682  await usingApi(async (api) => {683    const tx = api.tx.unique.setOffchainSchema(collectionId, '0x' + Buffer.from(data).toString('hex'));684    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;685  });686}687688export interface CreateFungibleData {689  readonly Value: bigint;690}691692export interface CreateReFungibleData { }693export interface CreateNftData { }694695export type CreateItemData = {696  NFT: CreateNftData;697} | {698  Fungible: CreateFungibleData;699} | {700  ReFungible: CreateReFungibleData;701};702703export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {704  await usingApi(async (api) => {705    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);706    // if burning token by admin - use adminButnItemExpectSuccess707    expect(balanceBefore >= BigInt(value)).to.be.true;708709    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);710    const events = await submitTransactionAsync(sender, tx);711    const result = getGenericResult(events);712    expect(result.success).to.be.true;713714    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);715    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);716  });717}718719export async function720approveExpectSuccess(721  collectionId: number,722  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,723) {724  await usingApi(async (api: ApiPromise) => {725    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);726    const events = await submitTransactionAsync(owner, approveUniqueTx);727    const result = getGenericResult(events);728    expect(result.success).to.be.true;729730    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));731  });732}733734export async function adminApproveFromExpectSuccess(735  collectionId: number,736  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,737) {738  await usingApi(async (api: ApiPromise) => {739    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);740    const events = await submitTransactionAsync(admin, approveUniqueTx);741    const result = getGenericResult(events);742    expect(result.success).to.be.true;743744    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));745  });746}747748export async function749transferFromExpectSuccess(750  collectionId: number,751  tokenId: number,752  accountApproved: IKeyringPair,753  accountFrom: IKeyringPair | CrossAccountId,754  accountTo: IKeyringPair | CrossAccountId,755  value: number | bigint = 1,756  type = 'NFT',757) {758  await usingApi(async (api: ApiPromise) => {759    const to = normalizeAccountId(accountTo);760    let balanceBefore = 0n;761    if (type === 'Fungible') {762      balanceBefore = await getBalance(api, collectionId, to, tokenId);763    }764    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);765    const events = await submitTransactionAsync(accountApproved, transferFromTx);766    const result = getCreateItemResult(events);767    // tslint:disable-next-line:no-unused-expression768    expect(result.success).to.be.true;769    if (type === 'NFT') {770      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);771    }772    if (type === 'Fungible') {773      const balanceAfter = await getBalance(api, collectionId, to, tokenId);774      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));775    }776    if (type === 'ReFungible') {777      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(BigInt(value));778    }779  });780}781782export async function783transferFromExpectFail(784  collectionId: number,785  tokenId: number,786  accountApproved: IKeyringPair,787  accountFrom: IKeyringPair,788  accountTo: IKeyringPair,789  value: number | bigint = 1,790) {791  await usingApi(async (api: ApiPromise) => {792    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);793    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;794    const result = getCreateCollectionResult(events);795    // tslint:disable-next-line:no-unused-expression796    expect(result.success).to.be.false;797  });798}799800/* eslint no-async-promise-executor: "off" */801export async function getBlockNumber(api: ApiPromise): Promise<number> {802  return new Promise<number>(async (resolve) => {803    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {804      unsubscribe();805      resolve(head.number.toNumber());806    });807  });808}809810export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {811  await usingApi(async (api) => {812    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));813    const events = await submitTransactionAsync(sender, changeAdminTx);814    const result = getCreateCollectionResult(events);815    expect(result.success).to.be.true;816  });817}818819export async function820getFreeBalance(account: IKeyringPair) : Promise<bigint>821{822  let balance = 0n;823  await usingApi(async (api) => {824    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());825  });826827  return balance;828}829830export async function831scheduleTransferAndWaitExpectSuccess(832  collectionId: number,833  tokenId: number,834  sender: IKeyringPair,835  recipient: IKeyringPair,836  value: number | bigint = 1,837  blockSchedule: number,838) {839  await usingApi(async (api: ApiPromise) => {840    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);841842    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();843    console.log(await getFreeBalance(sender));844845    // sleep for n + 1 blocks846    await waitNewBlocks(blockSchedule + 1);847848    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();849850    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));851    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);852  });853}854855export async function856scheduleTransferExpectSuccess(857  collectionId: number,858  tokenId: number,859  sender: IKeyringPair,860  recipient: IKeyringPair,861  value: number | bigint = 1,862  blockSchedule: number,863) {864  await usingApi(async (api: ApiPromise) => {865    const blockNumber: number | undefined = await getBlockNumber(api);866    const expectedBlockNumber = blockNumber + blockSchedule;867868    expect(blockNumber).to.be.greaterThan(0);869    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);870    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);871872    const events = await submitTransactionAsync(sender, scheduleTx);873    expect(getGenericResult(events).success).to.be.true;874875    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));876  });877}878879export async function880scheduleTransferFundsPeriodicExpectSuccess(881  amount: bigint,882  sender: IKeyringPair,883  recipient: IKeyringPair,884  blockSchedule: number,885  period: number,886  repetitions: number,887) {888  await usingApi(async (api: ApiPromise) => {889    const blockNumber: number | undefined = await getBlockNumber(api);890    const expectedBlockNumber = blockNumber + blockSchedule;891892    const balanceBefore = await getFreeBalance(recipient);893    894    expect(blockNumber).to.be.greaterThan(0);895    const transferTx = api.tx.balances.transfer(recipient.address, amount);896    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);897898    const events = await submitTransactionAsync(sender, scheduleTx);899    expect(getGenericResult(events).success).to.be.true;900901    expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);902  });903}904905906export async function907transferExpectSuccess(908  collectionId: number,909  tokenId: number,910  sender: IKeyringPair,911  recipient: IKeyringPair | CrossAccountId,912  value: number | bigint = 1,913  type = 'NFT',914) {915  await usingApi(async (api: ApiPromise) => {916    const to = normalizeAccountId(recipient);917918    let balanceBefore = 0n;919    if (type === 'Fungible') {920      balanceBefore = await getBalance(api, collectionId, to, tokenId);921    }922    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);923    const events = await submitTransactionAsync(sender, transferTx);924    const result = getTransferResult(events);925    // tslint:disable-next-line:no-unused-expression926    expect(result.success).to.be.true;927    expect(result.collectionId).to.be.equal(collectionId);928    expect(result.itemId).to.be.equal(tokenId);929    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));930    expect(result.recipient).to.be.deep.equal(to);931    expect(result.value).to.be.equal(BigInt(value));932    if (type === 'NFT') {933      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);934    }935    if (type === 'Fungible') {936      const balanceAfter = await getBalance(api, collectionId, to, tokenId);937      expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));938    }939    if (type === 'ReFungible') {940      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;941    }942  });943}944945export async function946transferExpectFailure(947  collectionId: number,948  tokenId: number,949  sender: IKeyringPair,950  recipient: IKeyringPair,951  value: number | bigint = 1,952) {953  await usingApi(async (api: ApiPromise) => {954    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);955    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;956    const result = getGenericResult(events);957    // if (events && Array.isArray(events)) {958    //   const result = getCreateCollectionResult(events);959    // tslint:disable-next-line:no-unused-expression960    expect(result.success).to.be.false;961    //}962  });963}964965export async function966approveExpectFail(967  collectionId: number,968  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,969) {970  await usingApi(async (api: ApiPromise) => {971    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);972    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;973    const result = getCreateCollectionResult(events);974    // tslint:disable-next-line:no-unused-expression975    expect(result.success).to.be.false;976  });977}978979export async function getBalance(980  api: ApiPromise,981  collectionId: number,982  owner: string | CrossAccountId,983  token: number,984): Promise<bigint> {985  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();986}987export async function getTokenOwner(988  api: ApiPromise,989  collectionId: number,990  token: number,991): Promise<CrossAccountId> {992  return normalizeAccountId((await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any);993}994export async function isTokenExists(995  api: ApiPromise,996  collectionId: number,997  token: number,998): Promise<boolean> {999  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1000}1001export async function getLastTokenId(1002  api: ApiPromise,1003  collectionId: number,1004): Promise<number> {1005  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1006}1007export async function getAdminList(1008  api: ApiPromise,1009  collectionId: number,1010): Promise<string[]> {1011  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1012}1013export async function getVariableMetadata(1014  api: ApiPromise,1015  collectionId: number,1016  tokenId: number,1017): Promise<number[]> {1018  return [...(await api.rpc.unique.variableMetadata(collectionId, tokenId))];1019}1020export async function getConstMetadata(1021  api: ApiPromise,1022  collectionId: number,1023  tokenId: number,1024): Promise<number[]> {1025  return [...(await api.rpc.unique.constMetadata(collectionId, tokenId))];1026}10271028export async function createFungibleItemExpectSuccess(1029  sender: IKeyringPair,1030  collectionId: number,1031  data: CreateFungibleData,1032  owner: CrossAccountId | string = sender.address,1033) {1034  return await usingApi(async (api) => {1035    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});10361037    const events = await submitTransactionAsync(sender, tx);1038    const result = getCreateItemResult(events);10391040    expect(result.success).to.be.true;1041    return result.itemId;1042  });1043}10441045export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1046  let newItemId = 0;1047  await usingApi(async (api) => {1048    const to = normalizeAccountId(owner);1049    const itemCountBefore = await getLastTokenId(api, collectionId);1050    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);10511052    let tx;1053    if (createMode === 'Fungible') {1054      const createData = {fungible: {value: 10}};1055      tx = api.tx.unique.createItem(collectionId, to, createData as any);1056    } else if (createMode === 'ReFungible') {1057      const createData = {refungible: {const_data: [], variable_data: [], pieces: 100}};1058      tx = api.tx.unique.createItem(collectionId, to, createData as any);1059    } else {1060      const createData = {nft: {const_data: [], variable_data: []}};1061      tx = api.tx.unique.createItem(collectionId, to, createData as any);1062    }10631064    const events = await submitTransactionAsync(sender, tx);1065    const result = getCreateItemResult(events);10661067    const itemCountAfter = await getLastTokenId(api, collectionId);1068    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);10691070    // What to expect1071    // tslint:disable-next-line:no-unused-expression1072    expect(result.success).to.be.true;1073    if (createMode === 'Fungible') {1074      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1075    } else {1076      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1077    }1078    expect(collectionId).to.be.equal(result.collectionId);1079    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1080    expect(to).to.be.deep.equal(result.recipient);1081    newItemId = result.itemId;1082  });1083  return newItemId;1084}10851086export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: string = sender.address) {1087  await usingApi(async (api) => {1088    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);10891090    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1091    const result = getCreateItemResult(events);10921093    expect(result.success).to.be.false;1094  });1095}10961097export async function setPublicAccessModeExpectSuccess(1098  sender: IKeyringPair, collectionId: number,1099  accessMode: 'Normal' | 'AllowList',1100) {1101  await usingApi(async (api) => {11021103    // Run the transaction1104    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1105    const events = await submitTransactionAsync(sender, tx);1106    const result = getGenericResult(events);11071108    // Get the collection1109    const collection = await queryCollectionExpectSuccess(api, collectionId);11101111    // What to expect1112    // tslint:disable-next-line:no-unused-expression1113    expect(result.success).to.be.true;1114    expect(collection.access.toHuman()).to.be.equal(accessMode);1115  });1116}11171118export async function setPublicAccessModeExpectFail(1119  sender: IKeyringPair, collectionId: number,1120  accessMode: 'Normal' | 'AllowList',1121) {1122  await usingApi(async (api) => {11231124    // Run the transaction1125    const tx = api.tx.unique.setPublicAccessMode(collectionId, accessMode);1126    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1127    const result = getGenericResult(events);11281129    // What to expect1130    // tslint:disable-next-line:no-unused-expression1131    expect(result.success).to.be.false;1132  });1133}11341135export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1136  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1137}11381139export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1140  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1141}11421143export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1144  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1145}11461147export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1148  await usingApi(async (api) => {11491150    // Run the transaction1151    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1152    const events = await submitTransactionAsync(sender, tx);1153    const result = getGenericResult(events);1154    expect(result.success).to.be.true;11551156    // Get the collection1157    const collection = await queryCollectionExpectSuccess(api, collectionId);11581159    expect(collection.mintMode.toHuman()).to.be.equal(enabled);1160  });1161}11621163export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1164  await setMintPermissionExpectSuccess(sender, collectionId, true);1165}11661167export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1168  await usingApi(async (api) => {1169    // Run the transaction1170    const tx = api.tx.unique.setMintPermission(collectionId, enabled);1171    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1172    const result = getCreateCollectionResult(events);1173    // tslint:disable-next-line:no-unused-expression1174    expect(result.success).to.be.false;1175  });1176}11771178export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1179  await usingApi(async (api) => {1180    // Run the transaction1181    const tx = api.tx.unique.setChainLimits(limits);1182    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1183    const result = getCreateCollectionResult(events);1184    // tslint:disable-next-line:no-unused-expression1185    expect(result.success).to.be.false;1186  });1187}11881189export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1190  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1191}11921193export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1194  await usingApi(async (api) => {1195    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;11961197    // Run the transaction1198    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1199    const events = await submitTransactionAsync(sender, tx);1200    const result = getGenericResult(events);1201    expect(result.success).to.be.true;12021203    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1204  });1205}12061207export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1208  await usingApi(async (api) => {12091210    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;12111212    // Run the transaction1213    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1214    const events = await submitTransactionAsync(sender, tx);1215    const result = getGenericResult(events);1216    expect(result.success).to.be.true;12171218    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1219  });1220}12211222export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1223  await usingApi(async (api) => {12241225    // Run the transaction1226    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1227    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1228    const result = getGenericResult(events);12291230    // What to expect1231    // tslint:disable-next-line:no-unused-expression1232    expect(result.success).to.be.false;1233  });1234}12351236export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1237  await usingApi(async (api) => {1238    // Run the transaction1239    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1240    const events = await submitTransactionAsync(sender, tx);1241    const result = getGenericResult(events);12421243    // What to expect1244    // tslint:disable-next-line:no-unused-expression1245    expect(result.success).to.be.true;1246  });1247}12481249export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1250  await usingApi(async (api) => {1251    // Run the transaction1252    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1253    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1254    const result = getGenericResult(events);12551256    // What to expect1257    // tslint:disable-next-line:no-unused-expression1258    expect(result.success).to.be.false;1259  });1260}12611262export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1263  : Promise<UpDataStructsCollection | null> => {1264  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1265};12661267export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1268  // set global object - collectionsCount1269  return (await api.rpc.unique.collectionStats()).created.toNumber();1270};12711272export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsCollection> {1273  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1274}12751276export async function waitNewBlocks(blocksCount = 1): Promise<void> {1277  await usingApi(async (api) => {1278    const promise = new Promise<void>(async (resolve) => {1279      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1280        if (blocksCount > 0) {1281          blocksCount--;1282        } else {1283          unsubscribe();1284          resolve();1285        }1286      });1287    });1288    return promise;1289  });1290}