git.delta.rocks / unique-network / refs/commits / 0f7bb4adb180

difftreelog

Merge pull request #341 from UniqueNetwork/feature/simple-scheduler

kozyrevdev2022-06-03parents: #93f5452 #9e5b125.patch.diff
in: master
Feature/simple scheduler

11 files changed

modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -15,11 +15,13 @@
 scale-info = { version = "2.0.1", default-features = false, features = [
 	"derive",
 ] }
+
 frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
 frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
 sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
 sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
 sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.22' }
 frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
 
 up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22" }
@@ -40,6 +42,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
@@ -1,23 +1,6 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license
 // This file is part of Substrate.
 
-// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
+// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
 // SPDX-License-Identifier: Apache-2.0
 
 // Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,16 +15,9 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! # Scheduler
-//! A module for scheduling dispatches.
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Module`]
-//!
-//! ## Overview
+//! # Schedulerdo_reschedule
 //!
-//! This module exposes capabilities for scheduling dispatches to occur at a
+//! This Pallet exposes capabilities for scheduling dispatches to occur at a
 //! specified block number or at a specified period. These scheduled dispatches
 //! may be named or anonymous and may be canceled.
 //!
@@ -57,106 +33,59 @@
 //!
 //! ### Dispatchable Functions
 //!
-//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a
-//!   specified block and with a specified priority.
-//! * `cancel` - cancel a scheduled dispatch, specified by block number and
-//!   index.
-//! * `schedule_named` - augments the `schedule` interface with an additional
-//!   `Vec<u8>` parameter that can be used for identification.
+//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and
+//!   with a specified priority.
+//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.
+//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter
+//!   that can be used for identification.
 //! * `cancel_named` - the named complement to the cancel function.
 
 // Ensure we're `no_std` when compiling for Wasm.
 #![cfg_attr(not(feature = "std"), no_std)]
-#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]
 
+#[cfg(feature = "runtime-benchmarks")]
 mod benchmarking;
+
 pub mod weights;
 
-use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};
-use codec::{Encode, Decode, Codec};
+use sp_core::H160;
+use codec::{Codec, Decode, Encode};
+use frame_system::{self as system, ensure_signed};
+pub use pallet::*;
+use scale_info::TypeInfo;
 use sp_runtime::{
-	RuntimeDebug,
-	traits::{Zero, One, BadOrigin, Saturating},
+	traits::{BadOrigin, One, Saturating, Zero},
+	RuntimeDebug, DispatchErrorWithPostInfo,
 };
+use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
+
 use frame_support::{
-	decl_module, decl_storage, decl_event, decl_error,
-	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},
+	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},
 	traits::{
-		Get,
-		schedule::{self, DispatchTime},
-		OriginTrait, EnsureOrigin, IsType,
+		schedule::{self, DispatchTime, MaybeHashed},
+		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,
+		StorageVersion,
 	},
 	weights::{GetDispatchInfo, Weight},
 };
-use frame_system::{self as system, ensure_signed};
-pub use weights::WeightInfo;
-use up_sponsorship::SponsorshipHandler;
-use scale_info::TypeInfo;
 
-/// 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
-/// should be added to our implied traits list.
-///
-/// `system::Config` should always be included in our implied traits.
-/// //
-pub trait Config: system::Config {
-	/// The overarching event type.
-	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;
-
-	/// The aggregated origin which the dispatch will take.
-	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
-		+ From<Self::PalletsOrigin>
-		+ IsType<<Self as system::Config>::Origin>;
-
-	/// The caller origin, overarching type of all pallets origins.
-	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;
-
-	/// The aggregated call type.
-	type Call: Parameter
-		+ Dispatchable<Origin = <Self as Config>::Origin>
-		+ GetDispatchInfo
-		+ From<system::Call<Self>>;
-
-	/// The maximum weight that may be scheduled per block for any dispatchables of less priority
-	/// than `schedule::HARD_DEADLINE`.
-	type MaximumWeight: Get<Weight>;
-
-	/// Required origin to schedule or cancel calls.
-	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;
-
-	/// The maximum number of scheduled calls in the queue for a single block.
-	/// 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;
-}
+pub use weights::WeightInfo;
 
-// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;
-
 /// Just a simple index for naming period tasks.
 pub type PeriodicIndex = u32;
 /// The location of a scheduled task that can be used to remove it.
 pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
+pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;
 
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
-#[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>>,
-}
+type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];
+pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;
 
 /// 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 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {
 	/// The unique identity for this task, if there is one.
-	maybe_id: Option<Vec<u8>>,
+	maybe_id: Option<ScheduledId>,
 	/// This task's priority.
 	priority: schedule::Priority,
 	/// The call to be dispatched.
@@ -168,63 +97,213 @@
 	_phantom: PhantomData<AccountId>,
 }
 
+pub type ScheduledV3Of<T> = ScheduledV3<
+	CallOrHashOf<T>,
+	<T as frame_system::Config>::BlockNumber,
+	<T as Config>::PalletsOrigin,
+	<T as frame_system::Config>::AccountId,
+>;
+
+pub type ScheduledOf<T> = ScheduledV3Of<T>;
+
 /// The current version of Scheduled struct.
 pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =
-	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;
+	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;
 
-// 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)]
-enum Releases {
-	V1,
-	V2,
+#[cfg(feature = "runtime-benchmarks")]
+mod preimage_provider {
+	use frame_support::traits::PreimageRecipient;
+	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}
+	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}
 }
 
-impl Default for Releases {
-	fn default() -> Self {
-		Releases::V1
-	}
+#[cfg(not(feature = "runtime-benchmarks"))]
+mod preimage_provider {
+	use frame_support::traits::PreimageProvider;
+	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}
+	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}
 }
 
-#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
-pub struct CallSpec {
-	module: u32,
-	method: u32,
+pub use preimage_provider::PreimageProviderAndMaybeRecipient;
+
+pub(crate) trait MarginalWeightInfo: WeightInfo {
+	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {
+		match (periodic, named, resolved) {
+			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),
+			(_, true, None) => {
+				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)
+			}
+			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),
+			(false, true, Some(false)) => {
+				Self::on_initialize_named(2) - Self::on_initialize_named(1)
+			}
+			(true, false, Some(false)) => {
+				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)
+			}
+			(true, true, Some(false)) => {
+				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)
+			}
+			(false, false, Some(true)) => {
+				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)
+			}
+			(false, true, Some(true)) => {
+				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)
+			}
+			(true, false, Some(true)) => {
+				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)
+			}
+			(true, true, Some(true)) => {
+				Self::on_initialize_periodic_named_resolved(2)
+					- Self::on_initialize_periodic_named_resolved(1)
+			}
+		}
+	}
 }
+impl<T: WeightInfo> MarginalWeightInfo for T {}
 
-decl_storage! {
-	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>>>;
+#[frame_support::pallet]
+pub mod pallet {
+	use super::*;
+	use frame_support::{
+		dispatch::PostDispatchInfo,
+		pallet_prelude::*,
+		traits::{schedule::LookupError, PreimageProvider},
+	};
+	use frame_system::pallet_prelude::*;
+
+	/// The current storage version.
+	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);
+
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	#[pallet::storage_version(STORAGE_VERSION)]
+	#[pallet::without_storage_info]
+	pub struct Pallet<T>(_);
+
+	/// `system::Config` should always be included in our implied traits.
+	#[pallet::config]
+	pub trait Config: frame_system::Config {
+		/// The overarching event type.
+		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
+
+		/// The aggregated origin which the dispatch will take.
+		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
+			+ From<Self::PalletsOrigin>
+			+ IsType<<Self as system::Config>::Origin>;
+
+		/// The caller origin, overarching type of all pallets origins.
+		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;
+
+		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;
+
+		/// The aggregated call type.
+		type Call: Parameter
+			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>
+			+ GetDispatchInfo
+			+ From<system::Call<Self>>;
 
-		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber
-			=> Vec<Option<CallSpec>>;
+		/// The maximum weight that may be scheduled per block for any dispatchables of less
+		/// priority than `schedule::HARD_DEADLINE`.
+		#[pallet::constant]
+		type MaximumWeight: Get<Weight>;
 
-		/// Lookup from identity to the block number and index of the task.
-		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;
+		/// Required origin to schedule or cancel calls.
+		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;
 
-		/// Storage version of the pallet.
+		/// Compare the privileges of origins.
+		///
+		/// This will be used when canceling a task, to ensure that the origin that tries
+		/// to cancel has greater or equal privileges as the origin that created the scheduled task.
 		///
-		/// New networks start with last version.
-		StorageVersion build(|_| Releases::V2): Releases;
+		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can
+		/// be used. This will only check if two given origins are equal.
+		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;
+
+		/// The maximum number of scheduled calls in the queue for a single block.
+		/// Not strictly enforced, but used for weight estimation.
+		#[pallet::constant]
+		type MaxScheduledPerBlock: Get<u32>;
+
+		/// Weight information for extrinsics in this pallet.
+		type WeightInfo: WeightInfo;
+
+		/// The preimage provider with which we look up call hashes to get the call.
+		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;
+
+		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.
+		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;
+
+		/// Sponsoring function.
+		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
+
+		/// The helper type used for custom transaction fee logic.
+		type CallExecutor: DispatchCall<Self, H160>;
 	}
-}
 
-decl_event!(
-	pub enum Event<T> where <T as system::Config>::BlockNumber {
-		/// Scheduled some task. \[when, index\]
-		Scheduled(BlockNumber, u32),
-		/// Canceled some task. \[when, index\]
-		Canceled(BlockNumber, u32),
-		/// Dispatched some task. \[task, id, result\]
-		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),
+	/// A Scheduler-Runtime interface for finer payment handling.
+	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
+		fn reserve_balance(
+			id: ScheduledId,
+			sponsor: <T as frame_system::Config>::AccountId,
+			call: <T as Config>::Call,
+			count: u32,
+		) -> Result<(), DispatchError>;
+
+		fn pay_for_call(
+			id: ScheduledId,
+			sponsor: <T as frame_system::Config>::AccountId,
+			call: <T as Config>::Call,
+		) -> Result<u128, DispatchError>;
+
+		/// Resolve the call dispatch, including any post-dispatch operations.
+		fn dispatch_call(
+			signer: T::AccountId,
+			function: <T as Config>::Call,
+		) -> Result<
+			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+			TransactionValidityError,
+		>;
+
+		fn cancel_reserve(
+			id: ScheduledId,
+			sponsor: <T as frame_system::Config>::AccountId,
+		) -> Result<u128, DispatchError>;
 	}
-);
 
-decl_error! {
-	pub enum Error for Module<T: Config> {
+	/// Items to be executed, indexed by the block number that they should be executed on.
+	#[pallet::storage]
+	pub type Agenda<T: Config> =
+		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;
+
+	/// Lookup from identity to the block number and index of the task.
+	#[pallet::storage]
+	pub(crate) type Lookup<T: Config> =
+		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;
+
+	/// Events type.
+	#[pallet::event]
+	#[pallet::generate_deposit(pub(super) fn deposit_event)]
+	pub enum Event<T: Config> {
+		/// Scheduled some task.
+		Scheduled { when: T::BlockNumber, index: u32 },
+		/// Canceled some task.
+		Canceled { when: T::BlockNumber, index: u32 },
+		/// Dispatched some task.
+		Dispatched {
+			task: TaskAddress<T::BlockNumber>,
+			id: Option<ScheduledId>,
+			result: DispatchResult,
+		},
+		/// The call for the provided hash was not found so the task has been aborted.
+		CallLookupFailed {
+			task: TaskAddress<T::BlockNumber>,
+			id: Option<ScheduledId>,
+			error: LookupError,
+		},
+	}
+
+	#[pallet::error]
+	pub enum Error<T> {
 		/// Failed to schedule a call
 		FailedToSchedule,
 		/// Cannot find the scheduled call.
@@ -234,249 +313,268 @@
 		/// Reschedule failed because it does not change scheduled time.
 		RescheduleNoChange,
 	}
-}
 
-decl_module! {
-	/// Scheduler module declaration.
-	pub struct Module<T: Config> for enum Call
-	where
-		origin: <T as system::Config>::Origin
-	{
-		type Error = Error<T>;
-		fn deposit_event() = default;
+	#[pallet::hooks]
+	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+		/// Execute the scheduled calls
+		fn on_initialize(now: T::BlockNumber) -> Weight {
+			let limit = T::MaximumWeight::get();
 
+			let mut queued = Agenda::<T>::take(now)
+				.into_iter()
+				.enumerate()
+				.filter_map(|(index, s)| Some((index as u32, s?)))
+				.collect::<Vec<_>>();
 
-		/// Anonymously schedule a task.
-		///
-		/// # <weight>
-		/// - S = Number of already scheduled calls
-		/// - Base Weight: 22.29 + .126 * S µs
-		/// - DB Weight:
-		///     - Read: Agenda
-		///     - Write: Agenda
-		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls
-		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
-		fn schedule(origin,
-			when: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: schedule::Priority,
-			call: Box<<T as Config>::Call>,
-		)
-		{
-			let origin = <T as Config>::Origin::from(origin);
-			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;
-		}
+			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {
+				log::warn!(
+					target: "runtime::scheduler",
+					"Warning: This block has more items queued in Scheduler than \
+					expected from the runtime configuration. An update might be needed."
+				);
+			}
 
-		/// Cancel an anonymously scheduled task.
-		///
-		/// # <weight>
-		/// - S = Number of already scheduled calls
-		/// - Base Weight: 22.15 + 2.869 * S µs
-		/// - DB Weight:
-		///     - Read: Agenda
-		///     - Write: Agenda, Lookup
-		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls
-		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]
-		fn cancel(origin, when: T::BlockNumber, index: u32) {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::Origin::from(origin);
-			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
+			queued.sort_by_key(|(_, s)| s.priority);
+
+			let next = now + One::one();
+
+			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);
+			for (order, (index, mut s)) in queued.into_iter().enumerate() {
+				let named = if let Some(ref id) = s.maybe_id {
+					Lookup::<T>::remove(id);
+					true
+				} else {
+					false
+				};
+
+				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();
+				s.call = call;
+
+				let resolved = if let Some(completed) = maybe_completed {
+					T::PreimageProvider::unrequest_preimage(&completed);
+					true
+				} else {
+					false
+				};
+				let call = match s.call.as_value().cloned() {
+					Some(c) => c,
+					None => {
+						// Preimage not available - postpone until some block.
+						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));
+						if let Some(delay) = T::NoPreimagePostponement::get() {
+							let until = now.saturating_add(delay);
+							if let Some(ref id) = s.maybe_id {
+								let index = Agenda::<T>::decode_len(until).unwrap_or(0);
+								Lookup::<T>::insert(id, (until, index as u32));
+							}
+							Agenda::<T>::append(until, Some(s));
+						}
+						continue;
+					}
+				};
+
+				let periodic = s.maybe_periodic.is_some();
+				let call_weight = call.get_dispatch_info().weight;
+				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));
+				let origin =
+					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())
+						.into();
+				if ensure_signed(origin).is_ok() {
+					// Weights of Signed dispatches expect their signing account to be whitelisted.
+					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
+				}
+
+				// We allow a scheduled call if any is true:
+				// - It's priority is `HARD_DEADLINE`
+				// - It does not push the weight past the limit.
+				// - It is the first item in the schedule
+				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;
+				let test_weight = total_weight
+					.saturating_add(call_weight)
+					.saturating_add(item_weight);
+				if !hard_deadline && order > 0 && test_weight > limit {
+					// Cannot be scheduled this block - postpone until next.
+					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));
+					if let Some(ref id) = s.maybe_id {
+						// NOTE: We could reasonably not do this (in which case there would be one
+						// block where the named and delayed item could not be referenced by name),
+						// but we will do it anyway since it should be mostly free in terms of
+						// weight and it is slightly cleaner.
+						let index = Agenda::<T>::decode_len(next).unwrap_or(0);
+						Lookup::<T>::insert(id, (next, index as u32));
+					}
+					Agenda::<T>::append(next, Some(s));
+					continue;
+				}
+
+				let sender = ensure_signed(
+					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())
+						.into(),
+				)
+				.unwrap();
+
+				// // if call have id it was be reserved
+				// if s.maybe_id.is_some() {
+				// 	let _ = T::CallExecutor::pay_for_call(
+				// 		s.maybe_id.unwrap(),
+				// 		sender.clone(),
+				// 		call.clone(),
+				// 	);
+				// }
+
+				let r = T::CallExecutor::dispatch_call(sender, call.clone());
+
+				let mut actual_call_weight: Weight = item_weight;
+				let result: Result<_, DispatchError> = match r {
+					Ok(o) => match o {
+						Ok(di) => {
+							actual_call_weight = di.actual_weight.unwrap_or(item_weight);
+							Ok(())
+						}
+						Err(err) => Err(err.error),
+					},
+					Err(_) => {
+						log::error!(
+							target: "runtime::scheduler",
+							"Warning: Scheduler has failed to execute a post-dispatch transaction. \
+							This block might have become invalid.");
+						Err(DispatchError::CannotLookup)
+					} // todo possibly force a skip/return here, do something with the error
+				};
+
+				total_weight.saturating_accrue(item_weight);
+				total_weight.saturating_accrue(actual_call_weight);
+
+				Self::deposit_event(Event::Dispatched {
+					task: (now, index),
+					id: s.maybe_id.clone(),
+					result,
+				});
+
+				if let &Some((period, count)) = &s.maybe_periodic {
+					if count > 1 {
+						s.maybe_periodic = Some((period, count - 1));
+					} else {
+						s.maybe_periodic = None;
+					}
+					let wake = now + period;
+					// If scheduled is named, place its information in `Lookup`
+					if let Some(ref id) = s.maybe_id {
+						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);
+						Lookup::<T>::insert(id, (wake, wake_index as u32));
+					}
+					Agenda::<T>::append(wake, Some(s));
+				}
+			}
+			0
+			//total_weight
 		}
+	}
 
+	#[pallet::call]
+	impl<T: Config> Pallet<T> {
 		/// Schedule a named task.
-		///
-		/// # <weight>
-		/// - S = Number of already scheduled calls
-		/// - Base Weight: 29.6 + .159 * S µs
-		/// - DB Weight:
-		///     - Read: Agenda, Lookup
-		///     - Write: Agenda, Lookup
-		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls
-		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
-		fn schedule_named(origin,
-			id: Vec<u8>,
+		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+		pub fn schedule_named(
+			origin: OriginFor<T>,
+			id: ScheduledId,
 			when: T::BlockNumber,
 			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
 			priority: schedule::Priority,
-			call: Box<<T as Config>::Call>,
-		) {
+			call: Box<CallOrHashOf<T>>,
+		) -> DispatchResult {
 			T::ScheduleOrigin::ensure_origin(origin.clone())?;
 			let origin = <T as Config>::Origin::from(origin);
 			Self::do_schedule_named(
-				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call
+				id,
+				DispatchTime::At(when),
+				maybe_periodic,
+				priority,
+				origin.caller().clone(),
+				*call,
 			)?;
+			Ok(())
 		}
 
 		/// Cancel a named scheduled task.
-		///
-		/// # <weight>
-		/// - S = Number of already scheduled calls
-		/// - Base Weight: 24.91 + 2.907 * S µs
-		/// - DB Weight:
-		///     - Read: Agenda, Lookup
-		///     - Write: Agenda, Lookup
-		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls
-		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]
-		fn cancel_named(origin, id: Vec<u8>) {
+		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
+		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {
 			T::ScheduleOrigin::ensure_origin(origin.clone())?;
 			let origin = <T as Config>::Origin::from(origin);
 			Self::do_cancel_named(Some(origin.caller().clone()), id)?;
-		}
-
-		/// Anonymously schedule a task after a delay.
-		///
-		/// # <weight>
-		/// Same as [`schedule`].
-		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
-		fn schedule_after(origin,
-			after: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: schedule::Priority,
-			call: Box<<T as Config>::Call>,
-		) {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::Origin::from(origin);
-			Self::do_schedule(
-				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
-			)?;
+			Ok(())
 		}
 
 		/// Schedule a named task after a delay.
 		///
 		/// # <weight>
-		/// Same as [`schedule_named`].
+		/// Same as [`schedule_named`](Self::schedule_named).
 		/// # </weight>
-		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
-		fn schedule_named_after(origin,
-			id: Vec<u8>,
+		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+		pub fn schedule_named_after(
+			origin: OriginFor<T>,
+			id: ScheduledId,
 			after: T::BlockNumber,
 			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
 			priority: schedule::Priority,
-			call: Box<<T as Config>::Call>,
-		) {
+			call: Box<CallOrHashOf<T>>,
+		) -> DispatchResult {
 			T::ScheduleOrigin::ensure_origin(origin.clone())?;
 			let origin = <T as Config>::Origin::from(origin);
 			Self::do_schedule_named(
-				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
+				id,
+				DispatchTime::After(after),
+				maybe_periodic,
+				priority,
+				origin.caller().clone(),
+				*call,
 			)?;
+			Ok(())
 		}
-
-		/// Execute the scheduled calls
-		///
-		/// # <weight>
-		/// - S = Number of already scheduled calls
-		/// - N = Named scheduled calls
-		/// - P = Periodic Calls
-		/// - Base Weight: 9.243 + 23.45 * S µs
-		/// - DB Weight:
-		///     - Read: Agenda + Lookup * N + Agenda(Future) * P
-		///     - Write: Agenda + Lookup * N  + Agenda(future) * P
-		/// # </weight>
-		fn on_initialize(now: T::BlockNumber) -> Weight {
-			let limit = T::MaximumWeight::get();
-			let mut queued = Agenda::<T>::take(now).into_iter()
-				.enumerate()
-				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))
-				.collect::<Vec<_>>();
-			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {
-				log::warn!(
-					target: "runtime::scheduler",
-					"Warning: This block has more items queued in Scheduler than \
-					expected from the runtime configuration. An update might be needed."
-				);
-			}
-			queued.sort_by_key(|(_, s)| s.priority);
-			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)
-			let mut total_weight: Weight = 0;
-			queued.into_iter()
-				.enumerate()
-				.scan(base_weight, |cumulative_weight, (order, (index, s))| {
-					*cumulative_weight = cumulative_weight
-						.saturating_add(s.call.get_dispatch_info().weight);
-
-					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
-						s.origin.clone()
-					).into();
-
-					if ensure_signed(origin).is_ok() {
-						 // AccountData for inner call origin accountdata.
-						*cumulative_weight = cumulative_weight
-							.saturating_add(T::DbWeight::get().reads_writes(1, 1));
-					}
-
-					if s.maybe_id.is_some() {
-						// Remove/Modify Lookup
-						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));
-					}
-					if s.maybe_periodic.is_some() {
-						// Read/Write Agenda for future block
-						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));
-					}
+	}
+}
 
-					Some((order, index, *cumulative_weight, s))
-				})
-				.filter_map(|(order, index, cumulative_weight, mut s)| {
-					// We allow a scheduled call if any is true:
-					// - It's priority is `HARD_DEADLINE`
-					// - It does not push the weight past the limit.
-					// - It is the first item in the schedule
-					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
+impl<T: Config> Pallet<T> {
+	#[cfg(feature = "try-runtime")]
+	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {
+		Ok(())
+	}
 
-						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
-							s.origin.clone()
-						).into();
-						let sender = match ensure_signed(origin) {
-							Ok(v) => v,
-							// TODO: Support for unsigned extrinsics?
-							Err(_) => return Some(Some(s))
-						};
-						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 {
-								s.maybe_periodic = Some((period, count - 1));
-							} else {
-								s.maybe_periodic = None;
-							}
-							let next = now + period;
-							// If scheduled is named, place it's information in `Lookup`
-							if let Some(ref id) = s.maybe_id {
-								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);
-								Lookup::<T>::insert(id, (next, next_index as u32));
-							}
-							Agenda::<T>::append(next, Some(s));
-						} else if let Some(ref id) = s.maybe_id {
-									  Lookup::<T>::remove(id);
-								  }
-						Self::deposit_event(RawEvent::Dispatched(
-							(now, index),
-							maybe_id,
-							r.map(|_| ()).map_err(|e| e.error)
-						));
-						total_weight = cumulative_weight;
-						None
-					} else {
-						Some(Some(s))
-					}
-				})
-				.for_each(|unused| {
-					let next = now + One::one();
-					Agenda::<T>::append(next, unused);
-				});
+	#[cfg(feature = "try-runtime")]
+	pub fn post_migrate_to_v3() -> Result<(), &'static str> {
+		use frame_support::dispatch::GetStorageVersion;
 
-			total_weight
+		assert!(Self::current_storage_version() == 3);
+		for k in Agenda::<T>::iter_keys() {
+			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;
 		}
+		Ok(())
+	}
+
+	/// Helper to migrate scheduler when the pallet origin type has changed.
+	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {
+		Agenda::<T>::translate::<
+			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,
+			_,
+		>(|_, agenda| {
+			Some(
+				agenda
+					.into_iter()
+					.map(|schedule| {
+						schedule.map(|schedule| Scheduled {
+							maybe_id: schedule.maybe_id,
+							priority: schedule.priority,
+							call: schedule.call,
+							maybe_periodic: schedule.maybe_periodic,
+							origin: schedule.origin.into(),
+							_phantom: Default::default(),
+						})
+					})
+					.collect::<Vec<_>>(),
+			)
+		});
 	}
-}
 
-impl<T: Config> Module<T> {
 	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
 		let now = frame_system::Pallet::<T>::block_number();
 
@@ -499,9 +597,10 @@
 		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
 		priority: schedule::Priority,
 		origin: T::PalletsOrigin,
-		call: <T as Config>::Call,
+		call: CallOrHashOf<T>,
 	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
 		let when = Self::resolve_time(when)?;
+		call.ensure_requested::<T::PreimageProvider>();
 
 		// sanitize maybe_periodic
 		let maybe_periodic = maybe_periodic
@@ -518,14 +617,7 @@
 		});
 		Agenda::<T>::append(when, s);
 		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
-		if index > T::MaxScheduledPerBlock::get() {
-			log::warn!(
-				target: "runtime::scheduler",
-				"Warning: There are more items queued in the Scheduler than \
-				expected from the runtime configuration. An update might be needed.",
-			);
-		}
-		Self::deposit_event(RawEvent::Scheduled(when, index));
+		Self::deposit_event(Event::Scheduled { when, index });
 
 		Ok((when, index))
 	}
@@ -539,7 +631,10 @@
 				Ok(None),
 				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
 					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
-						if *o != s.origin {
+						if matches!(
+							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
+							Some(Ordering::Less) | None
+						) {
 							return Err(BadOrigin.into());
 						}
 					};
@@ -548,13 +643,14 @@
 			)
 		})?;
 		if let Some(s) = scheduled {
+			s.call.ensure_unrequested::<T::PreimageProvider>();
 			if let Some(id) = s.maybe_id {
 				Lookup::<T>::remove(id);
 			}
-			Self::deposit_event(RawEvent::Canceled(when, index));
+			Self::deposit_event(Event::Canceled { when, index });
 			Ok(())
 		} else {
-			Err(Error::<T>::NotFound.into())
+			Err(Error::<T>::NotFound)?
 		}
 	}
 
@@ -576,27 +672,32 @@
 		})?;
 
 		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;
-		Self::deposit_event(RawEvent::Canceled(when, index));
-		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));
+		Self::deposit_event(Event::Canceled { when, index });
+		Self::deposit_event(Event::Scheduled {
+			when: new_time,
+			index: new_index,
+		});
 
 		Ok((new_time, new_index))
 	}
 
 	fn do_schedule_named(
-		id: Vec<u8>,
+		id: ScheduledId,
 		when: DispatchTime<T::BlockNumber>,
 		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
 		priority: schedule::Priority,
 		origin: T::PalletsOrigin,
-		call: <T as Config>::Call,
+		call: CallOrHashOf<T>,
 	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
 		// ensure id it is unique
 		if Lookup::<T>::contains_key(&id) {
-			return Err(Error::<T>::FailedToSchedule.into());
+			return Err(Error::<T>::FailedToSchedule)?;
 		}
 
 		let when = Self::resolve_time(when)?;
 
+		call.ensure_requested::<T::PreimageProvider>();
+
 		// sanitize maybe_periodic
 		let maybe_periodic = maybe_periodic
 			.filter(|p| p.1 > 1 && !p.0.is_zero())
@@ -606,52 +707,74 @@
 		let s = Scheduled {
 			maybe_id: Some(id.clone()),
 			priority,
-			call,
+			call: call.clone(),
 			maybe_periodic,
-			origin,
+			origin: origin.clone(),
 			_phantom: Default::default(),
 		};
+
+		// reserve balance for periodic execution
+		// let sender =
+		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;
+		// let repeats = match maybe_periodic {
+		// 	Some(p) => p.1,
+		// 	None => 1,
+		// };
+		// let _ = T::CallExecutor::reserve_balance(
+		// 	id.clone(),
+		// 	sender,
+		// 	call.as_value().unwrap().clone(),
+		// 	repeats,
+		// );
+
 		Agenda::<T>::append(when, Some(s));
 		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
-		if index > T::MaxScheduledPerBlock::get() {
-			log::warn!(
-				target: "runtime::scheduler",
-				"Warning: There are more items queued in the Scheduler than \
-				expected from the runtime configuration. An update might be needed.",
-			);
-		}
 		let address = (when, index);
 		Lookup::<T>::insert(&id, &address);
-		Self::deposit_event(RawEvent::Scheduled(when, index));
+		Self::deposit_event(Event::Scheduled { when, index });
 
 		Ok(address)
 	}
 
-	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {
+	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {
 		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
 			if let Some((when, index)) = lookup.take() {
 				let i = index as usize;
 				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
 					if let Some(s) = agenda.get_mut(i) {
-						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
-							if *o != s.origin {
+						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {
+							if matches!(
+								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
+								Some(Ordering::Less) | None
+							) {
 								return Err(BadOrigin.into());
 							}
+							// release balance reserve
+							// let sender = ensure_signed(
+							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(
+							// 		origin.unwrap(),
+							// 	)
+							// 	.into(),
+							// )?;
+							// let _ = T::CallExecutor::cancel_reserve(id, sender);
+
+							s.call.ensure_unrequested::<T::PreimageProvider>();
 						}
 						*s = None;
 					}
 					Ok(())
 				})?;
-				Self::deposit_event(RawEvent::Canceled(when, index));
+
+				Self::deposit_event(Event::Canceled { when, index });
 				Ok(())
 			} else {
-				Err(Error::<T>::NotFound.into())
+				Err(Error::<T>::NotFound)?
 			}
 		})
 	}
 
 	fn do_reschedule_named(
-		id: Vec<u8>,
+		id: ScheduledId,
 		new_time: DispatchTime<T::BlockNumber>,
 	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
 		let new_time = Self::resolve_time(new_time)?;
@@ -674,8 +797,11 @@
 				})?;
 
 				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;
-				Self::deposit_event(RawEvent::Canceled(when, index));
-				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));
+				Self::deposit_event(Event::Canceled { when, index });
+				Self::deposit_event(Event::Scheduled {
+					when: new_time,
+					index: new_index,
+				});
 
 				*lookup = Some((new_time, new_index));
 
@@ -684,161 +810,86 @@
 		)
 	}
 }
-
-#[cfg(test)]
-#[allow(clippy::from_over_into)]
-mod tests {
-	use super::*;
 
-	use frame_support::{
-		ord_parameter_types, parameter_types,
-		traits::{Contains, ConstU32, EnsureOneOf},
-		weights::constants::RocksDbWeight,
-	};
-	use sp_core::H256;
-	use sp_runtime::{
-		Perbill,
-		testing::Header,
-		traits::{BlakeTwo256, IdentityLookup},
-	};
-	use frame_system::{EnsureRoot, EnsureSignedBy};
-	use crate as scheduler;
+impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>
+	for Pallet<T>
+{
+	type Address = TaskAddress<T::BlockNumber>;
+	type Hash = T::Hash;
 
-	#[frame_support::pallet]
-	pub mod logger {
-		use super::{OriginCaller, OriginTrait};
-		use frame_support::pallet_prelude::*;
-		use frame_system::pallet_prelude::*;
-		use std::cell::RefCell;
-
-		thread_local! {
-			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());
-		}
-		pub fn log() -> Vec<(OriginCaller, u32)> {
-			LOG.with(|log| log.borrow().clone())
-		}
-
-		#[pallet::pallet]
-		#[pallet::generate_store(pub(super) trait Store)]
-		pub struct Pallet<T>(PhantomData<T>);
-
-		#[pallet::hooks]
-		impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
-
-		#[pallet::config]
-		pub trait Config: frame_system::Config {
-			type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
-		}
-
-		#[pallet::event]
-		#[pallet::generate_deposit(pub(super) fn deposit_event)]
-		pub enum Event<T: Config> {
-			Logged(u32, Weight),
-		}
+	fn schedule(
+		when: DispatchTime<T::BlockNumber>,
+		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+		priority: schedule::Priority,
+		origin: T::PalletsOrigin,
+		call: CallOrHashOf<T>,
+	) -> Result<Self::Address, DispatchError> {
+		Self::do_schedule(when, maybe_periodic, priority, origin, call)
+	}
 
-		#[pallet::call]
-		impl<T: Config> Pallet<T>
-		where
-			<T as frame_system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>,
-		{
-			#[pallet::weight(*weight)]
-			pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
-				Self::deposit_event(Event::Logged(i, weight));
-				LOG.with(|log| {
-					log.borrow_mut().push((origin.caller().clone(), i));
-				});
-				Ok(())
-			}
+	fn cancel((when, index): Self::Address) -> Result<(), ()> {
+		Self::do_cancel(None, (when, index)).map_err(|_| ())
+	}
 
-			#[pallet::weight(*weight)]
-			pub fn log_without_filter(
-				origin: OriginFor<T>,
-				i: u32,
-				weight: Weight,
-			) -> DispatchResult {
-				Self::deposit_event(Event::Logged(i, weight));
-				LOG.with(|log| {
-					log.borrow_mut().push((origin.caller().clone(), i));
-				});
-				Ok(())
-			}
-		}
+	fn reschedule(
+		address: Self::Address,
+		when: DispatchTime<T::BlockNumber>,
+	) -> Result<Self::Address, DispatchError> {
+		Self::do_reschedule(address, when)
 	}
 
-	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
-	type Block = frame_system::mocking::MockBlock<Test>;
+	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {
+		Agenda::<T>::get(when)
+			.get(index as usize)
+			.ok_or(())
+			.map(|_| when)
+	}
+}
 
-	frame_support::construct_runtime!(
-		pub enum Test where
-			Block = Block,
-			NodeBlock = Block,
-			UncheckedExtrinsic = UncheckedExtrinsic,
-		{
-			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-			Logger: logger::{Pallet, Call, Event<T>},
-			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},
-		}
-	);
+impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>
+	for Pallet<T>
+{
+	type Address = TaskAddress<T::BlockNumber>;
+	type Hash = T::Hash;
 
-	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
-	pub struct BaseFilter;
-	impl Contains<Call> for BaseFilter {
-		fn contains(call: &Call) -> bool {
-			!matches!(call, Call::Logger(logger::Call::log { .. }))
-		}
+	fn schedule_named(
+		id: Vec<u8>,
+		when: DispatchTime<T::BlockNumber>,
+		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+		priority: schedule::Priority,
+		origin: T::PalletsOrigin,
+		call: CallOrHashOf<T>,
+	) -> Result<Self::Address, ()> {
+		let inner_id: ScheduledId = id
+			.try_into()
+			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)
+			.map_err(|_| ())
 	}
 
-	parameter_types! {
-		pub const BlockHashCount: u64 = 250;
-		pub BlockWeights: frame_system::limits::BlockWeights =
-			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);
+	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {
+		let inner_id: ScheduledId = id
+			.try_into()
+			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+		Self::do_cancel_named(None, inner_id).map_err(|_| ())
 	}
-	impl system::Config for Test {
-		type BaseCallFilter = BaseFilter;
-		type BlockWeights = ();
-		type BlockLength = ();
-		type DbWeight = RocksDbWeight;
-		type Origin = Origin;
-		type Call = Call;
-		type Index = u64;
-		type BlockNumber = u64;
-		type Hash = H256;
-		type Hashing = BlakeTwo256;
-		type AccountId = u64;
-		type Lookup = IdentityLookup<Self::AccountId>;
-		type Header = Header;
-		type Event = Event;
-		type BlockHashCount = BlockHashCount;
-		type Version = ();
-		type PalletInfo = PalletInfo;
-		type AccountData = ();
-		type OnNewAccount = ();
-		type OnKilledAccount = ();
-		type SystemWeightInfo = ();
-		type SS58Prefix = ();
-		type OnSetCode = ();
-		type MaxConsumers = ConstU32<16>;
-	}
-	impl logger::Config for Test {
-		type Event = Event;
-	}
-	parameter_types! {
-		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
-		pub const MaxScheduledPerBlock: u32 = 10;
-	}
-	ord_parameter_types! {
-		pub const One: u64 = 1;
+
+	fn reschedule_named(
+		id: Vec<u8>,
+		when: DispatchTime<T::BlockNumber>,
+	) -> Result<Self::Address, DispatchError> {
+		let inner_id: ScheduledId = id
+			.try_into()
+			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+		Self::do_reschedule_named(inner_id, when)
 	}
 
-	impl Config for Test {
-		type Event = Event;
-		type Origin = Origin;
-		type PalletsOrigin = OriginCaller;
-		type Call = Call;
-		type MaximumWeight = MaximumSchedulerWeight;
-		type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
-		type MaxScheduledPerBlock = MaxScheduledPerBlock;
-		type WeightInfo = ();
-		type SponsorshipHandler = ();
+	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {
+		let inner_id: ScheduledId = id
+			.try_into()
+			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+		Lookup::<T>::get(inner_id)
+			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))
+			.ok_or(())
 	}
 }
modifiedpallets/scheduler/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/weights.rs
+++ b/pallets/scheduler/src/weights.rs
@@ -1,23 +1,6 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license
 // This file is part of Substrate.
 
-// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
+// Copyright (C) 2022 Parity Technologies (UK) Ltd.
 // SPDX-License-Identifier: Apache-2.0
 
 // Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,13 +15,14 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! Weights for pallet_scheduler
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0
-//! DATE: 2020-10-27, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: [], HIGH RANGE: []
-//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
+//! Autogenerated weights for pallet_scheduler
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
 
 // Executed Command:
-// target/release/substrate
+// ./target/production/substrate
 // benchmark
 // --chain=dev
 // --steps=50
@@ -49,78 +33,332 @@
 // --wasm-execution=compiled
 // --heap-pages=4096
 // --output=./frame/scheduler/src/weights.rs
-// --template=./.maintain/frame-weight-template.hbs
+// --template=.maintain/frame-weight-template.hbs
+// --header=HEADER-APACHE2
+// --raw
 
+#![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
 
-use frame_support::{
-	traits::Get,
-	weights::{Weight, constants::RocksDbWeight},
-};
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
 
 /// Weight functions needed for pallet_scheduler.
 pub trait WeightInfo {
-	fn schedule(s: u32) -> Weight;
-	fn cancel(s: u32) -> Weight;
-	fn schedule_named(s: u32) -> Weight;
-	fn cancel_named(s: u32) -> Weight;
+	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
+	fn on_initialize_named_resolved(s: u32, ) -> Weight;
+	fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
+	fn on_initialize_resolved(s: u32, ) -> Weight;
+	fn on_initialize_named_aborted(s: u32, ) -> Weight;
+	fn on_initialize_aborted(s: u32, ) -> Weight;
+	fn on_initialize_periodic_named(s: u32, ) -> Weight;
+	fn on_initialize_periodic(s: u32, ) -> Weight;
+	fn on_initialize_named(s: u32, ) -> Weight;
+	fn on_initialize(s: u32, ) -> Weight;
+	fn schedule(s: u32, ) -> Weight;
+	fn cancel(s: u32, ) -> Weight;
+	fn schedule_named(s: u32, ) -> Weight;
+	fn cancel_named(s: u32, ) -> Weight;
 }
 
 /// Weights for pallet_scheduler using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	fn schedule(s: u32) -> Weight {
-		35_029_000_u64
-			.saturating_add(77_000_u64.saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1_u64))
-			.saturating_add(T::DbWeight::get().writes(1_u64))
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+		(11_587_000 as Weight)
+			// Standard Error: 17_000
+			.saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named_resolved(s: u32, ) -> Weight {
+		(8_965_000 as Weight)
+			// Standard Error: 11_000
+			.saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
 	}
-	fn cancel(s: u32) -> Weight {
-		31_419_000_u64
-			.saturating_add(4_015_000_u64.saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1_u64))
-			.saturating_add(T::DbWeight::get().writes(2_u64))
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+		(8_654_000 as Weight)
+			// Standard Error: 17_000
+			.saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	fn on_initialize_resolved(s: u32, ) -> Weight {
+		(9_303_000 as Weight)
+			// Standard Error: 10_000
+			.saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named_aborted(s: u32, ) -> Weight {
+		(7_506_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:0)
+	fn on_initialize_aborted(s: u32, ) -> Weight {
+		(8_046_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic_named(s: u32, ) -> Weight {
+		(13_704_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	fn on_initialize_periodic(s: u32, ) -> Weight {
+		(12_668_000 as Weight)
+			// Standard Error: 5_000
+			.saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named(s: u32, ) -> Weight {
+		(13_946_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn on_initialize(s: u32, ) -> Weight {
+		(13_151_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule(s: u32, ) -> Weight {
+		(14_040_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn cancel(s: u32, ) -> Weight {
+		(14_376_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(1 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
-	fn schedule_named(s: u32) -> Weight {
-		44_752_000_u64
-			.saturating_add(123_000_u64.saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(2_u64))
-			.saturating_add(T::DbWeight::get().writes(2_u64))
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule_named(s: u32, ) -> Weight {
+		(16_806_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
-	fn cancel_named(s: u32) -> Weight {
-		35_712_000_u64
-			.saturating_add(4_008_000_u64.saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(2_u64))
-			.saturating_add(T::DbWeight::get().writes(2_u64))
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn cancel_named(s: u32, ) -> Weight {
+		(15_852_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
 }
 
 // For backwards compatibility and tests
 impl WeightInfo for () {
-	fn schedule(s: u32) -> Weight {
-		35_029_000_u64
-			.saturating_add(77_000_u64.saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1_u64))
-			.saturating_add(RocksDbWeight::get().writes(1_u64))
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+		(11_587_000 as Weight)
+			// Standard Error: 17_000
+			.saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named_resolved(s: u32, ) -> Weight {
+		(8_965_000 as Weight)
+			// Standard Error: 11_000
+			.saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
 	}
-	fn cancel(s: u32) -> Weight {
-		31_419_000_u64
-			.saturating_add(4_015_000_u64.saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1_u64))
-			.saturating_add(RocksDbWeight::get().writes(2_u64))
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+		(8_654_000 as Weight)
+			// Standard Error: 17_000
+			.saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
 	}
-	fn schedule_named(s: u32) -> Weight {
-		44_752_000_u64
-			.saturating_add(123_000_u64.saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(2_u64))
-			.saturating_add(RocksDbWeight::get().writes(2_u64))
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Preimage PreimageFor (r:1 w:1)
+	// Storage: Preimage StatusFor (r:1 w:1)
+	fn on_initialize_resolved(s: u32, ) -> Weight {
+		(9_303_000 as Weight)
+			// Standard Error: 10_000
+			.saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
-	fn cancel_named(s: u32) -> Weight {
-		35_712_000_u64
-			.saturating_add(4_008_000_u64.saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(2_u64))
-			.saturating_add(RocksDbWeight::get().writes(2_u64))
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named_aborted(s: u32, ) -> Weight {
+		(7_506_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Preimage PreimageFor (r:1 w:0)
+	fn on_initialize_aborted(s: u32, ) -> Weight {
+		(8_046_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic_named(s: u32, ) -> Weight {
+		(13_704_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:2 w:2)
+	fn on_initialize_periodic(s: u32, ) -> Weight {
+		(12_668_000 as Weight)
+			// Standard Error: 5_000
+			.saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_named(s: u32, ) -> Weight {
+		(13_946_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn on_initialize(s: u32, ) -> Weight {
+		(13_151_000 as Weight)
+			// Standard Error: 4_000
+			.saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule(s: u32, ) -> Weight {
+		(14_040_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn cancel(s: u32, ) -> Weight {
+		(14_376_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule_named(s: u32, ) -> Weight {
+		(16_806_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn cancel_named(s: u32, ) -> Weight {
+		(15_852_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
 }
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -28,6 +28,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::{Member};
 // #[cfg(any(feature = "std", test))]
 // pub use sp_runtime::BuildStorage;
 
@@ -59,7 +61,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -67,8 +69,13 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
-use up_data_structs::*;
+use pallet_unq_scheduler::DispatchCall;
+use up_data_structs::{
+	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+	CollectionStats, RpcCollection,
+	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
+};
+
 // use pallet_contracts::weights::WeightInfo;
 // #[cfg(any(feature = "std", test))]
 use frame_system::{
@@ -79,12 +86,17 @@
 	traits::{BaseArithmetic, Unsigned},
 };
 use smallvec::smallvec;
+// use scale_info::TypeInfo;
 use codec::{Encode, Decode};
 use fp_rpc::TransactionStatus;
 use sp_runtime::{
-	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf, Saturating},
+	traits::{
+		Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf,
+		Saturating, CheckedConversion,
+	},
+	generic::Era,
 	transaction_validity::TransactionValidityError,
-	SaturatedConversion,
+	DispatchErrorWithPostInfo, SaturatedConversion,
 };
 
 // pub use pallet_timestamp::Call as TimestampCall;
@@ -102,7 +114,7 @@
 	ParentIsPreset,
 };
 use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
+use sp_std::{cmp::Ordering, marker::PhantomData};
 
 use xcm::latest::{
 	//	Xcm,
@@ -113,7 +125,6 @@
 };
 use xcm_executor::traits::{MatchesFungible, WeightTrader};
 //use xcm_executor::traits::MatchesFungible;
-use sp_runtime::traits::CheckedConversion;
 
 use unique_runtime_common::{
 	impl_common_runtime_apis,
@@ -406,12 +417,13 @@
 	// pub const ExistentialDeposit: u128 = 500;
 	pub const ExistentialDeposit: u128 = 0;
 	pub const MaxLocks: u32 = 50;
+	pub const MaxReserves: u32 = 50;
 }
 
 impl pallet_balances::Config for Runtime {
 	type MaxLocks = MaxLocks;
-	type MaxReserves = ();
-	type ReserveIdentifier = [u8; 8];
+	type MaxReserves = MaxReserves;
+	type ReserveIdentifier = [u8; 16];
 	/// The type for recording an account's balance.
 	type Balance = Balance;
 	/// The ubiquitous event type.
@@ -930,33 +942,156 @@
 	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
 }
 
-// parameter_types! {
-// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// 		RuntimeBlockWeights::get().max_block;
-// 	pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+		RuntimeBlockWeights::get().max_block;
+	pub const MaxScheduledPerBlock: u32 = 50;
+}
+
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+	(
+		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(),
+		// sponsoring transaction logic
+		// pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+	)
+}
+
+pub struct SchedulerPaymentExecutor;
+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>,
+{
+	fn dispatch_call(
+		signer: <T as frame_system::Config>::AccountId,
+		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,
+			SignedExtraScheduler,
+			SelfContainedSignedInfo,
+		> {
+			signed:
+				CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+					signer.clone().into(),
+					get_signed_extras(signer.into()),
+				),
+			function: call.into(),
+		};
+
+		extrinsic.apply::<Runtime>(&dispatch_info, 0)
+	}
+
+	fn reserve_balance(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+		count: u32,
+	) -> Result<(), DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+			.saturating_mul(count.into());
+
+		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+			&id,
+			&(sponsor.into()),
+			weight,
+		)
+	}
+
+	fn pay_for_call(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<u128, DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				weight,
+			),
+		)
+	}
+
+	fn cancel_reserve(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+	) -> Result<u128, DispatchError> {
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				u128::MAX,
+			),
+		)
+	}
+}
+
+parameter_types! {
+	pub const NoPreimagePostponement: Option<u32> = Some(10);
+	pub const Preimage: Option<u32> = Some(10);
+}
+
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+	fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+		Some(Ordering::Equal)
+	}
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+	type Event = Event;
+	type Origin = Origin;
+	type Currency = Balances;
+	type PalletsOrigin = OriginCaller;
+	type Call = Call;
+	type MaximumWeight = MaximumSchedulerWeight;
+	type ScheduleOrigin = EnsureSigned<AccountId>;
+	type MaxScheduledPerBlock = MaxScheduledPerBlock;
+	type WeightInfo = ();
+	type CallExecutor = SchedulerPaymentExecutor;
+	type OriginPrivilegeCmp = OriginPrivilegeCmp;
+	type PreimageProvider = ();
+	type NoPreimagePostponement = NoPreimagePostponement;
+}
 
 type EvmSponsorshipHandler = (
 	UniqueEthSponsorshipHandler<Runtime>,
 	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
 );
+
 type SponsorshipHandler = (
 	UniqueSponsorshipHandler<Runtime>,
 	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
 	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
 );
-
-// impl pallet_unq_scheduler::Config for Runtime {
-// 	type Event = Event;
-// 	type Origin = Origin;
-// 	type PalletsOrigin = OriginCaller;
-// 	type Call = Call;
-// 	type MaximumWeight = MaximumSchedulerWeight;
-// 	type ScheduleOrigin = EnsureSigned<AccountId>;
-// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// 	type SponsorshipHandler = SponsorshipHandler;
-// 	type WeightInfo = ();
-// }
 
 impl pallet_evm_transaction_payment::Config for Runtime {
 	type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -1020,7 +1155,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1087,10 +1222,17 @@
 	frame_system::CheckEra<Runtime>,
 	frame_system::CheckNonce<Runtime>,
 	frame_system::CheckWeight<Runtime>,
-	pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+	ChargeTransactionPayment,
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 	pallet_ethereum::FakeTransactionFinalizer<Runtime>,
 );
+pub type SignedExtraScheduler = (
+	frame_system::CheckSpecVersion<Runtime>,
+	frame_system::CheckGenesis<Runtime>,
+	frame_system::CheckEra<Runtime>,
+	frame_system::CheckNonce<Runtime>,
+	frame_system::CheckWeight<Runtime>,
+);
 /// Unchecked extrinsic type as expected by this runtime.
 pub type UncheckedExtrinsic =
 	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -33,7 +33,7 @@
 
 use sp_runtime::{
 	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
-	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
+	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero, Member},
 	transaction_validity::{TransactionSource, TransactionValidity},
 	ApplyExtrinsicResult, RuntimeAppPublic,
 };
@@ -58,7 +58,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -81,18 +81,28 @@
 use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};
 use fp_rpc::TransactionStatus;
 use sp_runtime::{
-	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
+	traits::{
+		Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+		CheckedConversion,
+	},
+	generic::Era,
 	transaction_validity::TransactionValidityError,
-	SaturatedConversion,
+	SaturatedConversion, DispatchErrorWithPostInfo,
 };
 
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+
 // pub use pallet_timestamp::Call as TimestampCall;
 pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
 
 // Polkadot imports
 use pallet_xcm::XcmPassthrough;
 use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits, 
+	CollectionStats, RpcCollection, 
+	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -102,7 +112,8 @@
 	ParentIsPreset,
 };
 use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
 
 use xcm::latest::{
 	//	Xcm,
@@ -112,8 +123,6 @@
 	Error as XcmError,
 };
 use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
-use sp_runtime::traits::CheckedConversion;
 
 use unique_runtime_common::{
 	impl_common_runtime_apis,
@@ -390,7 +399,7 @@
 impl pallet_balances::Config for Runtime {
 	type MaxLocks = MaxLocks;
 	type MaxReserves = ();
-	type ReserveIdentifier = [u8; 8];
+	type ReserveIdentifier = [u8; 16];
 	/// The type for recording an account's balance.
 	type Balance = Balance;
 	/// The ubiquitous event type.
@@ -913,11 +922,11 @@
 	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
 }
 
-// parameter_types! {
-// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// 		RuntimeBlockWeights::get().max_block;
-// 	pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+		RuntimeBlockWeights::get().max_block;
+	pub const MaxScheduledPerBlock: u32 = 50;
+}
 
 type EvmSponsorshipHandler = (
 	UniqueEthSponsorshipHandler<Runtime>,
@@ -929,17 +938,34 @@
 	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
 );
 
-// impl pallet_unq_scheduler::Config for Runtime {
-// 	type Event = Event;
-// 	type Origin = Origin;
-// 	type PalletsOrigin = OriginCaller;
-// 	type Call = Call;
-// 	type MaximumWeight = MaximumSchedulerWeight;
-// 	type ScheduleOrigin = EnsureSigned<AccountId>;
-// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// 	type SponsorshipHandler = SponsorshipHandler;
-// 	type WeightInfo = ();
-// }
+parameter_types! {
+	pub const NoPreimagePostponement: Option<u32> = Some(10);
+	pub const Preimage: Option<u32> = Some(10);
+}
+
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+	fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+		Some(Ordering::Equal)
+	}
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+	type Event = Event;
+	type Origin = Origin;
+	type Currency = Balances;
+	type PalletsOrigin = OriginCaller;
+	type Call = Call;
+	type MaximumWeight = MaximumSchedulerWeight;
+	type ScheduleOrigin = EnsureSigned<AccountId>;
+	type MaxScheduledPerBlock = MaxScheduledPerBlock;
+	type WeightInfo = ();
+	type CallExecutor = SchedulerPaymentExecutor;
+	type OriginPrivilegeCmp = OriginPrivilegeCmp;
+	type PreimageProvider = ();
+	type NoPreimagePostponement = NoPreimagePostponement;
+}
 
 impl pallet_evm_transaction_payment::Config for Runtime {
 	type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -954,6 +980,110 @@
 //	 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
 // }
 
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+	(
+		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(),
+		// sponsoring transaction logic
+		// pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+	)
+}
+
+pub struct SchedulerPaymentExecutor;
+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>,
+{
+	fn dispatch_call(
+		signer: <T as frame_system::Config>::AccountId,
+		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,
+			SignedExtraScheduler,
+			SelfContainedSignedInfo,
+		> {
+			signed:
+				CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+					signer.clone().into(),
+					get_signed_extras(signer.into()),
+				),
+			function: call.into(),
+		};
+
+		extrinsic.apply::<Runtime>(&dispatch_info, 0)
+	}
+
+	fn reserve_balance(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+		count: u32,
+	) -> Result<(), DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+			.saturating_mul(count.into());
+
+		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+			&id,
+			&(sponsor.into()),
+			weight.into(),
+		)
+	}
+
+	fn pay_for_call(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<u128, DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				weight.into(),
+			),
+		)
+	}
+
+	fn cancel_reserve(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+	) -> Result<u128, DispatchError> {
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				u128::MAX,
+			),
+		)
+	}
+}
+
 parameter_types! {
 	// 0x842899ECF380553E8a4de75bF534cdf6fBF64049
 	pub const HelpersContractAddress: H160 = H160([
@@ -1003,7 +1133,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1073,6 +1203,15 @@
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 	pallet_ethereum::FakeTransactionFinalizer<Runtime>,
 );
+
+pub type SignedExtraScheduler = (
+	frame_system::CheckSpecVersion<Runtime>,
+	frame_system::CheckGenesis<Runtime>,
+	frame_system::CheckEra<Runtime>,
+	frame_system::CheckNonce<Runtime>,
+	frame_system::CheckWeight<Runtime>,
+	// pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
 /// Unchecked extrinsic type as expected by this runtime.
 pub type UncheckedExtrinsic =
 	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -33,11 +33,20 @@
 
 use sp_runtime::{
 	Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
-	traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
-	transaction_validity::{TransactionSource, TransactionValidity},
-	ApplyExtrinsicResult, RuntimeAppPublic,
+	generic::Era,
+	traits::{
+		Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+		CheckedConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion,
+		Zero, Member,
+	},
+	transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
+	ApplyExtrinsicResult, RuntimeAppPublic, SaturatedConversion, DispatchErrorWithPostInfo,
 };
 
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
+
 use sp_std::prelude::*;
 
 #[cfg(feature = "std")]
@@ -59,7 +68,7 @@
 	traits::{
 		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
 		Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
-		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+		OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
 	},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -86,18 +95,17 @@
 use smallvec::smallvec;
 use codec::{Encode, Decode};
 use fp_rpc::TransactionStatus;
-use sp_runtime::{
-	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
-	transaction_validity::TransactionValidityError,
-	SaturatedConversion,
-};
 
 // pub use pallet_timestamp::Call as TimestampCall;
 
 // Polkadot imports
 use pallet_xcm::XcmPassthrough;
 use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits, 
+	CollectionStats, RpcCollection, 
+	mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
 use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
 use xcm_builder::{
 	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -107,7 +115,6 @@
 	ParentIsPreset,
 };
 use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
 
 use xcm::latest::{
 	//	Xcm,
@@ -117,7 +124,6 @@
 	Error as XcmError,
 };
 use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
 use sp_runtime::traits::CheckedConversion;
 
 use unique_runtime_common::{
@@ -395,7 +401,7 @@
 impl pallet_balances::Config for Runtime {
 	type MaxLocks = MaxLocks;
 	type MaxReserves = ();
-	type ReserveIdentifier = [u8; 8];
+	type ReserveIdentifier = [u8; 16];
 	/// The type for recording an account's balance.
 	type Balance = Balance;
 	/// The ubiquitous event type.
@@ -918,12 +924,145 @@
 	type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
 }
 
-// parameter_types! {
-// 	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// 		RuntimeBlockWeights::get().max_block;
-// 	pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+		RuntimeBlockWeights::get().max_block;
+	pub const MaxScheduledPerBlock: u32 = 50;
+}
+
+parameter_types! {
+	pub const NoPreimagePostponement: Option<u32> = Some(10);
+	pub const Preimage: Option<u32> = Some(10);
+}
 
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+	fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+		Some(Ordering::Equal)
+	}
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+	type Event = Event;
+	type Origin = Origin;
+	type Currency = Balances;
+	type PalletsOrigin = OriginCaller;
+	type Call = Call;
+	type MaximumWeight = MaximumSchedulerWeight;
+	type ScheduleOrigin = EnsureSigned<AccountId>;
+	type MaxScheduledPerBlock = MaxScheduledPerBlock;
+	type WeightInfo = ();
+	type CallExecutor = SchedulerPaymentExecutor;
+	type OriginPrivilegeCmp = OriginPrivilegeCmp;
+	type PreimageProvider = ();
+	type NoPreimagePostponement = NoPreimagePostponement;
+}
+
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+	(
+		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(),
+		// sponsoring transaction logic
+		// pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+	)
+}
+
+pub struct SchedulerPaymentExecutor;
+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>,
+{
+	fn dispatch_call(
+		signer: <T as frame_system::Config>::AccountId,
+		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,
+			SignedExtraScheduler,
+			SelfContainedSignedInfo,
+		> {
+			signed:
+				CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+					signer.clone().into(),
+					get_signed_extras(signer.into()),
+				),
+			function: call.into(),
+		};
+
+		extrinsic.apply::<Runtime>(&dispatch_info, 0)
+	}
+
+	fn reserve_balance(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+		count: u32,
+	) -> Result<(), DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+			.saturating_mul(count.into());
+
+		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+			&id,
+			&(sponsor.into()),
+			weight.into(),
+		)
+	}
+
+	fn pay_for_call(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<u128, DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				weight.into(),
+			),
+		)
+	}
+
+	fn cancel_reserve(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+	) -> Result<u128, DispatchError> {
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				u128::MAX,
+			),
+		)
+	}
+}
+
 type EvmSponsorshipHandler = (
 	UniqueEthSponsorshipHandler<Runtime>,
 	pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
@@ -933,18 +1072,6 @@
 	//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
 	pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
 );
-
-// impl pallet_unq_scheduler::Config for Runtime {
-// 	type Event = Event;
-// 	type Origin = Origin;
-// 	type PalletsOrigin = OriginCaller;
-// 	type Call = Call;
-// 	type MaximumWeight = MaximumSchedulerWeight;
-// 	type ScheduleOrigin = EnsureSigned<AccountId>;
-// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// 	type SponsorshipHandler = SponsorshipHandler;
-// 	type WeightInfo = ();
-// }
 
 impl pallet_evm_transaction_payment::Config for Runtime {
 	type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -1008,7 +1135,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		// Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1078,6 +1205,14 @@
 	//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
 	pallet_ethereum::FakeTransactionFinalizer<Runtime>,
 );
+pub type SignedExtraScheduler = (
+	frame_system::CheckSpecVersion<Runtime>,
+	frame_system::CheckGenesis<Runtime>,
+	frame_system::CheckEra<Runtime>,
+	frame_system::CheckNonce<Runtime>,
+	frame_system::CheckWeight<Runtime>,
+	// pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
 /// Unchecked extrinsic type as expected by this runtime.
 pub type UncheckedExtrinsic =
 	fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -68,6 +68,8 @@
     "testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
     "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
     "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
+    "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
+    "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
     "testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
     "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
     "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
addedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/scheduling.test.ts
@@ -0,0 +1,55 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
+import {scheduleExpectSuccess, waitNewBlocks} from '../util/helpers';
+import privateKey from '../substrate/privateKey';
+
+describe('Scheduing EVM smart contracts', () => {
+  itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3}) => {
+    const deployer = await createEthAccountWithBalance(api, web3);
+    const flipper = await deployFlipper(web3, deployer);
+    const initialValue = await flipper.methods.getValue().call();
+    const alice = privateKey('//Alice');
+    await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+    {
+      const tx = api.tx.evm.call(
+        subToEth(alice.address),
+        flipper.options.address,
+        flipper.methods.flip().encodeABI(),
+        '0',
+        GAS_ARGS.gas,
+        await web3.eth.getGasPrice(),
+        null,
+        null,
+        [],
+      );
+      const waitForBlocks = 4;
+      const periodBlocks = 2;
+
+      await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+      
+      await waitNewBlocks(waitForBlocks - 1);
+      expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+  
+      await waitNewBlocks(periodBlocks);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+    }
+  });
+});
\ No newline at end of file
modifiedtests/src/pallet-presence.test.tsdiffbeforeafterboth
--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -50,7 +50,7 @@
   'unique',
   'nonfungible',
   'refungible',
-  //'scheduler',
+  'scheduler',
   'charging',
 ];
 
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -14,32 +14,197 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-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,
+} from './substrate/substrate-api';
+import {
   createItemExpectSuccess,
   createCollectionExpectSuccess,
   scheduleTransferExpectSuccess,
+  scheduleTransferAndWaitExpectSuccess,
   setCollectionSponsorExpectSuccess,
   confirmSponsorshipExpectSuccess,
+  findUnusedAddress,
+  UNIQUE,
+  enablePublicMintingExpectSuccess,
+  addToAllowListExpectSuccess,
+  waitNewBlocks,
+  normalizeAccountId,
+  getTokenOwner,
+  getGenericResult,
+  scheduleTransferFundsPeriodicExpectSuccess,
+  getFreeBalance,
+  confirmSponsorshipByKeyExpectSuccess,
+  scheduleExpectFailure,
 } from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
 
 chai.use(chaiAsPromised);
 
-describe.skip('Integration Test scheduler base transaction', () => {
-  it('User can transfer owned token with delay (scheduler)', async () => {
+describe.skip('Scheduling token and balance transfers', () => {
+  let alice: IKeyringPair;
+  let bob: IKeyringPair;
+  let scheduledIdBase: string;
+  let scheduledIdSlider: number;
+
+  before(async() => {
     await usingApi(async () => {
-      const alice = privateKey('//Alice');
-      const bob = privateKey('//Bob');
-      // nft
+      alice = privateKey('//Alice');
+      bob = privateKey('//Bob');
+    });
+
+    scheduledIdBase = '0x' + '0'.repeat(31);
+    scheduledIdSlider = 0;
+  });
+
+  // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+  function makeScheduledId(): string {
+    return scheduledIdBase + ((scheduledIdSlider++) % 10);
+  }
+
+  it('Can schedule a transfer of an owned token with delay', async () => {
+    await usingApi(async () => {
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
       await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
       await confirmSponsorshipExpectSuccess(nftCollectionId);
 
-      await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
+    });
+  });
+
+  it('Can transfer funds periodically', async () => {
+    await usingApi(async () => {
+      const waitForBlocks = 4;
+      const period = 2;
+      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+      const bobsBalanceBefore = await getFreeBalance(bob);
+
+      // discounting already waited-for operations
+      await waitNewBlocks(waitForBlocks - 2);
+      const bobsBalanceAfterFirst = await getFreeBalance(bob);
+      expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+      await waitNewBlocks(period);
+      const bobsBalanceAfterSecond = await getFreeBalance(bob);
+      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 bobBalanceBefore = await getFreeBalance(bob);
+      const waitForBlocks = 4;
+      // no need to wait to check, fees must be deducted on scheduling, immediately
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+      const bobBalanceAfter = await getFreeBalance(bob);
+      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+      // wait for sequentiality matters
+      await waitNewBlocks(waitForBlocks - 1);
+    });
+  });
+
+  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, makeScheduledId());
+
+      // Get rid of the account's funds before the scheduled transaction takes place
+      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+      const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+      expect(getGenericResult(events).success).to.be.true;
+      /*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('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+
+    await usingApi(async (api) => {
+      const zeroBalance = await findUnusedAddress(api);
+      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);
+
+      const waitForBlocks = 5;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
+
+      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(waitForBlocks - 3);
+
+      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+    });
+  });
+
+  it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
+    const collectionId = await createCollectionExpectSuccess();
+    await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+    await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+    await usingApi(async (api) => {
+      const zeroBalance = await findUnusedAddress(api);
+
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+      const bobBalanceBefore = await getFreeBalance(bob);
+
+      const createData = {nft: {const_data: [], variable_data: []}};
+      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+
+      /*const badTransaction = async function () {
+        await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+      };
+      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
+
+      await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
+
+      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
     });
   });
 });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
before · tests/src/util/helpers.ts
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617import '../interfaces/augment-api-rpc';18import '../interfaces/augment-api-query';19import {ApiPromise, Keyring} from '@polkadot/api';20import type {AccountId, EventRecord, Event} from '@polkadot/types/interfaces';21import {AnyTuple, IEvent, IKeyringPair} from '@polkadot/types/types';22import {evmToAddress} from '@polkadot/util-crypto';23import BN from 'bn.js';24import chai from 'chai';25import chaiAsPromised from 'chai-as-promised';26import {alicesPublicKey} from '../accounts';27import privateKey from '../substrate/privateKey';28import {default as usingApi, executeTransaction, submitTransactionAsync, submitTransactionExpectFailAsync} from '../substrate/substrate-api';29import {hexToStr, strToUTF16, utf16ToStr} from './util';30import {UpDataStructsRpcCollection, UpDataStructsCreateItemData, UpDataStructsProperty} from '@polkadot/types/lookup';3132chai.use(chaiAsPromised);33const expect = chai.expect;3435export type CrossAccountId = {36  Substrate: string,37} | {38  Ethereum: string,39};4041export function normalizeAccountId(input: string | AccountId | CrossAccountId | IKeyringPair): CrossAccountId {42  if (typeof input === 'string') {43    if (input.length === 48 || input.length === 47) {44      return {Substrate: input};45    } else if (input.length === 42 && input.startsWith('0x')) {46      return {Ethereum: input.toLowerCase()};47    } else if (input.length === 40 && !input.startsWith('0x')) {48      return {Ethereum: '0x' + input.toLowerCase()};49    } else {50      throw new Error(`Unknown address format: "${input}"`);51    }52  }53  if ('address' in input) {54    return {Substrate: input.address};55  }56  if ('Ethereum' in input) {57    return {58      Ethereum: input.Ethereum.toLowerCase(),59    };60  } else if ('ethereum' in input) {61    return {62      Ethereum: (input as any).ethereum.toLowerCase(),63    };64  } else if ('Substrate' in input) {65    return input;66  } else if ('substrate' in input) {67    return {68      Substrate: (input as any).substrate,69    };70  }7172  // AccountId73  return {Substrate: input.toString()};74}75export function toSubstrateAddress(input: string | CrossAccountId | IKeyringPair): string {76  input = normalizeAccountId(input);77  if ('Substrate' in input) {78    return input.Substrate;79  } else {80    return evmToAddress(input.Ethereum);81  }82}8384export const U128_MAX = (1n << 128n) - 1n;8586const MICROUNIQUE = 1_000_000_000_000n;87const MILLIUNIQUE = 1_000n * MICROUNIQUE;88const CENTIUNIQUE = 10n * MILLIUNIQUE;89export const UNIQUE = 100n * CENTIUNIQUE;9091type GenericResult = {92  success: boolean,93};9495interface CreateCollectionResult {96  success: boolean;97  collectionId: number;98}99100interface CreateItemResult {101  success: boolean;102  collectionId: number;103  itemId: number;104  recipient?: CrossAccountId;105}106107interface TransferResult {108  collectionId: number;109  itemId: number;110  sender?: CrossAccountId;111  recipient?: CrossAccountId;112  value: bigint;113}114115interface IReFungibleOwner {116  fraction: BN;117  owner: number[];118}119120interface IGetMessage {121  checkMsgUnqMethod: string;122  checkMsgTrsMethod: string;123  checkMsgSysMethod: string;124}125126export interface IFungibleTokenDataType {127  value: number;128}129130export interface IChainLimits {131  collectionNumbersLimit: number;132  accountTokenOwnershipLimit: number;133  collectionsAdminsLimit: number;134  customDataLimit: number;135  nftSponsorTransferTimeout: number;136  fungibleSponsorTransferTimeout: number;137  refungibleSponsorTransferTimeout: number;138  //offchainSchemaLimit: number;139  //constOnChainSchemaLimit: number;140}141142export interface IReFungibleTokenDataType {143  owner: IReFungibleOwner[];144}145146export function uniqueEventMessage(events: EventRecord[]): IGetMessage {147  let checkMsgUnqMethod = '';148  let checkMsgTrsMethod = '';149  let checkMsgSysMethod = '';150  events.forEach(({event: {method, section}}) => {151    if (section === 'common') {152      checkMsgUnqMethod = method;153    } else if (section === 'treasury') {154      checkMsgTrsMethod = method;155    } else if (section === 'system') {156      checkMsgSysMethod = method;157    } else { return null; }158  });159  const result: IGetMessage = {160    checkMsgUnqMethod,161    checkMsgTrsMethod,162    checkMsgSysMethod,163  };164  return result;165}166167export function getEvent<T extends Event>(events: EventRecord[], check: (event: IEvent<AnyTuple>) => event is T): T | undefined {168  const event = events.find(r => check(r.event));169  if (!event) return;170  return event.event as T;171}172173export function getGenericResult(events: EventRecord[]): GenericResult {174  const result: GenericResult = {175    success: false,176  };177  events.forEach(({event: {method}}) => {178    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);179    if (method === 'ExtrinsicSuccess') {180      result.success = true;181    }182  });183  return result;184}185186187188export function getCreateCollectionResult(events: EventRecord[]): CreateCollectionResult {189  let success = false;190  let collectionId = 0;191  events.forEach(({event: {data, method, section}}) => {192    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);193    if (method == 'ExtrinsicSuccess') {194      success = true;195    } else if ((section == 'common') && (method == 'CollectionCreated')) {196      collectionId = parseInt(data[0].toString(), 10);197    }198  });199  const result: CreateCollectionResult = {200    success,201    collectionId,202  };203  return result;204}205206export function getCreateItemsResult(events: EventRecord[]): CreateItemResult[] {207  let success = false;208  let collectionId = 0;209  let itemId = 0;210  let recipient;211212  const results : CreateItemResult[]  = [];213214  events.forEach(({event: {data, method, section}}) => {215    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);216    if (method == 'ExtrinsicSuccess') {217      success = true;218    } else if ((section == 'common') && (method == 'ItemCreated')) {219      collectionId = parseInt(data[0].toString(), 10);220      itemId = parseInt(data[1].toString(), 10);221      recipient = normalizeAccountId(data[2].toJSON() as any);222223      const itemRes: CreateItemResult = {224        success,225        collectionId,226        itemId,227        recipient,228      };229230      results.push(itemRes);231    }232  });233234  return results;235}236237export function getCreateItemResult(events: EventRecord[]): CreateItemResult {238  let success = false;239  let collectionId = 0;240  let itemId = 0;241  let recipient;242  events.forEach(({event: {data, method, section}}) => {243    // console.log(`    ${phase}: ${section}.${method}:: ${data}`);244    if (method == 'ExtrinsicSuccess') {245      success = true;246    } else if ((section == 'common') && (method == 'ItemCreated')) {247      collectionId = parseInt(data[0].toString(), 10);248      itemId = parseInt(data[1].toString(), 10);249      recipient = normalizeAccountId(data[2].toJSON() as any);250    }251  });252  const result: CreateItemResult = {253    success,254    collectionId,255    itemId,256    recipient,257  };258  return result;259}260261export function getTransferResult(api: ApiPromise, events: EventRecord[]): TransferResult {262  for (const {event} of events) {263    if (api.events.common.Transfer.is(event)) {264      const [collection, token, sender, recipient, value] = event.data;265      return {266        collectionId: collection.toNumber(),267        itemId: token.toNumber(),268        sender: normalizeAccountId(sender.toJSON() as any),269        recipient: normalizeAccountId(recipient.toJSON() as any),270        value: value.toBigInt(),271      };272    }273  }274  throw new Error('no transfer event');275}276277interface Nft {278  type: 'NFT';279}280281interface Fungible {282  type: 'Fungible';283  decimalPoints: number;284}285286interface ReFungible {287  type: 'ReFungible';288}289290type CollectionMode = Nft | Fungible | ReFungible;291292export type Property = {293  key: any,294  value: any,295};296297type Permission = {298  mutable: boolean;299  collectionAdmin: boolean;300  tokenOwner: boolean;301}302303type PropertyPermission = {304  key: any;305  permission: Permission;306}307308export type CreateCollectionParams = {309  mode: CollectionMode,310  name: string,311  description: string,312  tokenPrefix: string,313  properties?: Array<Property>,314  propPerm?: Array<PropertyPermission>315};316317const defaultCreateCollectionParams: CreateCollectionParams = {318  description: 'description',319  mode: {type: 'NFT'},320  name: 'name',321  tokenPrefix: 'prefix',322};323324export async function createCollectionExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {325  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};326327  let collectionId = 0;328  await usingApi(async (api) => {329    // Get number of collections before the transaction330    const collectionCountBefore = await getCreatedCollectionCount(api);331332    // Run the CreateCollection transaction333    const alicePrivateKey = privateKey('//Alice');334335    let modeprm = {};336    if (mode.type === 'NFT') {337      modeprm = {nft: null};338    } else if (mode.type === 'Fungible') {339      modeprm = {fungible: mode.decimalPoints};340    } else if (mode.type === 'ReFungible') {341      modeprm = {refungible: null};342    }343344    const tx = api.tx.unique.createCollectionEx({345      name: strToUTF16(name),346      description: strToUTF16(description),347      tokenPrefix: strToUTF16(tokenPrefix),348      mode: modeprm as any,349    });350    const events = await submitTransactionAsync(alicePrivateKey, tx);351    const result = getCreateCollectionResult(events);352353    // Get number of collections after the transaction354    const collectionCountAfter = await getCreatedCollectionCount(api);355356    // Get the collection357    const collection = await queryCollectionExpectSuccess(api, result.collectionId);358359    // What to expect360    // tslint:disable-next-line:no-unused-expression361    expect(result.success).to.be.true;362    expect(result.collectionId).to.be.equal(collectionCountAfter);363    // tslint:disable-next-line:no-unused-expression364    expect(collection).to.be.not.null;365    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');366    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));367    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);368    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);369    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);370371    collectionId = result.collectionId;372  });373374  return collectionId;375}376377export async function createCollectionWithPropsExpectSuccess(params: Partial<CreateCollectionParams> = {}): Promise<number> {378  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};379380  let collectionId = 0;381  await usingApi(async (api) => {382    // Get number of collections before the transaction383    const collectionCountBefore = await getCreatedCollectionCount(api);384385    // Run the CreateCollection transaction386    const alicePrivateKey = privateKey('//Alice');387388    let modeprm = {};389    if (mode.type === 'NFT') {390      modeprm = {nft: null};391    } else if (mode.type === 'Fungible') {392      modeprm = {fungible: mode.decimalPoints};393    } else if (mode.type === 'ReFungible') {394      modeprm = {refungible: null};395    }396397    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});398    const events = await submitTransactionAsync(alicePrivateKey, tx);399    const result = getCreateCollectionResult(events);400401    // Get number of collections after the transaction402    const collectionCountAfter = await getCreatedCollectionCount(api);403404    // Get the collection405    const collection = await queryCollectionExpectSuccess(api, result.collectionId);406407    // What to expect408    // tslint:disable-next-line:no-unused-expression409    expect(result.success).to.be.true;410    expect(result.collectionId).to.be.equal(collectionCountAfter);411    // tslint:disable-next-line:no-unused-expression412    expect(collection).to.be.not.null;413    expect(collectionCountAfter).to.be.equal(collectionCountBefore + 1, 'Error: NFT collection NOT created.');414    expect(collection.owner.toString()).to.be.equal(toSubstrateAddress(alicesPublicKey));415    expect(utf16ToStr(collection.name.toJSON() as any)).to.be.equal(name);416    expect(utf16ToStr(collection.description.toJSON() as any)).to.be.equal(description);417    expect(hexToStr(collection.tokenPrefix.toJSON())).to.be.equal(tokenPrefix);418419420    collectionId = result.collectionId;421  });422423  return collectionId;424}425426export async function createCollectionWithPropsExpectFailure(params: Partial<CreateCollectionParams> = {}) {427  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};428429  await usingApi(async (api) => {430    // Get number of collections before the transaction431    const collectionCountBefore = await getCreatedCollectionCount(api);432433    // Run the CreateCollection transaction434    const alicePrivateKey = privateKey('//Alice');435436    let modeprm = {};437    if (mode.type === 'NFT') {438      modeprm = {nft: null};439    } else if (mode.type === 'Fungible') {440      modeprm = {fungible: mode.decimalPoints};441    } else if (mode.type === 'ReFungible') {442      modeprm = {refungible: null};443    }444445    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any, properties: params.properties, tokenPropertyPermissions: params.propPerm});446    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;447448449    // Get number of collections after the transaction450    const collectionCountAfter = await getCreatedCollectionCount(api);451452    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');453  });454}455456export async function createCollectionExpectFailure(params: Partial<CreateCollectionParams> = {}) {457  const {name, description, mode, tokenPrefix} = {...defaultCreateCollectionParams, ...params};458459  let modeprm = {};460  if (mode.type === 'NFT') {461    modeprm = {nft: null};462  } else if (mode.type === 'Fungible') {463    modeprm = {fungible: mode.decimalPoints};464  } else if (mode.type === 'ReFungible') {465    modeprm = {refungible: null};466  }467468  await usingApi(async (api) => {469    // Get number of collections before the transaction470    const collectionCountBefore = await getCreatedCollectionCount(api);471472    // Run the CreateCollection transaction473    const alicePrivateKey = privateKey('//Alice');474    const tx = api.tx.unique.createCollectionEx({name: strToUTF16(name), description: strToUTF16(description), tokenPrefix: strToUTF16(tokenPrefix), mode: modeprm as any});475    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;476477    // Get number of collections after the transaction478    const collectionCountAfter = await getCreatedCollectionCount(api);479480    // What to expect481    expect(collectionCountAfter).to.be.equal(collectionCountBefore, 'Error: Collection with incorrect data created.');482  });483}484485export async function findUnusedAddress(api: ApiPromise, seedAddition = ''): Promise<IKeyringPair> {486  let bal = 0n;487  let unused;488  do {489    const randomSeed = 'seed' + Math.floor(Math.random() * Math.floor(10000)) + seedAddition;490    const keyring = new Keyring({type: 'sr25519'});491    unused = keyring.addFromUri(`//${randomSeed}`);492    bal = (await api.query.system.account(unused.address)).data.free.toBigInt();493  } while (bal !== 0n);494  return unused;495}496497export async function getAllowance(api: ApiPromise, collectionId: number, owner: CrossAccountId | string, approved: CrossAccountId | string, tokenId: number) {498  return (await api.rpc.unique.allowance(collectionId, normalizeAccountId(owner), normalizeAccountId(approved), tokenId)).toBigInt();499}500501export function findUnusedAddresses(api: ApiPromise, amount: number): Promise<IKeyringPair[]> {502  return Promise.all(new Array(amount).fill(null).map(() => findUnusedAddress(api, '_' + Date.now())));503}504505export async function findNotExistingCollection(api: ApiPromise): Promise<number> {506  const totalNumber = await getCreatedCollectionCount(api);507  const newCollection: number = totalNumber + 1;508  return newCollection;509}510511function getDestroyResult(events: EventRecord[]): boolean {512  let success = false;513  events.forEach(({event: {method}}) => {514    if (method == 'ExtrinsicSuccess') {515      success = true;516    }517  });518  return success;519}520521export async function destroyCollectionExpectFailure(collectionId: number, senderSeed = '//Alice') {522  await usingApi(async (api) => {523    // Run the DestroyCollection transaction524    const alicePrivateKey = privateKey(senderSeed);525    const tx = api.tx.unique.destroyCollection(collectionId);526    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;527  });528}529530export async function destroyCollectionExpectSuccess(collectionId: number, senderSeed = '//Alice') {531  await usingApi(async (api) => {532    // Run the DestroyCollection transaction533    const alicePrivateKey = privateKey(senderSeed);534    const tx = api.tx.unique.destroyCollection(collectionId);535    const events = await submitTransactionAsync(alicePrivateKey, tx);536    const result = getDestroyResult(events);537    expect(result).to.be.true;538539    // What to expect540    expect(await getDetailedCollectionInfo(api, collectionId)).to.be.null;541  });542}543544export async function setCollectionLimitsExpectSuccess(sender: IKeyringPair, collectionId: number, limits: any) {545  await usingApi(async (api) => {546    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);547    const events = await submitTransactionAsync(sender, tx);548    const result = getGenericResult(events);549550    expect(result.success).to.be.true;551  });552}553554export const setCollectionPermissionsExpectSuccess = async (sender: IKeyringPair, collectionId: number, permissions: {mintMode?: boolean, access?: 'Normal' | 'AllowList', nesting?: 'Disabled' | 'Owner' | {OwnerRestricted: number[]}}) => {555  await usingApi(async(api) => {556    const tx = api.tx.unique.setCollectionPermissions(collectionId, permissions);557    const events = await submitTransactionAsync(sender, tx);558    const result = getGenericResult(events);559560    expect(result.success).to.be.true;561  });562};563564export async function setCollectionLimitsExpectFailure(sender: IKeyringPair, collectionId: number, limits: any) {565  await usingApi(async (api) => {566    const tx = api.tx.unique.setCollectionLimits(collectionId, limits);567    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;568    const result = getGenericResult(events);569570    expect(result.success).to.be.false;571  });572}573574export async function setCollectionSponsorExpectSuccess(collectionId: number, sponsor: string, sender = '//Alice') {575  await usingApi(async (api) => {576577    // Run the transaction578    const senderPrivateKey = privateKey(sender);579    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);580    const events = await submitTransactionAsync(senderPrivateKey, tx);581    const result = getGenericResult(events);582583    // Get the collection584    const collection = await queryCollectionExpectSuccess(api, collectionId);585586    // What to expect587    expect(result.success).to.be.true;588    expect(collection.sponsorship.toJSON()).to.deep.equal({589      unconfirmed: sponsor,590    });591  });592}593594export async function removeCollectionSponsorExpectSuccess(collectionId: number, sender = '//Alice') {595  await usingApi(async (api) => {596597    // Run the transaction598    const alicePrivateKey = privateKey(sender);599    const tx = api.tx.unique.removeCollectionSponsor(collectionId);600    const events = await submitTransactionAsync(alicePrivateKey, tx);601    const result = getGenericResult(events);602603    // Get the collection604    const collection = await queryCollectionExpectSuccess(api, collectionId);605606    // What to expect607    expect(result.success).to.be.true;608    expect(collection.sponsorship.toJSON()).to.be.deep.equal({disabled: null});609  });610}611612export async function removeCollectionSponsorExpectFailure(collectionId: number, senderSeed = '//Alice') {613  await usingApi(async (api) => {614615    // Run the transaction616    const alicePrivateKey = privateKey(senderSeed);617    const tx = api.tx.unique.removeCollectionSponsor(collectionId);618    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;619  });620}621622export async function setCollectionSponsorExpectFailure(collectionId: number, sponsor: string, senderSeed = '//Alice') {623  await usingApi(async (api) => {624625    // Run the transaction626    const alicePrivateKey = privateKey(senderSeed);627    const tx = api.tx.unique.setCollectionSponsor(collectionId, sponsor);628    await expect(submitTransactionExpectFailAsync(alicePrivateKey, tx)).to.be.rejected;629  });630}631632export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {633  await usingApi(async (api) => {634635    // Run the transaction636    const sender = privateKey(senderSeed);637    const tx = api.tx.unique.confirmSponsorship(collectionId);638    const events = await submitTransactionAsync(sender, tx);639    const result = getGenericResult(events);640641    // Get the collection642    const collection = await queryCollectionExpectSuccess(api, collectionId);643644    // What to expect645    expect(result.success).to.be.true;646    expect(collection.sponsorship.toJSON()).to.be.deep.equal({647      confirmed: sender.address,648    });649  });650}651652653export async function confirmSponsorshipExpectFailure(collectionId: number, senderSeed = '//Alice') {654  await usingApi(async (api) => {655656    // Run the transaction657    const sender = privateKey(senderSeed);658    const tx = api.tx.unique.confirmSponsorship(collectionId);659    await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;660  });661}662663export async function enableContractSponsoringExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {664  await usingApi(async (api) => {665    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);666    const events = await submitTransactionAsync(sender, tx);667    const result = getGenericResult(events);668669    expect(result.success).to.be.true;670  });671}672673export async function enableContractSponsoringExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, enable: boolean) {674  await usingApi(async (api) => {675    const tx = api.tx.unique.enableContractSponsoring(contractAddress, enable);676    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;677    const result = getGenericResult(events);678679    expect(result.success).to.be.false;680  });681}682683export async function setTransferFlagExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {684685  await usingApi(async (api) => {686687    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);688    const events = await submitTransactionAsync(sender, tx);689    const result = getGenericResult(events);690691    expect(result.success).to.be.true;692  });693}694695export async function setTransferFlagExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {696697  await usingApi(async (api) => {698699    const tx = api.tx.unique.setTransfersEnabledFlag(collectionId, enabled);700    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;701    const result = getGenericResult(events);702703    expect(result.success).to.be.false;704  });705}706707export async function setContractSponsoringRateLimitExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {708  await usingApi(async (api) => {709    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);710    const events = await submitTransactionAsync(sender, tx);711    const result = getGenericResult(events);712713    expect(result.success).to.be.true;714  });715}716717export async function setContractSponsoringRateLimitExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, rateLimit: number) {718  await usingApi(async (api) => {719    const tx = api.tx.unique.setContractSponsoringRateLimit(contractAddress, rateLimit);720    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;721    const result = getGenericResult(events);722723    expect(result.success).to.be.false;724  });725}726727export async function getNextSponsored(728  api: ApiPromise,729  collectionId: number,730  account: string | CrossAccountId,731  tokenId: number,732): Promise<number> {733  return Number((await api.rpc.unique.nextSponsored(collectionId, account, tokenId)).unwrapOr(-1));734}735736export async function toggleContractAllowlistExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, value = true) {737  await usingApi(async (api) => {738    const tx = api.tx.unique.toggleContractAllowList(contractAddress, value);739    const events = await submitTransactionAsync(sender, tx);740    const result = getGenericResult(events);741742    expect(result.success).to.be.true;743  });744}745746export async function isAllowlistedInContract(contractAddress: AccountId | string, user: string) {747  let allowlisted = false;748  await usingApi(async (api) => {749    allowlisted = (await api.query.unique.contractAllowList(contractAddress, user)).toJSON() as boolean;750  });751  return allowlisted;752}753754export async function addToContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {755  await usingApi(async (api) => {756    const tx = api.tx.unique.addToContractAllowList(contractAddress.toString(), user.toString());757    const events = await submitTransactionAsync(sender, tx);758    const result = getGenericResult(events);759760    expect(result.success).to.be.true;761  });762}763764export async function removeFromContractAllowListExpectSuccess(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {765  await usingApi(async (api) => {766    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());767    const events = await submitTransactionAsync(sender, tx);768    const result = getGenericResult(events);769770    expect(result.success).to.be.true;771  });772}773774export async function removeFromContractAllowListExpectFailure(sender: IKeyringPair, contractAddress: AccountId | string, user: AccountId | string) {775  await usingApi(async (api) => {776    const tx = api.tx.unique.removeFromContractAllowList(contractAddress.toString(), user.toString());777    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;778    const result = getGenericResult(events);779780    expect(result.success).to.be.false;781  });782}783784export interface CreateFungibleData {785  readonly Value: bigint;786}787788export interface CreateReFungibleData { }789export interface CreateNftData { }790791export type CreateItemData = {792  NFT: CreateNftData;793} | {794  Fungible: CreateFungibleData;795} | {796  ReFungible: CreateReFungibleData;797};798799export async function burnItemExpectSuccess(sender: IKeyringPair, collectionId: number, tokenId: number, value = 1) {800  await usingApi(async (api) => {801    const balanceBefore = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);802    // if burning token by admin - use adminButnItemExpectSuccess803    expect(balanceBefore >= BigInt(value)).to.be.true;804805    const tx = api.tx.unique.burnItem(collectionId, tokenId, value);806    const events = await submitTransactionAsync(sender, tx);807    const result = getGenericResult(events);808    expect(result.success).to.be.true;809810    const balanceAfter = await getBalance(api, collectionId, normalizeAccountId(sender), tokenId);811    expect(balanceAfter + BigInt(value)).to.be.equal(balanceBefore);812  });813}814815export async function816approveExpectSuccess(817  collectionId: number,818  tokenId: number, owner: IKeyringPair, approved: CrossAccountId | string, amount: number | bigint = 1,819) {820  await usingApi(async (api: ApiPromise) => {821    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);822    const events = await submitTransactionAsync(owner, approveUniqueTx);823    const result = getGenericResult(events);824    expect(result.success).to.be.true;825826    expect(await getAllowance(api, collectionId, owner.address, approved, tokenId)).to.be.equal(BigInt(amount));827  });828}829830export async function adminApproveFromExpectSuccess(831  collectionId: number,832  tokenId: number, admin: IKeyringPair, owner: CrossAccountId | string, approved: CrossAccountId | string, amount: number | bigint = 1,833) {834  await usingApi(async (api: ApiPromise) => {835    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved), collectionId, tokenId, amount);836    const events = await submitTransactionAsync(admin, approveUniqueTx);837    const result = getGenericResult(events);838    expect(result.success).to.be.true;839840    expect(await getAllowance(api, collectionId, owner, approved, tokenId)).to.be.equal(BigInt(amount));841  });842}843844export async function845transferFromExpectSuccess(846  collectionId: number,847  tokenId: number,848  accountApproved: IKeyringPair,849  accountFrom: IKeyringPair | CrossAccountId,850  accountTo: IKeyringPair | CrossAccountId,851  value: number | bigint = 1,852  type = 'NFT',853) {854  await usingApi(async (api: ApiPromise) => {855    const from = normalizeAccountId(accountFrom);856    const to = normalizeAccountId(accountTo);857    let balanceBefore = 0n;858    if (type === 'Fungible' || type === 'ReFungible') {859      balanceBefore = await getBalance(api, collectionId, to, tokenId);860    }861    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom), to, collectionId, tokenId, value);862    const events = await submitTransactionAsync(accountApproved, transferFromTx);863    const result = getCreateItemResult(events);864    // tslint:disable-next-line:no-unused-expression865    expect(result.success).to.be.true;866    if (type === 'NFT') {867      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);868    }869    if (type === 'Fungible') {870      const balanceAfter = await getBalance(api, collectionId, to, tokenId);871      if (JSON.stringify(to) !== JSON.stringify(from)) {872        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));873      } else {874        expect(balanceAfter).to.be.equal(balanceBefore);875      }876    }877    if (type === 'ReFungible') {878      expect(await getBalance(api, collectionId, to, tokenId)).to.be.equal(balanceBefore + BigInt(value));879    }880  });881}882883export async function884transferFromExpectFail(885  collectionId: number,886  tokenId: number,887  accountApproved: IKeyringPair,888  accountFrom: IKeyringPair,889  accountTo: IKeyringPair,890  value: number | bigint = 1,891) {892  await usingApi(async (api: ApiPromise) => {893    const transferFromTx = api.tx.unique.transferFrom(normalizeAccountId(accountFrom.address), normalizeAccountId(accountTo.address), collectionId, tokenId, value);894    const events = await expect(submitTransactionExpectFailAsync(accountApproved, transferFromTx)).to.be.rejected;895    const result = getCreateCollectionResult(events);896    // tslint:disable-next-line:no-unused-expression897    expect(result.success).to.be.false;898  });899}900901/* eslint no-async-promise-executor: "off" */902async function getBlockNumber(api: ApiPromise): Promise<number> {903  return new Promise<number>(async (resolve) => {904    const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {905      unsubscribe();906      resolve(head.number.toNumber());907    });908  });909}910911export async function addCollectionAdminExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | CrossAccountId) {912  await usingApi(async (api) => {913    const changeAdminTx = api.tx.unique.addCollectionAdmin(collectionId, normalizeAccountId(address));914    const events = await submitTransactionAsync(sender, changeAdminTx);915    const result = getCreateCollectionResult(events);916    expect(result.success).to.be.true;917  });918}919920export async function921getFreeBalance(account: IKeyringPair): Promise<bigint> {922  let balance = 0n;923  await usingApi(async (api) => {924    balance = BigInt((await api.query.system.account(account.address)).data.free.toString());925  });926927  return balance;928}929930export async function transferBalanceTo(api: ApiPromise, source: IKeyringPair, target: string, amount = 1000n * UNIQUE) {931  const tx = api.tx.balances.transfer(target, amount);932  const events = await submitTransactionAsync(source, tx);933  const result = getGenericResult(events);934  expect(result.success).to.be.true;935}936937export async function938scheduleTransferExpectSuccess(939  collectionId: number,940  tokenId: number,941  sender: IKeyringPair,942  recipient: IKeyringPair,943  value: number | bigint = 1,944  blockSchedule: number,945) {946  await usingApi(async (api: ApiPromise) => {947    const blockNumber: number | undefined = await getBlockNumber(api);948    const expectedBlockNumber = blockNumber + blockSchedule;949950    expect(blockNumber).to.be.greaterThan(0);951    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);952    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);953954    await submitTransactionAsync(sender, scheduleTx);955956    const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();957958    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));959960    // sleep for 4 blocks961    await waitNewBlocks(blockSchedule + 1);962963    const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();964965    expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));966    expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);967  });968}969970971export async function972transferExpectSuccess(973  collectionId: number,974  tokenId: number,975  sender: IKeyringPair,976  recipient: IKeyringPair | CrossAccountId,977  value: number | bigint = 1,978  type = 'NFT',979) {980  await usingApi(async (api: ApiPromise) => {981    const from = normalizeAccountId(sender);982    const to = normalizeAccountId(recipient);983984    let balanceBefore = 0n;985    if (type === 'Fungible') {986      balanceBefore = await getBalance(api, collectionId, to, tokenId);987    }988    const transferTx = api.tx.unique.transfer(to, collectionId, tokenId, value);989    const events = await executeTransaction(api, sender, transferTx);990991    const result = getTransferResult(api, events);992    expect(result.collectionId).to.be.equal(collectionId);993    expect(result.itemId).to.be.equal(tokenId);994    expect(result.sender).to.be.deep.equal(normalizeAccountId(sender.address));995    expect(result.recipient).to.be.deep.equal(to);996    expect(result.value).to.be.equal(BigInt(value));997998    if (type === 'NFT') {999      expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(to);1000    }1001    if (type === 'Fungible') {1002      const balanceAfter = await getBalance(api, collectionId, to, tokenId);1003      if (JSON.stringify(to) !== JSON.stringify(from)) {1004        expect(balanceAfter - balanceBefore).to.be.equal(BigInt(value));1005      } else {1006        expect(balanceAfter).to.be.equal(balanceBefore);1007      }1008    }1009    if (type === 'ReFungible') {1010      expect(await getBalance(api, collectionId, to, tokenId) >= value).to.be.true;1011    }1012  });1013}10141015export async function1016transferExpectFailure(1017  collectionId: number,1018  tokenId: number,1019  sender: IKeyringPair,1020  recipient: IKeyringPair | CrossAccountId,1021  value: number | bigint = 1,1022) {1023  await usingApi(async (api: ApiPromise) => {1024    const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient), collectionId, tokenId, value);1025    const events = await expect(submitTransactionExpectFailAsync(sender, transferTx)).to.be.rejected;1026    const result = getGenericResult(events);1027    // if (events && Array.isArray(events)) {1028    //   const result = getCreateCollectionResult(events);1029    // tslint:disable-next-line:no-unused-expression1030    expect(result.success).to.be.false;1031    //}1032  });1033}10341035export async function1036approveExpectFail(1037  collectionId: number,1038  tokenId: number, owner: IKeyringPair, approved: IKeyringPair, amount: number | bigint = 1,1039) {1040  await usingApi(async (api: ApiPromise) => {1041    const approveUniqueTx = api.tx.unique.approve(normalizeAccountId(approved.address), collectionId, tokenId, amount);1042    const events = await expect(submitTransactionExpectFailAsync(owner, approveUniqueTx)).to.be.rejected;1043    const result = getCreateCollectionResult(events);1044    // tslint:disable-next-line:no-unused-expression1045    expect(result.success).to.be.false;1046  });1047}10481049export async function getBalance(1050  api: ApiPromise,1051  collectionId: number,1052  owner: string | CrossAccountId,1053  token: number,1054): Promise<bigint> {1055  return (await api.rpc.unique.balance(collectionId, normalizeAccountId(owner), token)).toBigInt();1056}1057export async function getTokenOwner(1058  api: ApiPromise,1059  collectionId: number,1060  token: number,1061): Promise<CrossAccountId> {1062  const owner = (await api.rpc.unique.tokenOwner(collectionId, token)).toJSON() as any;1063  if (owner == null) throw new Error('owner == null');1064  return normalizeAccountId(owner);1065}1066export async function getTopmostTokenOwner(1067  api: ApiPromise,1068  collectionId: number,1069  token: number,1070): Promise<CrossAccountId> {1071  const owner = (await api.rpc.unique.topmostTokenOwner(collectionId, token)).toJSON() as any;1072  if (owner == null) throw new Error('owner == null');1073  return normalizeAccountId(owner);1074}1075export async function isTokenExists(1076  api: ApiPromise,1077  collectionId: number,1078  token: number,1079): Promise<boolean> {1080  return (await api.rpc.unique.tokenExists(collectionId, token)).toJSON();1081}1082export async function getLastTokenId(1083  api: ApiPromise,1084  collectionId: number,1085): Promise<number> {1086  return (await api.rpc.unique.lastTokenId(collectionId)).toJSON();1087}1088export async function getAdminList(1089  api: ApiPromise,1090  collectionId: number,1091): Promise<string[]> {1092  return (await api.rpc.unique.adminlist(collectionId)).toHuman() as any;1093}1094export async function getTokenProperties(1095  api: ApiPromise,1096  collectionId: number,1097  tokenId: number,1098  propertyKeys: string[],1099): Promise<UpDataStructsProperty[]> {1100  return (await api.rpc.unique.tokenProperties(collectionId, tokenId, propertyKeys)).toHuman() as any;1101}11021103export async function createFungibleItemExpectSuccess(1104  sender: IKeyringPair,1105  collectionId: number,1106  data: CreateFungibleData,1107  owner: CrossAccountId | string = sender.address,1108) {1109  return await usingApi(async (api) => {1110    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), {Fungible: data});11111112    const events = await submitTransactionAsync(sender, tx);1113    const result = getCreateItemResult(events);11141115    expect(result.success).to.be.true;1116    return result.itemId;1117  });1118}11191120export async function createMultipleItemsWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any, owner: CrossAccountId | string = sender.address) {1121  await usingApi(async (api) => {1122    const to = normalizeAccountId(owner);1123    const tx = api.tx.unique.createMultipleItems(collectionId, to, itemsData);11241125    const events = await submitTransactionAsync(sender, tx);1126    const result = getCreateItemsResult(events);11271128    for (const res of result) {1129      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1130    }1131  });1132}11331134export async function createMultipleItemsExWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, itemsData: any) {1135  await usingApi(async (api) => {1136    const tx = api.tx.unique.createMultipleItemsEx(collectionId, itemsData);11371138    const events = await submitTransactionAsync(sender, tx);1139    const result = getCreateItemsResult(events);11401141    for (const res of result) {1142      expect(await api.rpc.unique.tokenProperties(collectionId, res.itemId)).not.to.be.empty;1143    }1144  });1145}11461147export async function createItemWithPropsExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, props:  Array<Property>, owner: CrossAccountId | string = sender.address) {1148  let newItemId = 0;1149  await usingApi(async (api) => {1150    const to = normalizeAccountId(owner);1151    const itemCountBefore = await getLastTokenId(api, collectionId);1152    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);11531154    let tx;1155    if (createMode === 'Fungible') {1156      const createData = {fungible: {value: 10}};1157      tx = api.tx.unique.createItem(collectionId, to, createData as any);1158    } else if (createMode === 'ReFungible') {1159      const createData = {refungible: {pieces: 100}};1160      tx = api.tx.unique.createItem(collectionId, to, createData as any);1161    } else {1162      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1163      tx = api.tx.unique.createItem(collectionId, to, data as UpDataStructsCreateItemData);1164    }11651166    const events = await submitTransactionAsync(sender, tx);1167    const result = getCreateItemResult(events);11681169    const itemCountAfter = await getLastTokenId(api, collectionId);1170    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);11711172    if (createMode === 'NFT') {1173      expect(await api.rpc.unique.tokenProperties(collectionId, result.itemId)).not.to.be.empty;1174    }11751176    // What to expect1177    // tslint:disable-next-line:no-unused-expression1178    expect(result.success).to.be.true;1179    if (createMode === 'Fungible') {1180      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1181    } else {1182      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1183    }1184    expect(collectionId).to.be.equal(result.collectionId);1185    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1186    expect(to).to.be.deep.equal(result.recipient);1187    newItemId = result.itemId;1188  });1189  return newItemId;1190}11911192export async function createItemWithPropsExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, props: Array<Property>, owner: CrossAccountId | string = sender.address) {1193  await usingApi(async (api) => {11941195    let tx;1196    if (createMode === 'NFT') {1197      const data = api.createType('UpDataStructsCreateItemData', {NFT: {properties: props}});1198      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), data);1199    } else {1200      tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);1201    }120212031204    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1205    if(events.message && events.message.toString().indexOf('1002: Verification Error') > -1) return;1206    const result = getCreateItemResult(events);12071208    expect(result.success).to.be.false;1209  });1210}12111212export async function createItemExpectSuccess(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1213  let newItemId = 0;1214  await usingApi(async (api) => {1215    const to = normalizeAccountId(owner);1216    const itemCountBefore = await getLastTokenId(api, collectionId);1217    const itemBalanceBefore = await getBalance(api, collectionId, to, newItemId);12181219    let tx;1220    if (createMode === 'Fungible') {1221      const createData = {fungible: {value: 10}};1222      tx = api.tx.unique.createItem(collectionId, to, createData as any);1223    } else if (createMode === 'ReFungible') {1224      const createData = {refungible: {pieces: 100}};1225      tx = api.tx.unique.createItem(collectionId, to, createData as any);1226    } else {1227      const createData = {nft: {}};1228      tx = api.tx.unique.createItem(collectionId, to, createData as any);1229    }12301231    const events = await submitTransactionAsync(sender, tx);1232    const result = getCreateItemResult(events);12331234    const itemCountAfter = await getLastTokenId(api, collectionId);1235    const itemBalanceAfter = await getBalance(api, collectionId, to, newItemId);12361237    // What to expect1238    // tslint:disable-next-line:no-unused-expression1239    expect(result.success).to.be.true;1240    if (createMode === 'Fungible') {1241      expect(itemBalanceAfter - itemBalanceBefore).to.be.equal(10n);1242    } else {1243      expect(itemCountAfter).to.be.equal(itemCountBefore + 1);1244    }1245    expect(collectionId).to.be.equal(result.collectionId);1246    expect(itemCountAfter.toString()).to.be.equal(result.itemId.toString());1247    expect(to).to.be.deep.equal(result.recipient);1248    newItemId = result.itemId;1249  });1250  return newItemId;1251}12521253export async function createItemExpectFailure(sender: IKeyringPair, collectionId: number, createMode: string, owner: CrossAccountId | string = sender.address) {1254  await usingApi(async (api) => {1255    const tx = api.tx.unique.createItem(collectionId, normalizeAccountId(owner), createMode);12561257    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1258    const result = getCreateItemResult(events);12591260    expect(result.success).to.be.false;1261  });1262}12631264export async function setPublicAccessModeExpectSuccess(1265  sender: IKeyringPair, collectionId: number,1266  accessMode: 'Normal' | 'AllowList',1267) {1268  await usingApi(async (api) => {12691270    // Run the transaction1271    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1272    const events = await submitTransactionAsync(sender, tx);1273    const result = getGenericResult(events);12741275    // Get the collection1276    const collection = await queryCollectionExpectSuccess(api, collectionId);12771278    // What to expect1279    // tslint:disable-next-line:no-unused-expression1280    expect(result.success).to.be.true;1281    expect(collection.permissions.access.toHuman()).to.be.equal(accessMode);1282  });1283}12841285export async function setPublicAccessModeExpectFail(1286  sender: IKeyringPair, collectionId: number,1287  accessMode: 'Normal' | 'AllowList',1288) {1289  await usingApi(async (api) => {12901291    // Run the transaction1292    const tx = api.tx.unique.setCollectionPermissions(collectionId, {access: accessMode});1293    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1294    const result = getGenericResult(events);12951296    // What to expect1297    // tslint:disable-next-line:no-unused-expression1298    expect(result.success).to.be.false;1299  });1300}13011302export async function enableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1303  await setPublicAccessModeExpectSuccess(sender, collectionId, 'AllowList');1304}13051306export async function enableAllowListExpectFail(sender: IKeyringPair, collectionId: number) {1307  await setPublicAccessModeExpectFail(sender, collectionId, 'AllowList');1308}13091310export async function disableAllowListExpectSuccess(sender: IKeyringPair, collectionId: number) {1311  await setPublicAccessModeExpectSuccess(sender, collectionId, 'Normal');1312}13131314export async function setMintPermissionExpectSuccess(sender: IKeyringPair, collectionId: number, enabled: boolean) {1315  await usingApi(async (api) => {13161317    // Run the transaction1318    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1319    const events = await submitTransactionAsync(sender, tx);1320    const result = getGenericResult(events);1321    expect(result.success).to.be.true;13221323    // Get the collection1324    const collection = await queryCollectionExpectSuccess(api, collectionId);13251326    expect(collection.permissions.mintMode.toHuman()).to.be.equal(enabled);1327  });1328}13291330export async function enablePublicMintingExpectSuccess(sender: IKeyringPair, collectionId: number) {1331  await setMintPermissionExpectSuccess(sender, collectionId, true);1332}13331334export async function setMintPermissionExpectFailure(sender: IKeyringPair, collectionId: number, enabled: boolean) {1335  await usingApi(async (api) => {1336    // Run the transaction1337    const tx = api.tx.unique.setCollectionPermissions(collectionId, {mintMode: enabled});1338    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1339    const result = getCreateCollectionResult(events);1340    // tslint:disable-next-line:no-unused-expression1341    expect(result.success).to.be.false;1342  });1343}13441345export async function setChainLimitsExpectFailure(sender: IKeyringPair, limits: IChainLimits) {1346  await usingApi(async (api) => {1347    // Run the transaction1348    const tx = api.tx.unique.setChainLimits(limits);1349    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1350    const result = getCreateCollectionResult(events);1351    // tslint:disable-next-line:no-unused-expression1352    expect(result.success).to.be.false;1353  });1354}13551356export async function isAllowlisted(api: ApiPromise, collectionId: number, address: string | CrossAccountId) {1357  return (await api.rpc.unique.allowed(collectionId, normalizeAccountId(address))).toJSON();1358}13591360export async function addToAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId | CrossAccountId) {1361  await usingApi(async (api) => {1362    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.false;13631364    // Run the transaction1365    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1366    const events = await submitTransactionAsync(sender, tx);1367    const result = getGenericResult(events);1368    expect(result.success).to.be.true;13691370    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1371  });1372}13731374export async function addToAllowListAgainExpectSuccess(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1375  await usingApi(async (api) => {13761377    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;13781379    // Run the transaction1380    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1381    const events = await submitTransactionAsync(sender, tx);1382    const result = getGenericResult(events);1383    expect(result.success).to.be.true;13841385    expect(await isAllowlisted(api, collectionId, normalizeAccountId(address))).to.be.true;1386  });1387}13881389export async function addToAllowListExpectFail(sender: IKeyringPair, collectionId: number, address: string | AccountId) {1390  await usingApi(async (api) => {13911392    // Run the transaction1393    const tx = api.tx.unique.addToAllowList(collectionId, normalizeAccountId(address));1394    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1395    const result = getGenericResult(events);13961397    // What to expect1398    // tslint:disable-next-line:no-unused-expression1399    expect(result.success).to.be.false;1400  });1401}14021403export async function removeFromAllowListExpectSuccess(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1404  await usingApi(async (api) => {1405    // Run the transaction1406    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1407    const events = await submitTransactionAsync(sender, tx);1408    const result = getGenericResult(events);14091410    // What to expect1411    // tslint:disable-next-line:no-unused-expression1412    expect(result.success).to.be.true;1413  });1414}14151416export async function removeFromAllowListExpectFailure(sender: IKeyringPair, collectionId: number, address: CrossAccountId) {1417  await usingApi(async (api) => {1418    // Run the transaction1419    const tx = api.tx.unique.removeFromAllowList(collectionId, normalizeAccountId(address));1420    const events = await expect(submitTransactionExpectFailAsync(sender, tx)).to.be.rejected;1421    const result = getGenericResult(events);14221423    // What to expect1424    // tslint:disable-next-line:no-unused-expression1425    expect(result.success).to.be.false;1426  });1427}14281429export const getDetailedCollectionInfo = async (api: ApiPromise, collectionId: number)1430  : Promise<UpDataStructsRpcCollection | null> => {1431  return (await api.rpc.unique.collectionById(collectionId)).unwrapOr(null);1432};14331434export const getCreatedCollectionCount = async (api: ApiPromise): Promise<number> => {1435  // set global object - collectionsCount1436  return (await api.rpc.unique.collectionStats()).created.toNumber();1437};14381439export async function queryCollectionExpectSuccess(api: ApiPromise, collectionId: number): Promise<UpDataStructsRpcCollection> {1440  return (await api.rpc.unique.collectionById(collectionId)).unwrap();1441}14421443export async function waitNewBlocks(blocksCount = 1): Promise<void> {1444  await usingApi(async (api) => {1445    const promise = new Promise<void>(async (resolve) => {1446      const unsubscribe = await api.rpc.chain.subscribeNewHeads(() => {1447        if (blocksCount > 0) {1448          blocksCount--;1449        } else {1450          unsubscribe();1451          resolve();1452        }1453      });1454    });1455    return promise;1456  });1457}