git.delta.rocks / unique-network / refs/commits / 5f0218ad9241

difftreelog

Merge pull request #691 from UniqueNetwork/feature/pallet-scheduler-v2

Yaroslav Bolyukin2022-11-21parents: #20c695f #f71c05b.patch.diff
in: master
Feature/pallet scheduler v2

32 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5389,7 +5389,7 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unique-scheduler",
+ "pallet-unique-scheduler-v2",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.2.1",
@@ -6725,9 +6725,10 @@
 dependencies = [
  "frame-support",
  "frame-system",
- "pallet-unique-scheduler",
+ "pallet-unique-scheduler-v2",
  "parity-scale-codec 3.2.1",
  "scale-info",
+ "sp-std",
 ]
 
 [[package]]
@@ -6851,22 +6852,21 @@
 ]
 
 [[package]]
-name = "pallet-unique-scheduler"
-version = "0.1.1"
+name = "pallet-unique-scheduler-v2"
+version = "0.1.0"
 dependencies = [
  "frame-benchmarking",
  "frame-support",
  "frame-system",
  "log",
+ "pallet-preimage",
  "parity-scale-codec 3.2.1",
  "scale-info",
- "serde",
  "sp-core",
  "sp-io",
  "sp-runtime",
  "sp-std",
  "substrate-test-utils",
- "up-sponsorship",
 ]
 
 [[package]]
@@ -8861,7 +8861,6 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unique-scheduler",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.2.1",
@@ -12992,7 +12991,6 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unique-scheduler",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.2.1",
modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -118,7 +118,7 @@
 
 .PHONY: bench-scheduler
 bench-scheduler:
-	make _bench PALLET=unique-scheduler PALLET_DIR=scheduler
+	make _bench PALLET=unique-scheduler-v2 PALLET_DIR=scheduler-v2
 
 .PHONY: bench-rmrk-core
 bench-rmrk-core:
addedpallets/scheduler-v2/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/scheduler-v2/Cargo.toml
@@ -0,0 +1,48 @@
+[package]
+name = "pallet-unique-scheduler-v2"
+version = "0.1.0"
+authors = ["Unique Network <support@uniquenetwork.io>"]
+edition = "2021"
+license = "GPLv3"
+homepage = "https://unique.network"
+repository = "https://github.com/UniqueNetwork/unique-chain"
+description = "Unique Scheduler pallet"
+readme = "README.md"
+
+[dependencies]
+codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
+log = { version = "0.4.17", default-features = false }
+scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
+frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-io = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-runtime = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-std = { version = "4.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+
+[dev-dependencies]
+pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
+
+[features]
+default = ["std"]
+runtime-benchmarks = [
+	"frame-benchmarking",
+	"frame-support/runtime-benchmarks",
+	"frame-system/runtime-benchmarks",
+]
+std = [
+	"codec/std",
+	"frame-benchmarking?/std",
+	"frame-support/std",
+	"frame-system/std",
+	"log/std",
+	"scale-info/std",
+	"sp-io/std",
+	"sp-runtime/std",
+	"sp-std/std",
+	"sp-core/std",
+]
+try-runtime = ["frame-support/try-runtime"]
addedpallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/scheduler-v2/src/benchmarking.rs
@@ -0,0 +1,374 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// 	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Scheduler pallet benchmarking.
+
+use super::*;
+use frame_benchmarking::{account, benchmarks};
+use frame_support::{
+	ensure,
+	traits::{schedule::Priority, PreimageRecipient},
+};
+use frame_system::RawOrigin;
+use sp_std::{prelude::*, vec};
+use sp_io::hashing::blake2_256;
+
+use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};
+use frame_system::Call as SystemCall;
+
+const SEED: u32 = 0;
+
+const BLOCK_NUMBER: u32 = 2;
+
+/// Add `n` items to the schedule.
+///
+/// For `resolved`:
+/// - `
+/// - `None`: aborted (hash without preimage)
+/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
+/// - `Some(false)`: plain call
+fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {
+	let t = DispatchTime::At(when);
+	let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();
+	for i in 0..n {
+		let call = make_call::<T>(None);
+		let period = Some(((i + 100).into(), 100));
+		let name = u32_to_name(i);
+		Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;
+	}
+	ensure!(
+		Agenda::<T>::get(when).agenda.len() == n as usize,
+		"didn't fill schedule"
+	);
+	Ok(())
+}
+
+/// Generate a name for a scheduled task from an unsigned integer.
+fn u32_to_name(i: u32) -> TaskName {
+	i.using_encoded(blake2_256)
+}
+
+/// A utility for creating simple scheduled tasks.
+///
+/// # Arguments
+/// * `periodic` - makes the task periodic.
+/// 	Sets the task's period and repetition count to `100`.
+/// * `named` - gives a name to the task: `u32_to_name(0)`.
+/// * `signed` - determines the origin of the task.
+/// 	If true, it will have the Signed origin. Otherwise it will have the Root origin.
+/// 	See [`make_origin`] for details.
+/// * maybe_lookup_len - sets optional lookup length. It is used to benchmark task fetching from the `Preimages` store.
+/// * priority - the task's priority.
+fn make_task<T: Config>(
+	periodic: bool,
+	named: bool,
+	signed: bool,
+	maybe_lookup_len: Option<u32>,
+	priority: Priority,
+) -> ScheduledOf<T> {
+	let call = make_call::<T>(maybe_lookup_len);
+	let maybe_periodic = match periodic {
+		true => Some((100u32.into(), 100)),
+		false => None,
+	};
+	let maybe_id = match named {
+		true => Some(u32_to_name(0)),
+		false => None,
+	};
+	let origin = make_origin::<T>(signed);
+	Scheduled {
+		maybe_id,
+		priority,
+		call,
+		maybe_periodic,
+		origin,
+		_phantom: PhantomData,
+	}
+}
+
+/// Creates a `SystemCall::remark` scheduled call with a given `len` in bytes.
+/// Returns `None` if the call is too large to encode.
+fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {
+	let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {
+		remark: vec![0; len as usize],
+	});
+	ScheduledCall::new(call).ok()
+}
+
+/// Creates a scheduled call and maximizes its size.
+///
+/// If the `maybe_lookup_len` is not supplied, the task will create the maximal `Inline` scheduled call.
+///
+/// Otherwise, the function will take the length value from the `maybe_lookup_len`
+/// and find a minimal length value that ensures that the scheduled call will require a Preimage lookup.
+fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {
+	let bound = EncodedCall::bound() as u32;
+	let mut len = match maybe_lookup_len {
+		Some(len) => {
+			len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)
+				.max(bound) - 3
+		}
+		None => bound.saturating_sub(4),
+	};
+
+	loop {
+		let c = match bounded::<T>(len) {
+			Some(x) => x,
+			None => {
+				len -= 1;
+				continue;
+			}
+		};
+		if c.lookup_needed() == maybe_lookup_len.is_some() {
+			break c;
+		}
+		if maybe_lookup_len.is_some() {
+			len += 1;
+		} else {
+			if len > 0 {
+				len -= 1;
+			} else {
+				break c;
+			}
+		}
+	}
+}
+
+/// Creates an origin for a scheduled call.
+///
+/// If `signed` is true, it creates the Signed origin from a default account `account("origin", 0, SEED)`.
+/// Otherwise, it creates the Root origin.
+fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {
+	match signed {
+		true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),
+		false => frame_system::RawOrigin::Root.into(),
+	}
+}
+
+/// Creates a dummy `WeightCounter` with the maximum possible weight limit.
+fn dummy_counter() -> WeightCounter {
+	WeightCounter {
+		used: Weight::zero(),
+		limit: Weight::MAX,
+	}
+}
+
+benchmarks! {
+	// `service_agendas` when no work is done.
+	// (multiple agendas - scheduled tasks in several blocks)
+	service_agendas_base {
+		let now = T::BlockNumber::from(BLOCK_NUMBER);
+		IncompleteSince::<T>::put(now - One::one());
+	}: {
+		Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);
+	} verify {
+		assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));
+	}
+
+	// `service_agenda` when no work is done.
+	// (only one agenda - scheduled tasks in a single block)
+	service_agenda_base {
+		let now = BLOCK_NUMBER.into();
+		let s in 0 .. T::MaxScheduledPerBlock::get();
+		fill_schedule::<T>(now, s)?;
+		let mut executed = 0;
+	}: {
+		Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);
+	} verify {
+		assert_eq!(executed, 0);
+	}
+
+	// `service_task` when the task is a non-periodic, non-named, non-fetched call which is not
+	// dispatched (e.g. due to being overweight).
+	service_task_base {
+		let now = BLOCK_NUMBER.into();
+		let task = make_task::<T>(false, false, false, None, 0);
+		// prevent any tasks from actually being executed as we only want the surrounding weight.
+		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+	}: {
+		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+	} verify {
+		//assert_eq!(result, Ok(()));
+	}
+
+	// TODO uncomment if we will use the Preimages
+	// // `service_task` when the task is a non-periodic, non-named, fetched call (with a known
+	// // preimage length) and which is not dispatched (e.g. due to being overweight).
+	// service_task_fetched {
+	// 	let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());
+	// 	let now = BLOCK_NUMBER.into();
+	// 	let task = make_task::<T>(false, false, false, Some(s), 0);
+	// 	// prevent any tasks from actually being executed as we only want the surrounding weight.
+	// 	let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+	// }: {
+	// 	let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+	// } verify {
+	// }
+
+	// `service_task` when the task is a non-periodic, named, non-fetched call which is not
+	// dispatched (e.g. due to being overweight).
+	service_task_named {
+		let now = BLOCK_NUMBER.into();
+		let task = make_task::<T>(false, true, false, None, 0);
+		// prevent any tasks from actually being executed as we only want the surrounding weight.
+		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+	}: {
+		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+	} verify {
+	}
+
+	// `service_task` when the task is a periodic, non-named, non-fetched call which is not
+	// dispatched (e.g. due to being overweight).
+	service_task_periodic {
+		let now = BLOCK_NUMBER.into();
+		let task = make_task::<T>(true, false, false, None, 0);
+		// prevent any tasks from actually being executed as we only want the surrounding weight.
+		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+	}: {
+		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+	} verify {
+	}
+
+	// `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.
+	execute_dispatch_signed {
+		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
+		let origin = make_origin::<T>(true);
+		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
+	}: {
+		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
+	}
+	verify {
+	}
+
+	// `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.
+	execute_dispatch_unsigned {
+		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
+		let origin = make_origin::<T>(false);
+		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
+	}: {
+		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
+	}
+	verify {
+	}
+
+	schedule {
+		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
+		let when = BLOCK_NUMBER.into();
+		let periodic = Some((T::BlockNumber::one(), 100));
+		let priority = Some(0);
+		// Essentially a no-op call.
+		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
+
+		fill_schedule::<T>(when, s)?;
+	}: _(RawOrigin::Root, when, periodic, priority, call)
+	verify {
+		ensure!(
+			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
+			"didn't add to schedule"
+		);
+	}
+
+	cancel {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+
+		fill_schedule::<T>(when, s)?;
+		assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);
+	}: _(RawOrigin::Root, when, 0)
+	verify {
+		ensure!(
+			Lookup::<T>::get(u32_to_name(0)).is_none(),
+			"didn't remove from lookup"
+		);
+		// Removed schedule is NONE
+		ensure!(
+			Agenda::<T>::get(when).agenda[0].is_none(),
+			"didn't remove from schedule"
+		);
+	}
+
+	schedule_named {
+		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
+		let id = u32_to_name(s);
+		let when = BLOCK_NUMBER.into();
+		let periodic = Some((T::BlockNumber::one(), 100));
+		let priority = Some(0);
+		// Essentially a no-op call.
+		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
+
+		fill_schedule::<T>(when, s)?;
+	}: _(RawOrigin::Root, id, when, periodic, priority, call)
+	verify {
+		ensure!(
+			Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
+			"didn't add to schedule"
+		);
+	}
+
+	cancel_named {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+
+		fill_schedule::<T>(when, s)?;
+	}: _(RawOrigin::Root, u32_to_name(0))
+	verify {
+		ensure!(
+			Lookup::<T>::get(u32_to_name(0)).is_none(),
+			"didn't remove from lookup"
+		);
+		// Removed schedule is NONE
+		ensure!(
+			Agenda::<T>::get(when).agenda[0].is_none(),
+			"didn't remove from schedule"
+		);
+	}
+
+	change_named_priority {
+		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		let idx = s - 1;
+		let id = u32_to_name(idx);
+		let priority = 42;
+		fill_schedule::<T>(when, s)?;
+	}: _(origin, id, priority)
+	verify {
+		ensure!(
+			Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,
+			"didn't change the priority"
+		);
+	}
+
+	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
+}
addedpallets/scheduler-v2/src/lib.rsdiffbeforeafterboth
after · pallets/scheduler-v2/src/lib.rs
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/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//!   with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//!   that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]69#![deny(missing_docs)]7071#[cfg(feature = "runtime-benchmarks")]72mod benchmarking;73#[cfg(test)]74mod mock;75#[cfg(test)]76mod tests;77pub mod weights;7879use codec::{Codec, Decode, Encode, MaxEncodedLen};80use frame_support::{81	dispatch::{82		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,83	},84	traits::{85		schedule::{self, DispatchTime, LOWEST_PRIORITY},86		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,87		ConstU32, UnfilteredDispatchable,88	},89	weights::Weight,90	unsigned::TransactionValidityError,91};9293use frame_system::{self as system};94use scale_info::TypeInfo;95use sp_runtime::{96	traits::{BadOrigin, One, Saturating, Zero, Hash},97	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,98};99use sp_core::H160;100use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};101pub use weights::WeightInfo;102103pub use pallet::*;104105/// Just a simple index for naming period tasks.106pub type PeriodicIndex = u32;107/// The location of a scheduled task that can be used to remove it.108pub type TaskAddress<BlockNumber> = (BlockNumber, u32);109110/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.111pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;112113#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]114#[scale_info(skip_type_params(T))]115/// A scheduled call is stored as is or as a preimage hash to lookup.116/// This enum represents both variants.117pub enum ScheduledCall<T: Config> {118	/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.119	Inline(EncodedCall),120121	/// A Blake2-256 hash of the call together with an upper limit for its size.122	PreimageLookup {123		/// A call hash to lookup124		hash: T::Hash,125126		/// The length of the decoded call127		unbounded_len: u32,128	},129}130131impl<T: Config> ScheduledCall<T> {132	/// Convert an otherwise unbounded or large value into a type ready for placing in storage.133	///134	/// NOTE: Once this API is used, you should use either `drop` or `realize`.135	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {136		let encoded = call.encode();137		let len = encoded.len();138139		match EncodedCall::try_from(encoded.clone()) {140			Ok(bounded) => Ok(Self::Inline(bounded)),141			Err(_) => {142				let hash = <T as system::Config>::Hashing::hash_of(&encoded);143				<T as Config>::Preimages::note_preimage(144					encoded145						.try_into()146						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,147				);148149				Ok(Self::PreimageLookup {150					hash,151					unbounded_len: len as u32,152				})153			}154		}155	}156157	/// The maximum length of the lookup that is needed to peek `Self`.158	pub fn lookup_len(&self) -> Option<u32> {159		match self {160			Self::Inline(..) => None,161			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),162		}163	}164165	/// Returns whether the image will require a lookup to be peeked.166	pub fn lookup_needed(&self) -> bool {167		match self {168			Self::Inline(_) => false,169			Self::PreimageLookup { .. } => true,170		}171	}172173	// Decodes a runtime call174	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {175		<T as Config>::RuntimeCall::decode(&mut data)176			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())177	}178}179180/// Weight Info for the Preimages fetches.181pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {182	/// Get the weight of a task fetches with a given decoded length.183	fn service_task_fetched(call_length: u32) -> Weight;184}185186impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {187	fn service_task_fetched(_call_length: u32) -> Weight {188		W::service_task_base()189	}190}191192/// A scheduler's interface for managing preimages to hashes193/// and looking up preimages from their hash on-chain.194pub trait SchedulerPreimages<T: Config>:195	PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>196{197	/// No longer request that the data for decoding the given `call` is available.198	fn drop(call: &ScheduledCall<T>);199200	/// Convert the given `call` instance back into its original instance, also returning the201	/// exact size of its encoded form if it needed to be looked-up from a stored preimage.202	///203	/// NOTE: This does not remove any data needed for realization. If you will no longer use the204	/// `call`, use `realize` instead or use `drop` afterwards.205	fn peek(206		call: &ScheduledCall<T>,207	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;208209	/// Convert the given scheduled `call` value back into its original instance. If successful,210	/// `drop` any data backing it. This will not break the realisability of independently211	/// created instances of `ScheduledCall` which happen to have identical data.212	fn realize(213		call: &ScheduledCall<T>,214	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;215}216217impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>218	SchedulerPreimages<T> for PP219{220	fn drop(call: &ScheduledCall<T>) {221		match call {222			ScheduledCall::Inline(_) => {}223			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),224		}225	}226227	fn peek(228		call: &ScheduledCall<T>,229	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {230		match call {231			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),232			ScheduledCall::PreimageLookup {233				hash,234				unbounded_len,235			} => {236				let (preimage, len) = Self::get_preimage(hash)237					.ok_or(<Error<T>>::PreimageNotFound)238					.map(|preimage| (preimage, *unbounded_len))?;239240				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))241			}242		}243	}244245	fn realize(246		call: &ScheduledCall<T>,247	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {248		let r = Self::peek(call)?;249		Self::drop(call);250		Ok(r)251	}252}253254/// Scheduler's supported origins.255pub enum ScheduledEnsureOriginSuccess<AccountId> {256	/// A scheduled transaction has the Root origin.257	Root,258259	/// A specific account has signed a scheduled transaction.260	Signed(AccountId),261}262263/// An identifier of a scheduled task.264pub type TaskName = [u8; 32];265266/// Information regarding an item to be executed in the future.267#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]268#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]269pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {270	/// The unique identity for this task, if there is one.271	maybe_id: Option<Name>,272273	/// This task's priority.274	priority: schedule::Priority,275276	/// The call to be dispatched.277	call: Call,278279	/// If the call is periodic, then this points to the information concerning that.280	maybe_periodic: Option<schedule::Period<BlockNumber>>,281282	/// The origin with which to dispatch the call.283	origin: PalletsOrigin,284	_phantom: PhantomData<AccountId>,285}286287/// Information regarding an item to be executed in the future.288pub type ScheduledOf<T> = Scheduled<289	TaskName,290	ScheduledCall<T>,291	<T as frame_system::Config>::BlockNumber,292	<T as Config>::PalletsOrigin,293	<T as frame_system::Config>::AccountId,294>;295296#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]297#[scale_info(skip_type_params(T))]298/// A structure for storing scheduled tasks in a block.299/// The `BlockAgenda` tracks the available free space for a new task in a block.4300///301/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.302pub struct BlockAgenda<T: Config> {303	agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,304	free_places: u32,305}306307impl<T: Config> BlockAgenda<T> {308	/// Tries to push a new scheduled task into the block's agenda.309	/// If there is a free place, the new task will take it,310	/// and the `BlockAgenda` will record that the number of free places has decreased.311	///312	/// An error containing the scheduled task will be returned if there are no free places.313	///314	/// The complexity of the check for the *existence* of a free place is O(1).315	/// The complexity of *finding* the free slot is O(n).316	fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {317		if self.free_places == 0 {318			return Err(scheduled);319		}320321		self.free_places = self.free_places.saturating_sub(1);322323		if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {324			// will always succeed due to the above check.325			let _ = self.agenda.try_push(Some(scheduled));326			Ok((self.agenda.len() - 1) as u32)327		} else {328			match self.agenda.iter().position(|i| i.is_none()) {329				Some(hole_index) => {330					self.agenda[hole_index] = Some(scheduled);331					Ok(hole_index as u32)332				}333				None => unreachable!("free_places was greater than 0; qed"),334			}335		}336	}337338	/// Sets a slot by the given index and the slot value.339	///340	/// ### Panics341	/// If the index is out of range, the function will panic.342	fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {343		self.agenda[index as usize] = slot;344	}345346	/// Returns an iterator containing references to the agenda's slots.347	fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {348		self.agenda.iter()349	}350351	/// Returns an immutable reference to a scheduled task if there is one under the given index.352	///353	///  The function returns `None` if:354	/// * The `index` is out of range355	/// * No scheduled task occupies the agenda slot under the given index.356	fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {357		match self.agenda.get(index as usize) {358			Some(Some(scheduled)) => Some(scheduled),359			_ => None,360		}361	}362363	/// Returns a mutable reference to a scheduled task if there is one under the given index.364	///365	///  The function returns `None` if:366	/// * The `index` is out of range367	/// * No scheduled task occupies the agenda slot under the given index.368	fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {369		match self.agenda.get_mut(index as usize) {370			Some(Some(scheduled)) => Some(scheduled),371			_ => None,372		}373	}374375	/// Take a scheduled task by the given index.376	///377	/// If there is a task under the index, the function will:378	/// * Free the corresponding agenda slot.379	/// * Decrease the number of free places.380	/// * Return the scheduled task.381	///382	/// The function returns `None` if there is no task under the index.383	fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {384		let removed = self.agenda.get_mut(index as usize)?.take();385386		if removed.is_some() {387			self.free_places = self.free_places.saturating_add(1);388		}389390		removed391	}392}393394impl<T: Config> Default for BlockAgenda<T> {395	fn default() -> Self {396		let agenda = Default::default();397		let free_places = T::MaxScheduledPerBlock::get();398399		Self {400			agenda,401			free_places,402		}403	}404}405/// A structure for tracking the used weight406/// and checking if it does not exceed the weight limit.407struct WeightCounter {408	used: Weight,409	limit: Weight,410}411412impl WeightCounter {413	/// Checks if the weight `w` can be accommodated by the counter.414	///415	/// If there is room for the additional weight `w`,416	/// the function will update the used weight and return true.417	fn check_accrue(&mut self, w: Weight) -> bool {418		let test = self.used.saturating_add(w);419		if test.any_gt(self.limit) {420			false421		} else {422			self.used = test;423			true424		}425	}426427	/// Checks if the weight `w` can be accommodated by the counter.428	fn can_accrue(&mut self, w: Weight) -> bool {429		self.used.saturating_add(w).all_lte(self.limit)430	}431}432433pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);434435impl<T: Config> MarginalWeightInfo<T> {436	/// Return the weight of servicing a single task.437	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {438		let base = T::WeightInfo::service_task_base();439		let mut total = match maybe_lookup_len {440			None => base,441			Some(l) => T::Preimages::service_task_fetched(l as u32),442		};443		if named {444			total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));445		}446		if periodic {447			total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));448		}449		total450	}451}452453#[frame_support::pallet]454pub mod pallet {455	use super::*;456	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};457	use system::pallet_prelude::*;458459	/// The current storage version.460	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);461462	#[pallet::pallet]463	#[pallet::generate_store(pub(super) trait Store)]464	#[pallet::storage_version(STORAGE_VERSION)]465	pub struct Pallet<T>(_);466467	#[pallet::config]468	pub trait Config: frame_system::Config {469		/// The overarching event type.470		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;471472		/// The aggregated origin which the dispatch will take.473		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>474			+ From<Self::PalletsOrigin>475			+ IsType<<Self as system::Config>::RuntimeOrigin>476			+ Clone;477478		/// The caller origin, overarching type of all pallets origins.479		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>480			+ Codec481			+ Clone482			+ Eq483			+ TypeInfo484			+ MaxEncodedLen;485486		/// The aggregated call type.487		type RuntimeCall: Parameter488			+ Dispatchable<489				RuntimeOrigin = <Self as Config>::RuntimeOrigin,490				PostInfo = PostDispatchInfo,491			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>492			+ GetDispatchInfo493			+ From<system::Call<Self>>;494495		/// The maximum weight that may be scheduled per block for any dispatchables.496		#[pallet::constant]497		type MaximumWeight: Get<Weight>;498499		/// Required origin to schedule or cancel calls.500		type ScheduleOrigin: EnsureOrigin<501			<Self as system::Config>::RuntimeOrigin,502			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,503		>;504505		/// Compare the privileges of origins.506		///507		/// This will be used when canceling a task, to ensure that the origin that tries508		/// to cancel has greater or equal privileges as the origin that created the scheduled task.509		///510		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can511		/// be used. This will only check if two given origins are equal.512		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;513514		/// The maximum number of scheduled calls in the queue for a single block.515		#[pallet::constant]516		type MaxScheduledPerBlock: Get<u32>;517518		/// Weight information for extrinsics in this pallet.519		type WeightInfo: WeightInfo;520521		/// The preimage provider with which we look up call hashes to get the call.522		type Preimages: SchedulerPreimages<Self>;523524		/// The helper type used for custom transaction fee logic.525		type CallExecutor: DispatchCall<Self, H160>;526527		/// Required origin to set/change calls' priority.528		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;529	}530531	/// It contains the block number from which we should service tasks.532	/// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.533	#[pallet::storage]534	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;535536	/// Items to be executed, indexed by the block number that they should be executed on.537	#[pallet::storage]538	pub type Agenda<T: Config> =539		StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;540541	/// Lookup from a name to the block number and index of the task.542	#[pallet::storage]543	pub(crate) type Lookup<T: Config> =544		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;545546	/// Events type.547	#[pallet::event]548	#[pallet::generate_deposit(pub(super) fn deposit_event)]549	pub enum Event<T: Config> {550		/// Scheduled some task.551		Scheduled {552			/// The block number in which the scheduled task should be executed.553			when: T::BlockNumber,554555			/// The index of the block's agenda slot.556			index: u32,557		},558		/// Canceled some task.559		Canceled {560			/// The block number in which the canceled task has been.561			when: T::BlockNumber,562563			/// The index of the block's agenda slot that had become available.564			index: u32,565		},566		/// Dispatched some task.567		Dispatched {568			/// The task's address - the block number and the block's agenda index.569			task: TaskAddress<T::BlockNumber>,570571			/// The task's name if it is not anonymous.572			id: Option<[u8; 32]>,573574			/// The task's execution result.575			result: DispatchResult,576		},577		/// Scheduled task's priority has changed578		PriorityChanged {579			/// The task's address - the block number and the block's agenda index.580			task: TaskAddress<T::BlockNumber>,581582			/// The new priority of the task.583			priority: schedule::Priority,584		},585		/// The call for the provided hash was not found so the task has been aborted.586		CallUnavailable {587			/// The task's address - the block number and the block's agenda index.588			task: TaskAddress<T::BlockNumber>,589590			/// The task's name if it is not anonymous.591			id: Option<[u8; 32]>,592		},593		/// The given task can never be executed since it is overweight.594		PermanentlyOverweight {595			/// The task's address - the block number and the block's agenda index.596			task: TaskAddress<T::BlockNumber>,597598			/// The task's name if it is not anonymous.599			id: Option<[u8; 32]>,600		},601	}602603	#[pallet::error]604	pub enum Error<T> {605		/// Failed to schedule a call606		FailedToSchedule,607		/// There is no place for a new task in the agenda608		AgendaIsExhausted,609		/// Scheduled call is corrupted610		ScheduledCallCorrupted,611		/// Scheduled call preimage is not found612		PreimageNotFound,613		/// Scheduled call is too big614		TooBigScheduledCall,615		/// Cannot find the scheduled call.616		NotFound,617		/// Given target block number is in the past.618		TargetBlockNumberInPast,619		/// Attempt to use a non-named function on a named task.620		Named,621	}622623	#[pallet::hooks]624	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {625		/// Execute the scheduled calls626		fn on_initialize(now: T::BlockNumber) -> Weight {627			let mut weight_counter = WeightCounter {628				used: Weight::zero(),629				limit: T::MaximumWeight::get(),630			};631			Self::service_agendas(&mut weight_counter, now, u32::max_value());632			weight_counter.used633		}634	}635636	#[pallet::call]637	impl<T: Config> Pallet<T> {638		/// Anonymously schedule a task.639		///640		/// Only `T::ScheduleOrigin` is allowed to schedule a task.641		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.642		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]643		pub fn schedule(644			origin: OriginFor<T>,645			when: T::BlockNumber,646			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,647			priority: Option<schedule::Priority>,648			call: Box<<T as Config>::RuntimeCall>,649		) -> DispatchResult {650			T::ScheduleOrigin::ensure_origin(origin.clone())?;651652			if priority.is_some() {653				T::PrioritySetOrigin::ensure_origin(origin.clone())?;654			}655656			let origin = <T as Config>::RuntimeOrigin::from(origin);657			Self::do_schedule(658				DispatchTime::At(when),659				maybe_periodic,660				priority.unwrap_or(LOWEST_PRIORITY),661				origin.caller().clone(),662				<ScheduledCall<T>>::new(*call)?,663			)?;664			Ok(())665		}666667		/// Cancel an anonymously scheduled task.668		///669		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.670		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]671		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {672			T::ScheduleOrigin::ensure_origin(origin.clone())?;673			let origin = <T as Config>::RuntimeOrigin::from(origin);674			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;675			Ok(())676		}677678		/// Schedule a named task.679		///680		/// Only `T::ScheduleOrigin` is allowed to schedule a task.681		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.682		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]683		pub fn schedule_named(684			origin: OriginFor<T>,685			id: TaskName,686			when: T::BlockNumber,687			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,688			priority: Option<schedule::Priority>,689			call: Box<<T as Config>::RuntimeCall>,690		) -> DispatchResult {691			T::ScheduleOrigin::ensure_origin(origin.clone())?;692693			if priority.is_some() {694				T::PrioritySetOrigin::ensure_origin(origin.clone())?;695			}696697			let origin = <T as Config>::RuntimeOrigin::from(origin);698			Self::do_schedule_named(699				id,700				DispatchTime::At(when),701				maybe_periodic,702				priority.unwrap_or(LOWEST_PRIORITY),703				origin.caller().clone(),704				<ScheduledCall<T>>::new(*call)?,705			)?;706			Ok(())707		}708709		/// Cancel a named scheduled task.710		///711		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.712		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]713		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {714			T::ScheduleOrigin::ensure_origin(origin.clone())?;715			let origin = <T as Config>::RuntimeOrigin::from(origin);716			Self::do_cancel_named(Some(origin.caller().clone()), id)?;717			Ok(())718		}719720		/// Anonymously schedule a task after a delay.721		///722		/// # <weight>723		/// Same as [`schedule`].724		/// # </weight>725		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]726		pub fn schedule_after(727			origin: OriginFor<T>,728			after: T::BlockNumber,729			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,730			priority: Option<schedule::Priority>,731			call: Box<<T as Config>::RuntimeCall>,732		) -> DispatchResult {733			T::ScheduleOrigin::ensure_origin(origin.clone())?;734735			if priority.is_some() {736				T::PrioritySetOrigin::ensure_origin(origin.clone())?;737			}738739			let origin = <T as Config>::RuntimeOrigin::from(origin);740			Self::do_schedule(741				DispatchTime::After(after),742				maybe_periodic,743				priority.unwrap_or(LOWEST_PRIORITY),744				origin.caller().clone(),745				<ScheduledCall<T>>::new(*call)?,746			)?;747			Ok(())748		}749750		/// Schedule a named task after a delay.751		///752		/// Only `T::ScheduleOrigin` is allowed to schedule a task.753		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.754		///755		/// # <weight>756		/// Same as [`schedule_named`](Self::schedule_named).757		/// # </weight>758		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]759		pub fn schedule_named_after(760			origin: OriginFor<T>,761			id: TaskName,762			after: T::BlockNumber,763			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,764			priority: Option<schedule::Priority>,765			call: Box<<T as Config>::RuntimeCall>,766		) -> DispatchResult {767			T::ScheduleOrigin::ensure_origin(origin.clone())?;768769			if priority.is_some() {770				T::PrioritySetOrigin::ensure_origin(origin.clone())?;771			}772773			let origin = <T as Config>::RuntimeOrigin::from(origin);774			Self::do_schedule_named(775				id,776				DispatchTime::After(after),777				maybe_periodic,778				priority.unwrap_or(LOWEST_PRIORITY),779				origin.caller().clone(),780				<ScheduledCall<T>>::new(*call)?,781			)?;782			Ok(())783		}784785		/// Change a named task's priority.786		///787		/// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.788		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]789		pub fn change_named_priority(790			origin: OriginFor<T>,791			id: TaskName,792			priority: schedule::Priority,793		) -> DispatchResult {794			T::PrioritySetOrigin::ensure_origin(origin.clone())?;795			let origin = <T as Config>::RuntimeOrigin::from(origin);796			Self::do_change_named_priority(origin.caller().clone(), id, priority)797		}798	}799}800801impl<T: Config> Pallet<T> {802	/// Converts the `DispatchTime` to the `BlockNumber`.803	///804	/// Returns an error if the block number is in the past.805	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {806		let now = frame_system::Pallet::<T>::block_number();807808		let when = match when {809			DispatchTime::At(x) => x,810			// The current block has already completed it's scheduled tasks, so811			// Schedule the task at lest one block after this current block.812			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),813		};814815		if when <= now {816			return Err(Error::<T>::TargetBlockNumberInPast.into());817		}818819		Ok(when)820	}821822	/// Places the mandatory task.823	///824	/// It will try to place the task into the block pointed by the `when` parameter.825	///826	/// If the block has no room for a task,827	/// the function will search for a future block that can accommodate the task.828	fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {829		Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");830	}831832	/// Tries to place a task `what` into the given block `when`.833	///834	/// Returns an error if the block has no room for the task.835	fn try_place_task(836		when: T::BlockNumber,837		what: ScheduledOf<T>,838	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {839		Self::place_task(when, what, false)840	}841842	/// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);843	/// otherwise it acts like [`try_place_task`](Self::try_place_task).844	///845	/// The function also updates the `Lookup` storage.846	fn place_task(847		mut when: T::BlockNumber,848		what: ScheduledOf<T>,849		is_mandatory: bool,850	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {851		let maybe_name = what.maybe_id;852		let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;853		let address = (when, index);854		if let Some(name) = maybe_name {855			Lookup::<T>::insert(name, address)856		}857		Self::deposit_event(Event::Scheduled {858			when: address.0,859			index: address.1,860		});861		Ok(address)862	}863864	/// Pushes the scheduled task into the block's agenda.865	///866	/// If `is_mandatory` is true, it searches for a block with a free slot for the given task.867	///868	/// If `is_mandatory` is false and there is no free slot, the function returns an error.869	fn push_to_agenda(870		when: &mut T::BlockNumber,871		mut what: ScheduledOf<T>,872		is_mandatory: bool,873	) -> Result<u32, DispatchError> {874		let mut agenda;875876		let index = loop {877			agenda = Agenda::<T>::get(*when);878879			match agenda.try_push(what) {880				Ok(index) => break index,881				Err(returned_what) if is_mandatory => {882					what = returned_what;883					when.saturating_inc();884				}885				Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),886			}887		};888889		Agenda::<T>::insert(when, agenda);890		Ok(index)891	}892893	fn do_schedule(894		when: DispatchTime<T::BlockNumber>,895		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,896		priority: schedule::Priority,897		origin: T::PalletsOrigin,898		call: ScheduledCall<T>,899	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {900		let when = Self::resolve_time(when)?;901902		// sanitize maybe_periodic903		let maybe_periodic = maybe_periodic904			.filter(|p| p.1 > 1 && !p.0.is_zero())905			// Remove one from the number of repetitions since we will schedule one now.906			.map(|(p, c)| (p, c - 1));907		let task = Scheduled {908			maybe_id: None,909			priority,910			call,911			maybe_periodic,912			origin,913			_phantom: PhantomData,914		};915		Self::try_place_task(when, task)916	}917918	fn do_cancel(919		origin: Option<T::PalletsOrigin>,920		(when, index): TaskAddress<T::BlockNumber>,921	) -> Result<(), DispatchError> {922		let scheduled = Agenda::<T>::try_mutate(923			when,924			|agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {925				let scheduled = match agenda.get(index) {926					Some(scheduled) => scheduled,927					None => return Ok(None),928				};929930				if let Some(ref o) = origin {931					if matches!(932						T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),933						Some(Ordering::Less) | None934					) {935						return Err(BadOrigin.into());936					}937				}938939				Ok(agenda.take(index))940			},941		)?;942		if let Some(s) = scheduled {943			T::Preimages::drop(&s.call);944945			if let Some(id) = s.maybe_id {946				Lookup::<T>::remove(id);947			}948			Self::deposit_event(Event::Canceled { when, index });949			Ok(())950		} else {951			Err(Error::<T>::NotFound.into())952		}953	}954955	fn do_schedule_named(956		id: TaskName,957		when: DispatchTime<T::BlockNumber>,958		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,959		priority: schedule::Priority,960		origin: T::PalletsOrigin,961		call: ScheduledCall<T>,962	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {963		// ensure id it is unique964		if Lookup::<T>::contains_key(&id) {965			return Err(Error::<T>::FailedToSchedule.into());966		}967968		let when = Self::resolve_time(when)?;969970		// sanitize maybe_periodic971		let maybe_periodic = maybe_periodic972			.filter(|p| p.1 > 1 && !p.0.is_zero())973			// Remove one from the number of repetitions since we will schedule one now.974			.map(|(p, c)| (p, c - 1));975976		let task = Scheduled {977			maybe_id: Some(id),978			priority,979			call,980			maybe_periodic,981			origin,982			_phantom: Default::default(),983		};984		Self::try_place_task(when, task)985	}986987	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {988		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {989			if let Some((when, index)) = lookup.take() {990				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {991					let scheduled = match agenda.get(index) {992						Some(scheduled) => scheduled,993						None => return Ok(()),994					};995996					if let Some(ref o) = origin {997						if matches!(998							T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),999							Some(Ordering::Less) | None1000						) {1001							return Err(BadOrigin.into());1002						}1003						T::Preimages::drop(&scheduled.call);1004					}10051006					agenda.take(index);10071008					Ok(())1009				})?;1010				Self::deposit_event(Event::Canceled { when, index });1011				Ok(())1012			} else {1013				Err(Error::<T>::NotFound.into())1014			}1015		})1016	}10171018	fn do_change_named_priority(1019		origin: T::PalletsOrigin,1020		id: TaskName,1021		priority: schedule::Priority,1022	) -> DispatchResult {1023		match Lookup::<T>::get(id) {1024			Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1025				let scheduled = match agenda.get_mut(index) {1026					Some(scheduled) => scheduled,1027					None => return Ok(()),1028				};10291030				if matches!(1031					T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1032					Some(Ordering::Less) | None1033				) {1034					return Err(BadOrigin.into());1035				}10361037				scheduled.priority = priority;1038				Self::deposit_event(Event::PriorityChanged {1039					task: (when, index),1040					priority,1041				});10421043				Ok(())1044			}),1045			None => Err(Error::<T>::NotFound.into()),1046		}1047	}1048}10491050enum ServiceTaskError {1051	/// Could not be executed due to missing preimage.1052	Unavailable,1053	/// Could not be executed due to weight limitations.1054	Overweight,1055}1056use ServiceTaskError::*;10571058/// A Scheduler-Runtime interface for finer payment handling.1059pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1060	/// Resolve the call dispatch, including any post-dispatch operations.1061	fn dispatch_call(1062		signer: Option<T::AccountId>,1063		function: <T as Config>::RuntimeCall,1064	) -> Result<1065		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1066		TransactionValidityError,1067	>;1068}10691070impl<T: Config> Pallet<T> {1071	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.1072	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1073		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1074			return;1075		}10761077		let mut incomplete_since = now + One::one();1078		let mut when = IncompleteSince::<T>::take().unwrap_or(now);1079		let mut executed = 0;10801081		let max_items = T::MaxScheduledPerBlock::get();1082		let mut count_down = max;1083		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1084		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1085			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1086				incomplete_since = incomplete_since.min(when);1087			}1088			when.saturating_inc();1089			count_down.saturating_dec();1090		}1091		incomplete_since = incomplete_since.min(when);1092		if incomplete_since <= now {1093			IncompleteSince::<T>::put(incomplete_since);1094		}1095	}10961097	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a1098	/// later block.1099	fn service_agenda(1100		weight: &mut WeightCounter,1101		executed: &mut u32,1102		now: T::BlockNumber,1103		when: T::BlockNumber,1104		max: u32,1105	) -> bool {1106		let mut agenda = Agenda::<T>::get(when);1107		let mut ordered = agenda1108			.iter()1109			.enumerate()1110			.filter_map(|(index, maybe_item)| {1111				maybe_item1112					.as_ref()1113					.map(|item| (index as u32, item.priority))1114			})1115			.collect::<Vec<_>>();1116		ordered.sort_by_key(|k| k.1);1117		let within_limit =1118			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1119		debug_assert!(1120			within_limit,1121			"weight limit should have been checked in advance"1122		);11231124		// Items which we know can be executed and have postponed for execution in a later block.1125		let mut postponed = (ordered.len() as u32).saturating_sub(max);1126		// Items which we don't know can ever be executed.1127		let mut dropped = 0;11281129		for (agenda_index, _) in ordered.into_iter().take(max as usize) {1130			let task = match agenda.take(agenda_index).take() {1131				None => continue,1132				Some(t) => t,1133			};1134			let base_weight = MarginalWeightInfo::<T>::service_task(1135				task.call.lookup_len().map(|x| x as usize),1136				task.maybe_id.is_some(),1137				task.maybe_periodic.is_some(),1138			);1139			if !weight.can_accrue(base_weight) {1140				postponed += 1;1141				break;1142			}1143			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1144			match result {1145				Err((Unavailable, slot)) => {1146					dropped += 1;1147					agenda.set_slot(agenda_index, slot);1148				}1149				Err((Overweight, slot)) => {1150					postponed += 1;1151					agenda.set_slot(agenda_index, slot);1152				}1153				Ok(()) => {1154					*executed += 1;1155				}1156			};1157		}1158		if postponed > 0 || dropped > 0 {1159			Agenda::<T>::insert(when, agenda);1160		} else {1161			Agenda::<T>::remove(when);1162		}1163		postponed == 01164	}11651166	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1167	///1168	/// This involves:1169	/// - removing and potentially replacing the `Lookup` entry for the task.1170	/// - realizing the task's call which can include a preimage lookup.1171	/// - Rescheduling the task for execution in a later agenda if periodic.1172	fn service_task(1173		weight: &mut WeightCounter,1174		now: T::BlockNumber,1175		when: T::BlockNumber,1176		agenda_index: u32,1177		is_first: bool,1178		mut task: ScheduledOf<T>,1179	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1180		let (call, lookup_len) = match T::Preimages::peek(&task.call) {1181			Ok(c) => c,1182			Err(_) => {1183				if let Some(ref id) = task.maybe_id {1184					Lookup::<T>::remove(id);1185				}11861187				return Err((Unavailable, Some(task)));1188			}1189		};11901191		weight.check_accrue(MarginalWeightInfo::<T>::service_task(1192			lookup_len.map(|x| x as usize),1193			task.maybe_id.is_some(),1194			task.maybe_periodic.is_some(),1195		));11961197		match Self::execute_dispatch(weight, task.origin.clone(), call) {1198			Err(Unavailable) => {1199				debug_assert!(false, "Checked to exist with `peek`");12001201				if let Some(ref id) = task.maybe_id {1202					Lookup::<T>::remove(id);1203				}12041205				Self::deposit_event(Event::CallUnavailable {1206					task: (when, agenda_index),1207					id: task.maybe_id,1208				});1209				Err((Unavailable, Some(task)))1210			}1211			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1212				T::Preimages::drop(&task.call);12131214				if let Some(ref id) = task.maybe_id {1215					Lookup::<T>::remove(id);1216				}12171218				Self::deposit_event(Event::PermanentlyOverweight {1219					task: (when, agenda_index),1220					id: task.maybe_id,1221				});1222				Err((Unavailable, Some(task)))1223			}1224			Err(Overweight) => {1225				// Preserve Lookup -- the task will be postponed.1226				Err((Overweight, Some(task)))1227			}1228			Ok(result) => {1229				Self::deposit_event(Event::Dispatched {1230					task: (when, agenda_index),1231					id: task.maybe_id,1232					result,1233				});12341235				let is_canceled = task1236					.maybe_id1237					.as_ref()1238					.map(|id| !Lookup::<T>::contains_key(id))1239					.unwrap_or(false);12401241				match &task.maybe_periodic {1242					&Some((period, count)) if !is_canceled => {1243						if count > 1 {1244							task.maybe_periodic = Some((period, count - 1));1245						} else {1246							task.maybe_periodic = None;1247						}1248						let wake = now.saturating_add(period);1249						Self::mandatory_place_task(wake, task);1250					}1251					_ => {1252						if let Some(ref id) = task.maybe_id {1253							Lookup::<T>::remove(id);1254						}12551256						T::Preimages::drop(&task.call)1257					}1258				}1259				Ok(())1260			}1261		}1262	}12631264	fn is_runtime_upgraded() -> bool {1265		let last = system::LastRuntimeUpgrade::<T>::get();1266		let current = T::Version::get();12671268		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)1269	}12701271	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1272	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1273	/// post info if available).1274	///1275	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1276	/// call itself).1277	fn execute_dispatch(1278		weight: &mut WeightCounter,1279		origin: T::PalletsOrigin,1280		call: <T as Config>::RuntimeCall,1281	) -> Result<DispatchResult, ServiceTaskError> {1282		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1283		let base_weight = match dispatch_origin.clone().as_signed() {1284			Some(_) => T::WeightInfo::execute_dispatch_signed(),1285			_ => T::WeightInfo::execute_dispatch_unsigned(),1286		};1287		let call_weight = call.get_dispatch_info().weight;1288		// We only allow a scheduled call if it cannot push the weight past the limit.1289		let max_weight = base_weight.saturating_add(call_weight);12901291		if !weight.can_accrue(max_weight) {1292			return Err(Overweight);1293		}12941295		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());12961297		let r = match ensured_origin {1298			Ok(ScheduledEnsureOriginSuccess::Root) => {1299				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1300			}1301			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1302				// Execute transaction via chain default pipeline1303				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1304				T::CallExecutor::dispatch_call(Some(sender), call)1305			}1306			Err(e) => Ok(Err(e.into())),1307		};13081309		let (maybe_actual_call_weight, result) = match r {1310			Ok(result) => match result {1311				Ok(post_info) => (post_info.actual_weight, Ok(())),1312				Err(error_and_info) => (1313					error_and_info.post_info.actual_weight,1314					Err(error_and_info.error),1315				),1316			},1317			Err(_) => {1318				log::error!(1319					target: "runtime::scheduler",1320					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1321					This block might have become invalid.");1322				(None, Err(DispatchError::CannotLookup))1323			}1324		};1325		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1326		weight.check_accrue(base_weight);1327		weight.check_accrue(call_weight);1328		Ok(result)1329	}1330}
addedpallets/scheduler-v2/src/mock.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -0,0 +1,287 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// 	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! # Scheduler test environment.
+
+use super::*;
+
+use crate as scheduler;
+use frame_support::{
+	ord_parameter_types, parameter_types,
+	traits::{ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize},
+	weights::constants::RocksDbWeight,
+};
+use frame_system::{EnsureRoot, RawOrigin};
+use sp_core::H256;
+use sp_runtime::{
+	testing::Header,
+	traits::{BlakeTwo256, IdentityLookup},
+	Perbill,
+};
+
+// Logger module to track execution.
+#[frame_support::pallet]
+pub mod logger {
+	use super::{OriginCaller, OriginTrait};
+	use frame_support::{pallet_prelude::*, parameter_types};
+	use frame_system::pallet_prelude::*;
+
+	parameter_types! {
+		static Log: Vec<(OriginCaller, u32)> = Vec::new();
+	}
+	pub fn log() -> Vec<(OriginCaller, u32)> {
+		Log::get().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 RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+	}
+
+	#[pallet::event]
+	#[pallet::generate_deposit(pub(super) fn deposit_event)]
+	pub enum Event<T: Config> {
+		Logged(u32, Weight),
+	}
+
+	#[pallet::call]
+	impl<T: Config> Pallet<T>
+	where
+		<T as frame_system::Config>::RuntimeOrigin: 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::mutate(|log| {
+				log.push((origin.caller().clone(), i));
+			});
+			Ok(())
+		}
+
+		#[pallet::weight(*weight)]
+		pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
+			Self::deposit_event(Event::Logged(i, weight));
+			Log::mutate(|log| {
+				log.push((origin.caller().clone(), i));
+			});
+			Ok(())
+		}
+	}
+}
+
+type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
+type Block = frame_system::mocking::MockBlock<Test>;
+
+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>},
+	}
+);
+
+// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
+pub struct BaseFilter;
+impl Contains<RuntimeCall> for BaseFilter {
+	fn contains(call: &RuntimeCall) -> bool {
+		!matches!(call, RuntimeCall::Logger(LoggerCall::log { .. }))
+	}
+}
+
+parameter_types! {
+	pub BlockWeights: frame_system::limits::BlockWeights =
+		frame_system::limits::BlockWeights::simple_max(
+			Weight::from_ref_time(2_000_000_000_000)
+			// .set_proof_size(u64::MAX),
+		);
+}
+impl system::Config for Test {
+	type BaseCallFilter = BaseFilter;
+	type BlockWeights = BlockWeights;
+	type BlockLength = ();
+	type DbWeight = RocksDbWeight;
+	type RuntimeOrigin = RuntimeOrigin;
+	type RuntimeCall = RuntimeCall;
+	type Index = u64;
+	type BlockNumber = u64;
+	type Hash = H256;
+	type Hashing = BlakeTwo256;
+	type AccountId = u64;
+	type Lookup = IdentityLookup<Self::AccountId>;
+	type Header = Header;
+	type RuntimeEvent = RuntimeEvent;
+	type BlockHashCount = ConstU64<250>;
+	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 RuntimeEvent = RuntimeEvent;
+}
+ord_parameter_types! {
+	pub const One: u64 = 1;
+}
+
+pub struct TestWeightInfo;
+impl WeightInfo for TestWeightInfo {
+	fn service_agendas_base() -> Weight {
+		Weight::from_ref_time(0b0000_0001)
+	}
+	fn service_agenda_base(i: u32) -> Weight {
+		Weight::from_ref_time((i << 8) as u64 + 0b0000_0010)
+	}
+	fn service_task_base() -> Weight {
+		Weight::from_ref_time(0b0000_0100)
+	}
+	fn service_task_periodic() -> Weight {
+		Weight::from_ref_time(0b0000_1100)
+	}
+	fn service_task_named() -> Weight {
+		Weight::from_ref_time(0b0001_0100)
+	}
+	// fn service_task_fetched(s: u32) -> Weight {
+	// 	Weight::from_ref_time((s << 8) as u64 + 0b0010_0100)
+	// }
+	fn execute_dispatch_signed() -> Weight {
+		Weight::from_ref_time(0b0100_0000)
+	}
+	fn execute_dispatch_unsigned() -> Weight {
+		Weight::from_ref_time(0b1000_0000)
+	}
+	fn schedule(_s: u32) -> Weight {
+		Weight::from_ref_time(50)
+	}
+	fn cancel(_s: u32) -> Weight {
+		Weight::from_ref_time(50)
+	}
+	fn schedule_named(_s: u32) -> Weight {
+		Weight::from_ref_time(50)
+	}
+	fn cancel_named(_s: u32) -> Weight {
+		Weight::from_ref_time(50)
+	}
+	fn change_named_priority(_s: u32) -> Weight {
+		Weight::from_ref_time(50)
+	}
+}
+parameter_types! {
+	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
+		BlockWeights::get().max_block;
+}
+
+pub struct EnsureSignedOneOrRoot;
+impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>> EnsureOrigin<O>
+	for EnsureSignedOneOrRoot
+{
+	type Success = ScheduledEnsureOriginSuccess<u64>;
+	fn try_origin(o: O) -> Result<Self::Success, O> {
+		o.into().and_then(|o| match o {
+			RawOrigin::Root => Ok(ScheduledEnsureOriginSuccess::Root),
+			RawOrigin::Signed(1) => Ok(ScheduledEnsureOriginSuccess::Signed(1)),
+			r => Err(O::from(r)),
+		})
+	}
+}
+
+pub struct Executor;
+impl DispatchCall<Test, sp_core::H160> for Executor {
+	fn dispatch_call(
+		signer: Option<u64>,
+		function: RuntimeCall,
+	) -> Result<
+		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+		TransactionValidityError,
+	> {
+		let origin = match signer {
+			Some(who) => RuntimeOrigin::signed(who),
+			None => RuntimeOrigin::none(),
+		};
+		Ok(function.dispatch(origin))
+	}
+}
+
+impl Config for Test {
+	type RuntimeEvent = RuntimeEvent;
+	type RuntimeOrigin = RuntimeOrigin;
+	type PalletsOrigin = OriginCaller;
+	type RuntimeCall = RuntimeCall;
+	type MaximumWeight = MaximumSchedulerWeight;
+	type ScheduleOrigin = EnsureSignedOneOrRoot;
+	type MaxScheduledPerBlock = ConstU32<10>;
+	type WeightInfo = TestWeightInfo;
+	type OriginPrivilegeCmp = EqualPrivilegeOnly;
+	type Preimages = ();
+	type PrioritySetOrigin = EnsureRoot<u64>;
+	type CallExecutor = Executor;
+}
+
+pub type LoggerCall = logger::Call<Test>;
+
+pub type SystemCall = frame_system::Call<Test>;
+
+pub fn new_test_ext() -> sp_io::TestExternalities {
+	let t = system::GenesisConfig::default()
+		.build_storage::<Test>()
+		.unwrap();
+	t.into()
+}
+
+pub fn run_to_block(n: u64) {
+	while System::block_number() < n {
+		Scheduler::on_finalize(System::block_number());
+		System::set_block_number(System::block_number() + 1);
+		Scheduler::on_initialize(System::block_number());
+	}
+}
+
+pub fn root() -> OriginCaller {
+	system::RawOrigin::Root.into()
+}
addedpallets/scheduler-v2/src/tests.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -0,0 +1,900 @@
+// 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-2022 Parity Technologies (UK) Ltd.
+// SPDX-License-Identifier: Apache-2.0
+
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// 	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! # Scheduler tests.
+
+use super::*;
+use crate::mock::{
+	logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,
+};
+use frame_support::{
+	assert_noop, assert_ok,
+	traits::{Contains, OnInitialize},
+	assert_err,
+};
+
+#[test]
+fn basic_scheduling_works() {
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+			&call
+		));
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		run_to_block(3);
+		assert!(logger::log().is_empty());
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(100);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+	});
+}
+
+#[test]
+fn schedule_after_works() {
+	new_test_ext().execute_with(|| {
+		run_to_block(2);
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+			&call
+		));
+		// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::After(3),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		run_to_block(5);
+		assert!(logger::log().is_empty());
+		run_to_block(6);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(100);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+	});
+}
+
+#[test]
+fn schedule_after_zero_works() {
+	new_test_ext().execute_with(|| {
+		run_to_block(2);
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+			&call
+		));
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::After(0),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		// Will trigger on the next block.
+		run_to_block(3);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(100);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+	});
+}
+
+#[test]
+fn periodic_scheduling_works() {
+	new_test_ext().execute_with(|| {
+		// at #4, every 3 blocks, 3 times.
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			Some((3, 3)),
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {
+				i: 42,
+				weight: Weight::from_ref_time(10)
+			}))
+			.unwrap()
+		));
+		run_to_block(3);
+		assert!(logger::log().is_empty());
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(6);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(7);
+		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
+		run_to_block(9);
+		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
+		run_to_block(10);
+		assert_eq!(
+			logger::log(),
+			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+		);
+		run_to_block(100);
+		assert_eq!(
+			logger::log(),
+			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+		);
+	});
+}
+
+#[test]
+fn cancel_named_scheduling_works_with_normal_cancel() {
+	new_test_ext().execute_with(|| {
+		// at #4.
+		Scheduler::do_schedule_named(
+			[1u8; 32],
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+				i: 69,
+				weight: Weight::from_ref_time(10),
+			}))
+			.unwrap(),
+		)
+		.unwrap();
+		let i = Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+				i: 42,
+				weight: Weight::from_ref_time(10),
+			}))
+			.unwrap(),
+		)
+		.unwrap();
+		run_to_block(3);
+		assert!(logger::log().is_empty());
+		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
+		assert_ok!(Scheduler::do_cancel(None, i));
+		run_to_block(100);
+		assert!(logger::log().is_empty());
+	});
+}
+
+#[test]
+fn cancel_named_periodic_scheduling_works() {
+	new_test_ext().execute_with(|| {
+		// at #4, every 3 blocks, 3 times.
+		Scheduler::do_schedule_named(
+			[1u8; 32],
+			DispatchTime::At(4),
+			Some((3, 3)),
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+				i: 42,
+				weight: Weight::from_ref_time(10),
+			}))
+			.unwrap(),
+		)
+		.unwrap();
+		// same id results in error.
+		assert!(Scheduler::do_schedule_named(
+			[1u8; 32],
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+				i: 69,
+				weight: Weight::from_ref_time(10)
+			}))
+			.unwrap(),
+		)
+		.is_err());
+		// different id is ok.
+		Scheduler::do_schedule_named(
+			[2u8; 32],
+			DispatchTime::At(8),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
+				i: 69,
+				weight: Weight::from_ref_time(10),
+			}))
+			.unwrap(),
+		)
+		.unwrap();
+		run_to_block(3);
+		assert!(logger::log().is_empty());
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(6);
+		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
+		run_to_block(100);
+		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
+	});
+}
+
+#[test]
+fn scheduler_respects_weight_limits() {
+	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: max_weight / 3 * 2,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: max_weight / 3 * 2,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		// 69 and 42 do not fit together
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 42u32)]);
+		run_to_block(5);
+		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
+	});
+}
+
+/// Permanently overweight calls are not deleted but also not executed.
+#[test]
+fn scheduler_does_not_delete_permanently_overweight_call() {
+	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: max_weight,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		// Never executes.
+		run_to_block(100);
+		assert_eq!(logger::log(), vec![]);
+
+		// Assert the `PermanentlyOverweight` event.
+		assert_eq!(
+			System::events().last().unwrap().event,
+			crate::Event::PermanentlyOverweight {
+				task: (4, 0),
+				id: None
+			}
+			.into(),
+		);
+		// The call is still in the agenda.
+		assert!(Agenda::<Test>::get(4).agenda[0].is_some());
+	});
+}
+
+#[test]
+fn scheduler_periodic_tasks_always_find_place() {
+	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+	let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();
+
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: (max_weight / 3) * 2,
+		});
+		let call = <ScheduledCall<Test>>::new(call).unwrap();
+
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			Some((4, u32::MAX)),
+			127,
+			root(),
+			call.clone(),
+		));
+		// Executes 5 times till block 20.
+		run_to_block(20);
+		assert_eq!(logger::log().len(), 5);
+
+		// Block 28 will already be full.
+		for _ in 0..max_per_block {
+			assert_ok!(Scheduler::do_schedule(
+				DispatchTime::At(28),
+				None,
+				120,
+				root(),
+				call.clone(),
+			));
+		}
+
+		run_to_block(24);
+		assert_eq!(logger::log().len(), 6);
+
+		// The periodic task should be postponed
+		assert_eq!(<Agenda<Test>>::get(29).agenda.len(), 1);
+
+		run_to_block(27); // will call on_initialize(28)
+		assert_eq!(logger::log().len(), 6);
+
+		run_to_block(28); // will call on_initialize(29)
+		assert_eq!(logger::log().len(), 7);
+	});
+}
+
+#[test]
+fn scheduler_respects_priority_ordering() {
+	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: max_weight / 3,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			1,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: max_weight / 3,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			0,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
+	});
+}
+
+#[test]
+fn scheduler_respects_priority_ordering_with_soft_deadlines() {
+	new_test_ext().execute_with(|| {
+		let max_weight: Weight = <Test as Config>::MaximumWeight::get();
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: max_weight / 5 * 2,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			255,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: max_weight / 5 * 2,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 2600,
+			weight: max_weight / 5 * 4,
+		});
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			126,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+
+		// 2600 does not fit with 69 or 42, but has higher priority, so will go through
+		run_to_block(4);
+		assert_eq!(logger::log(), vec![(root(), 2600u32)]);
+		// 69 and 42 fit together
+		run_to_block(5);
+		assert_eq!(
+			logger::log(),
+			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+		);
+	});
+}
+
+#[test]
+fn on_initialize_weight_is_correct() {
+	new_test_ext().execute_with(|| {
+		let call_weight = Weight::from_ref_time(25);
+
+		// Named
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 3,
+			weight: call_weight + Weight::from_ref_time(1),
+		});
+		assert_ok!(Scheduler::do_schedule_named(
+			[1u8; 32],
+			DispatchTime::At(3),
+			None,
+			255,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: call_weight + Weight::from_ref_time(2),
+		});
+		// Anon Periodic
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(2),
+			Some((1000, 3)),
+			128,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: call_weight + Weight::from_ref_time(3),
+		});
+		// Anon
+		assert_ok!(Scheduler::do_schedule(
+			DispatchTime::At(2),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+		// Named Periodic
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 2600,
+			weight: call_weight + Weight::from_ref_time(4),
+		});
+		assert_ok!(Scheduler::do_schedule_named(
+			[2u8; 32],
+			DispatchTime::At(1),
+			Some((1000, 3)),
+			126,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		));
+
+		// Will include the named periodic only
+		assert_eq!(
+			Scheduler::on_initialize(1),
+			TestWeightInfo::service_agendas_base()
+				+ TestWeightInfo::service_agenda_base(1)
+				+ <MarginalWeightInfo<Test>>::service_task(None, true, true)
+				+ TestWeightInfo::execute_dispatch_unsigned()
+				+ call_weight + Weight::from_ref_time(4)
+		);
+		assert_eq!(IncompleteSince::<Test>::get(), None);
+		assert_eq!(logger::log(), vec![(root(), 2600u32)]);
+
+		// Will include anon and anon periodic
+		assert_eq!(
+			Scheduler::on_initialize(2),
+			TestWeightInfo::service_agendas_base()
+				+ TestWeightInfo::service_agenda_base(2)
+				+ <MarginalWeightInfo<Test>>::service_task(None, false, true)
+				+ TestWeightInfo::execute_dispatch_unsigned()
+				+ call_weight + Weight::from_ref_time(3)
+				+ <MarginalWeightInfo<Test>>::service_task(None, false, false)
+				+ TestWeightInfo::execute_dispatch_unsigned()
+				+ call_weight + Weight::from_ref_time(2)
+		);
+		assert_eq!(IncompleteSince::<Test>::get(), None);
+		assert_eq!(
+			logger::log(),
+			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+		);
+
+		// Will include named only
+		assert_eq!(
+			Scheduler::on_initialize(3),
+			TestWeightInfo::service_agendas_base()
+				+ TestWeightInfo::service_agenda_base(1)
+				+ <MarginalWeightInfo<Test>>::service_task(None, true, false)
+				+ TestWeightInfo::execute_dispatch_unsigned()
+				+ call_weight + Weight::from_ref_time(1)
+		);
+		assert_eq!(IncompleteSince::<Test>::get(), None);
+		assert_eq!(
+			logger::log(),
+			vec![
+				(root(), 2600u32),
+				(root(), 69u32),
+				(root(), 42u32),
+				(root(), 3u32)
+			]
+		);
+
+		// Will contain none
+		let actual_weight = Scheduler::on_initialize(4);
+		assert_eq!(
+			actual_weight,
+			TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)
+		);
+	});
+}
+
+#[test]
+fn root_calls_works() {
+	new_test_ext().execute_with(|| {
+		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+		assert_ok!(Scheduler::schedule_named(
+			RuntimeOrigin::root(),
+			[1u8; 32],
+			4,
+			None,
+			Some(127),
+			call,
+		));
+		assert_ok!(Scheduler::schedule(
+			RuntimeOrigin::root(),
+			4,
+			None,
+			Some(127),
+			call2
+		));
+		run_to_block(3);
+		// Scheduled calls are in the agenda.
+		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+		assert!(logger::log().is_empty());
+		assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));
+		assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));
+		// Scheduled calls are made NONE, so should not effect state
+		run_to_block(100);
+		assert!(logger::log().is_empty());
+	});
+}
+
+#[test]
+fn fails_to_schedule_task_in_the_past() {
+	new_test_ext().execute_with(|| {
+		run_to_block(3);
+
+		let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+
+		assert_noop!(
+			Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),
+			Error::<Test>::TargetBlockNumberInPast,
+		);
+
+		assert_noop!(
+			Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),
+			Error::<Test>::TargetBlockNumberInPast,
+		);
+
+		assert_noop!(
+			Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),
+			Error::<Test>::TargetBlockNumberInPast,
+		);
+	});
+}
+
+#[test]
+fn should_use_origin() {
+	new_test_ext().execute_with(|| {
+		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+		assert_ok!(Scheduler::schedule_named(
+			system::RawOrigin::Signed(1).into(),
+			[1u8; 32],
+			4,
+			None,
+			None,
+			call,
+		));
+		assert_ok!(Scheduler::schedule(
+			system::RawOrigin::Signed(1).into(),
+			4,
+			None,
+			None,
+			call2,
+		));
+		run_to_block(3);
+		// Scheduled calls are in the agenda.
+		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+		assert!(logger::log().is_empty());
+		assert_ok!(Scheduler::cancel_named(
+			system::RawOrigin::Signed(1).into(),
+			[1u8; 32]
+		));
+		assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
+		// Scheduled calls are made NONE, so should not effect state
+		run_to_block(100);
+		assert!(logger::log().is_empty());
+	});
+}
+
+#[test]
+fn should_check_origin() {
+	new_test_ext().execute_with(|| {
+		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 69,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+		assert_noop!(
+			Scheduler::schedule_named(
+				system::RawOrigin::Signed(2).into(),
+				[1u8; 32],
+				4,
+				None,
+				None,
+				call
+			),
+			BadOrigin
+		);
+		assert_noop!(
+			Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),
+			BadOrigin
+		);
+	});
+}
+
+#[test]
+fn should_check_origin_for_cancel() {
+	new_test_ext().execute_with(|| {
+		let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
+			i: 69,
+			weight: Weight::from_ref_time(10),
+		}));
+		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		}));
+		assert_ok!(Scheduler::schedule_named(
+			system::RawOrigin::Signed(1).into(),
+			[1u8; 32],
+			4,
+			None,
+			None,
+			call,
+		));
+		assert_ok!(Scheduler::schedule(
+			system::RawOrigin::Signed(1).into(),
+			4,
+			None,
+			None,
+			call2,
+		));
+		run_to_block(3);
+		// Scheduled calls are in the agenda.
+		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);
+		assert!(logger::log().is_empty());
+		assert_noop!(
+			Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),
+			BadOrigin
+		);
+		assert_noop!(
+			Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
+			BadOrigin
+		);
+		assert_noop!(
+			Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),
+			BadOrigin
+		);
+		assert_noop!(
+			Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
+			BadOrigin
+		);
+		run_to_block(5);
+		assert_eq!(
+			logger::log(),
+			vec![
+				(system::RawOrigin::Signed(1).into(), 69u32),
+				(system::RawOrigin::Signed(1).into(), 42u32)
+			]
+		);
+	});
+}
+
+/// Cancelling a call and then scheduling a second call for the same
+/// block results in different addresses.
+#[test]
+fn schedule_does_not_resuse_addr() {
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+
+		// Schedule both calls.
+		let addr_1 = Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call.clone()).unwrap(),
+		)
+		.unwrap();
+		// Cancel the call.
+		assert_ok!(Scheduler::do_cancel(None, addr_1));
+		let addr_2 = Scheduler::do_schedule(
+			DispatchTime::At(4),
+			None,
+			127,
+			root(),
+			<ScheduledCall<Test>>::new(call).unwrap(),
+		)
+		.unwrap();
+
+		// Should not re-use the address.
+		assert!(addr_1 != addr_2);
+	});
+}
+
+#[test]
+fn schedule_agenda_overflows() {
+	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
+
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+		let call = <ScheduledCall<Test>>::new(call).unwrap();
+
+		// Schedule the maximal number allowed per block.
+		for _ in 0..max {
+			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();
+		}
+
+		// One more time and it errors.
+		assert_noop!(
+			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),
+			<Error<Test>>::AgendaIsExhausted,
+		);
+
+		run_to_block(4);
+		// All scheduled calls are executed.
+		assert_eq!(logger::log().len() as u32, max);
+	});
+}
+
+/// Cancelling and scheduling does not overflow the agenda but fills holes.
+#[test]
+fn cancel_and_schedule_fills_holes() {
+	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
+	assert!(
+		max > 3,
+		"This test only makes sense for MaxScheduledPerBlock > 3"
+	);
+
+	new_test_ext().execute_with(|| {
+		let call = RuntimeCall::Logger(LoggerCall::log {
+			i: 42,
+			weight: Weight::from_ref_time(10),
+		});
+		let call = <ScheduledCall<Test>>::new(call).unwrap();
+		let mut addrs = Vec::<_>::default();
+
+		// Schedule the maximal number allowed per block.
+		for _ in 0..max {
+			addrs.push(
+				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+					.unwrap(),
+			);
+		}
+		// Cancel three of them.
+		for addr in addrs.into_iter().take(3) {
+			Scheduler::do_cancel(None, addr).unwrap();
+		}
+		// Schedule three new ones.
+		for i in 0..3 {
+			let (_block, index) =
+				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+					.unwrap();
+			assert_eq!(i, index);
+		}
+
+		run_to_block(4);
+		// Maximum number of calls are executed.
+		assert_eq!(logger::log().len() as u32, max);
+	});
+}
+
+#[test]
+fn cannot_schedule_too_big_tasks() {
+	new_test_ext().execute_with(|| {
+		let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {
+			remark: vec![0; EncodedCall::bound() - 4],
+		}));
+
+		assert_ok!(Scheduler::schedule(
+			RuntimeOrigin::root(),
+			4,
+			None,
+			Some(127),
+			call
+		));
+
+		let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {
+			remark: vec![0; EncodedCall::bound() - 3],
+		}));
+
+		assert_err!(
+			Scheduler::schedule(RuntimeOrigin::root(), 4, None, Some(127), call),
+			<Error<Test>>::TooBigScheduledCall
+		);
+	});
+}
addedpallets/scheduler-v2/src/weights.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/scheduler-v2/src/weights.rs
@@ -0,0 +1,234 @@
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
+
+//! Autogenerated weights for pallet_unique_scheduler_v2
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-10-28, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
+
+// Executed Command:
+// target/release/unique-collator
+// benchmark
+// pallet
+// --pallet
+// pallet-unique-scheduler-v2
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
+// --steps=50
+// --repeat=80
+// --heap-pages=4096
+// --output=./pallets/scheduler-v2/src/weights.rs
+
+#![cfg_attr(rustfmt, rustfmt_skip)]
+#![allow(unused_parens)]
+#![allow(unused_imports)]
+#![allow(missing_docs)]
+#![allow(clippy::unnecessary_cast)]
+
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
+use sp_std::marker::PhantomData;
+
+/// Weight functions needed for pallet_unique_scheduler_v2.
+pub trait WeightInfo {
+	fn service_agendas_base() -> Weight;
+	fn service_agenda_base(s: u32, ) -> Weight;
+	fn service_task_base() -> Weight;
+	fn service_task_named() -> Weight;
+	fn service_task_periodic() -> Weight;
+	fn execute_dispatch_signed() -> Weight;
+	fn execute_dispatch_unsigned() -> Weight;
+	fn schedule(s: u32, ) -> Weight;
+	fn cancel(s: u32, ) -> Weight;
+	fn schedule_named(s: u32, ) -> Weight;
+	fn cancel_named(s: u32, ) -> Weight;
+	fn change_named_priority(s: u32, ) -> Weight;
+}
+
+/// Weights for pallet_unique_scheduler_v2 using the Substrate node and recommended hardware.
+pub struct SubstrateWeight<T>(PhantomData<T>);
+impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
+	// Storage: Scheduler IncompleteSince (r:1 w:1)
+	fn service_agendas_base() -> Weight {
+		Weight::from_ref_time(5_253_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn service_agenda_base(s: u32, ) -> Weight {
+		Weight::from_ref_time(3_858_000 as u64)
+			// Standard Error: 2_617
+			.saturating_add(Weight::from_ref_time(579_704 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	fn service_task_base() -> Weight {
+		Weight::from_ref_time(10_536_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn service_task_named() -> Weight {
+		Weight::from_ref_time(12_018_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	fn service_task_periodic() -> Weight {
+		Weight::from_ref_time(10_669_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+	}
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
+	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
+	fn execute_dispatch_signed() -> Weight {
+		Weight::from_ref_time(36_083_000 as u64)
+			.saturating_add(T::DbWeight::get().reads(5 as u64))
+			.saturating_add(T::DbWeight::get().writes(3 as u64))
+	}
+	fn execute_dispatch_unsigned() -> Weight {
+		Weight::from_ref_time(4_386_000 as u64)
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule(s: u32, ) -> Weight {
+		Weight::from_ref_time(17_257_000 as u64)
+			// Standard Error: 2_791
+			.saturating_add(Weight::from_ref_time(574_832 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn cancel(s: u32, ) -> Weight {
+		Weight::from_ref_time(19_803_000 as u64)
+			// Standard Error: 1_177
+			.saturating_add(Weight::from_ref_time(475_027 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(1 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule_named(s: u32, ) -> Weight {
+		Weight::from_ref_time(18_746_000 as u64)
+			// Standard Error: 2_997
+			.saturating_add(Weight::from_ref_time(635_697 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn cancel_named(s: u32, ) -> Weight {
+		Weight::from_ref_time(20_983_000 as u64)
+			// Standard Error: 1_850
+			.saturating_add(Weight::from_ref_time(518_812 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:0)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn change_named_priority(s: u32, ) -> Weight {
+		Weight::from_ref_time(21_591_000 as u64)
+			// Standard Error: 4_187
+			.saturating_add(Weight::from_ref_time(531_231 as u64).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
+			.saturating_add(T::DbWeight::get().writes(1 as u64))
+	}
+}
+
+// For backwards compatibility and tests
+impl WeightInfo for () {
+	// Storage: Scheduler IncompleteSince (r:1 w:1)
+	fn service_agendas_base() -> Weight {
+		Weight::from_ref_time(5_253_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn service_agenda_base(s: u32, ) -> Weight {
+		Weight::from_ref_time(3_858_000 as u64)
+			// Standard Error: 2_617
+			.saturating_add(Weight::from_ref_time(579_704 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	fn service_task_base() -> Weight {
+		Weight::from_ref_time(10_536_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn service_task_named() -> Weight {
+		Weight::from_ref_time(12_018_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: System LastRuntimeUpgrade (r:1 w:0)
+	fn service_task_periodic() -> Weight {
+		Weight::from_ref_time(10_669_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+	}
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
+	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
+	fn execute_dispatch_signed() -> Weight {
+		Weight::from_ref_time(36_083_000 as u64)
+			.saturating_add(RocksDbWeight::get().reads(5 as u64))
+			.saturating_add(RocksDbWeight::get().writes(3 as u64))
+	}
+	fn execute_dispatch_unsigned() -> Weight {
+		Weight::from_ref_time(4_386_000 as u64)
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule(s: u32, ) -> Weight {
+		Weight::from_ref_time(17_257_000 as u64)
+			// Standard Error: 2_791
+			.saturating_add(Weight::from_ref_time(574_832 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn cancel(s: u32, ) -> Weight {
+		Weight::from_ref_time(19_803_000 as u64)
+			// Standard Error: 1_177
+			.saturating_add(Weight::from_ref_time(475_027 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(1 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn schedule_named(s: u32, ) -> Weight {
+		Weight::from_ref_time(18_746_000 as u64)
+			// Standard Error: 2_997
+			.saturating_add(Weight::from_ref_time(635_697 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn cancel_named(s: u32, ) -> Weight {
+		Weight::from_ref_time(20_983_000 as u64)
+			// Standard Error: 1_850
+			.saturating_add(Weight::from_ref_time(518_812 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
+	// Storage: Scheduler Lookup (r:1 w:0)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn change_named_priority(s: u32, ) -> Weight {
+		Weight::from_ref_time(21_591_000 as u64)
+			// Standard Error: 4_187
+			.saturating_add(Weight::from_ref_time(531_231 as u64).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
+			.saturating_add(RocksDbWeight::get().writes(1 as u64))
+	}
+}
deletedpallets/scheduler/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/scheduler/CHANGELOG.md
+++ /dev/null
@@ -1,10 +0,0 @@
-<!-- bureaucrate goes here -->
-## [v0.1.1] 2022-08-16
-
-### Other changes
-
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
\ No newline at end of file
deletedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ /dev/null
@@ -1,53 +0,0 @@
-[package]
-name = "pallet-unique-scheduler"
-version = "0.1.1"
-authors = ["Unique Network <support@uniquenetwork.io>"]
-edition = "2021"
-license = "GPLv3"
-homepage = "https://unique.network"
-repository = "https://github.com/UniqueNetwork/unique-chain"
-description = "Unique Scheduler pallet"
-readme = "README.md"
-
-[dependencies]
-serde = { version = "1.0.130", default-features = false }
-codec = { package = "parity-scale-codec", version = "3.1.2", default-features = false }
-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.30" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.30' }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30" }
-log = { version = "0.4.16", default-features = false }
-
-[dev-dependencies]
-sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-[features]
-default = ["std"]
-std = [
-	"codec/std",
-	"sp-runtime/std",
-	"frame-benchmarking/std",
-	"frame-support/std",
-	"frame-system/std",
-	"up-sponsorship/std",
-	"sp-io/std",
-	"sp-std/std",
-	"sp-core/std",
-	"log/std",
-]
-runtime-benchmarks = [
-	"frame-benchmarking",
-	"frame-support/runtime-benchmarks",
-	"frame-system/runtime-benchmarks",
-]
-try-runtime = ["frame-support/try-runtime"]
deletedpallets/scheduler/README.mddiffbeforeafterboth
--- a/pallets/scheduler/README.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# Scheduler
-A module for scheduling dispatches.
-
-- [`scheduler::Trait`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/trait.Trait.html)
-- [`Call`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/enum.Call.html)
-- [`Module`](https://docs.rs/pallet-scheduler/latest/pallet_scheduler/struct.Module.html)
-
-## Overview
-
-This module 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.
-
-**NOTE:** The scheduled calls will be dispatched with the default filter
-for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
-except root which will get no filter. And not the filter contained in origin
-use to call `fn schedule`.
-
-If a call is scheduled using proxy or whatever mecanism which adds filter,
-then those filter will not be used when dispatching the schedule call.
-
-## Interface
-
-### 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.
-* `cancel_named` - the named complement to the cancel function.
-
-License: Unlicense
deletedpallets/scheduler/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/benchmarking.rs
+++ /dev/null
@@ -1,260 +0,0 @@
-// 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.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Scheduler pallet benchmarking.
-
-use super::*;
-use frame_benchmarking::{benchmarks, account};
-use frame_support::{
-	ensure,
-	traits::{OnInitialize},
-};
-use frame_system::RawOrigin;
-use sp_runtime::traits::Hash;
-use sp_std::{prelude::*, vec};
-
-use crate::Pallet as Scheduler;
-use frame_system::Pallet as System;
-use frame_support::traits::Currency;
-
-const BLOCK_NUMBER: u32 = 2;
-
-fn make_scheduled_id(src: u32) -> ScheduledId {
-	let slice_id: [u8; 4] = src.encode().try_into().unwrap();
-	let mut id: [u8; 16] = [0; 16];
-	id[..4].clone_from_slice(&slice_id);
-	id
-}
-
-/// Add `n` named items to the schedule.
-///
-/// For `resolved`:
-/// - `None`: aborted (hash without preimage)
-/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
-/// - `Some(false)`: plain call
-fn fill_schedule<T: Config>(
-	when: T::BlockNumber,
-	n: u32,
-	periodic: bool,
-	resolved: Option<bool>,
-) -> Result<(), &'static str> {
-	let t = DispatchTime::At(when);
-	let caller = account("user", 0, 1);
-
-	// Give the sender account max funds for transfer (their account will never reasonably be killed).
-	T::Currency::make_free_balance_be(&caller, T::Currency::minimum_balance());
-
-	for i in 0..n {
-		let (call, hash) = call_and_hash::<T>(i);
-		let call_or_hash = match resolved {
-			Some(_) => call.into(),
-			None => CallOrHashOf::<T>::Hash(hash),
-		};
-		let period = match periodic {
-			true => Some(((i + 100).into(), 100)),
-			false => None,
-		};
-
-		let id = make_scheduled_id(i);
-		let origin = frame_system::RawOrigin::Signed(caller.clone()).into();
-		Scheduler::<T>::do_schedule_named(id, t, period, 0, origin, call_or_hash)?;
-	}
-	ensure!(
-		Agenda::<T>::get(when).len() == n as usize,
-		"didn't fill schedule"
-	);
-	Ok(())
-}
-
-fn call_and_hash<T: Config>(i: u32) -> (<T as Config>::RuntimeCall, T::Hash) {
-	// Essentially a no-op call.
-	let call: <T as Config>::RuntimeCall = frame_system::Call::remark { remark: i.encode() }.into();
-	let hash = T::Hashing::hash_of(&call);
-	(call, hash)
-}
-
-benchmarks! {
-	on_initialize_periodic_named_resolved {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, true, Some(true))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		for i in 0..s {
-			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
-		}
-	}
-
-	on_initialize_named_resolved {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, Some(true))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		assert!(Agenda::<T>::iter().count() == 0);
-	}
-
-	on_initialize_periodic {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, true, Some(false))?;
-	}: { Scheduler::<T>::on_initialize(when); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		for i in 0..s {
-			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
-		}
-	}
-
-	on_initialize_periodic_resolved {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, true, Some(true))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s );
-		for i in 0..s {
-			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
-		}
-	}
-
-	on_initialize_aborted {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, None)?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), 0);
-	}
-
-	on_initialize_named_aborted {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, Some(false))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-	}
-
-	on_initialize_named {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, None)?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), 0);
-	}
-
-	on_initialize {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, Some(false))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		assert!(Agenda::<T>::iter().count() == 0);
-	}
-
-	on_initialize_resolved {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s, false, Some(true))?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		assert!(Agenda::<T>::iter().count() == 0);
-	}
-
-	schedule_named {
-		let caller: T::AccountId = account("user", 0, 1);
-		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
-		let s in 0 .. T::MaxScheduledPerBlock::get();
-		let slice_id: [u8; 4] = s.encode().try_into().unwrap();
-		let mut id: [u8; 16] =  [0; 16];
-		id[..4].clone_from_slice(&slice_id);
-		let when = BLOCK_NUMBER.into();
-		let periodic = Some((T::BlockNumber::one(), 100));
-		let priority = None;
-		// Essentially a no-op call.
-		let inner_call = frame_system::Call::set_storage { items: vec![] }.into();
-		let call = Box::new(CallOrHashOf::<T>::Value(inner_call));
-		fill_schedule::<T>(when, s, true, Some(false))?;
-	}: _(origin, id, when, periodic, priority, call)
-	verify {
-		ensure!(
-			Agenda::<T>::get(when).len() == (s + 1) as usize,
-			"didn't add to schedule"
-		);
-	}
-
-	cancel_named {
-		let caller: T::AccountId = account("user", 0, 1);
-		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		let idx = s - 1;
-		let id = make_scheduled_id(idx);
-		fill_schedule::<T>(when, s, true, Some(false))?;
-	}: _(origin, id)
-	verify {
-		ensure!(
-			Lookup::<T>::get(id).is_none(),
-			"didn't remove from lookup"
-		);
-		// Removed schedule is NONE
-		ensure!(
-			Agenda::<T>::get(when)[idx as usize].is_none(),
-			"didn't remove from schedule"
-		);
-	}
-
-	change_named_priority {
-		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		let idx = s - 1;
-		let id = make_scheduled_id(idx);
-		let priority = 42;
-		fill_schedule::<T>(when, s, true, Some(false))?;
-	}: _(origin, id, priority)
-	verify {
-		ensure!(
-			Agenda::<T>::get(when)[idx as usize].clone().unwrap().priority == priority,
-			"didn't change the priority"
-		);
-	}
-
-	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
-}
deletedpallets/scheduler/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/lib.rs
+++ /dev/null
@@ -1,802 +0,0 @@
-// 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-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	<http://www.apache.org/licenses/LICENSE-2.0>
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! # Unique scheduler
-//! A Pallet for scheduling dispatches.
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Pallet`]
-//!
-//! ## Overview
-//!
-//! This Pallet exposes capabilities for scheduling dispatches to occur at a
-//! specified block number or at a specified period. These scheduled dispatches
-//! should be named and may be canceled.
-//!
-//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.
-//! Any user can book a call of a certain transaction to a specific block number.
-//! Also possible to book a call with a certain frequency.
-//!
-//! Key differences from the original pallet:
-//! <https://crates.io/crates/pallet-scheduler>
-//! Schedule Id restricted by 16 bytes. Identificator for booked call.
-//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.
-//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.
-//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.
-//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.
-//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.
-//!
-//! ## Interface
-//!
-//! ### Dispatchable Functions
-//!
-//! * `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)]
-
-#[cfg(feature = "runtime-benchmarks")]
-mod benchmarking;
-
-pub mod weights;
-
-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::{
-	traits::{BadOrigin, One, Saturating, Zero},
-	RuntimeDebug, DispatchErrorWithPostInfo,
-};
-use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
-
-use frame_support::{
-	dispatch::{
-		DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter,
-		GetDispatchInfo,
-	},
-	traits::{
-		schedule::{self, DispatchTime, MaybeHashed},
-		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,
-		StorageVersion,
-	},
-	weights::{Weight},
-};
-
-pub use weights::WeightInfo;
-
-/// 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;
-
-pub type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];
-pub type CallOrHashOf<T> =
-	MaybeHashed<<T as Config>::RuntimeCall, <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 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {
-	/// The unique identity for this task, if there is one.
-	maybe_id: Option<ScheduledId>,
-	/// This task's priority.
-	priority: schedule::Priority,
-	/// The call to be dispatched.
-	call: Call,
-	/// If the call is periodic, then this points to the information concerning that.
-	maybe_periodic: Option<schedule::Period<BlockNumber>>,
-	/// The origin to dispatch the call.
-	origin: PalletsOrigin,
-	_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> =
-	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;
-
-pub enum ScheduledEnsureOriginSuccess<AccountId> {
-	Root,
-	Signed(AccountId),
-}
-
-#[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 {}
-}
-
-#[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 {}
-}
-
-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_resolved(2)
-					- Self::on_initialize_periodic_named_resolved(1)
-			}
-			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(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 {}
-
-#[frame_support::pallet]
-pub mod pallet {
-	use super::*;
-	use frame_support::{
-		dispatch::PostDispatchInfo,
-		pallet_prelude::*,
-		traits::{
-			schedule::{LookupError, LOWEST_PRIORITY},
-			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 RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
-
-		/// The aggregated origin which the dispatch will take.
-		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
-			+ From<Self::PalletsOrigin>
-			+ IsType<<Self as system::Config>::RuntimeOrigin>;
-
-		/// 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 RuntimeCall: Parameter
-			+ Dispatchable<
-				RuntimeOrigin = <Self as Config>::RuntimeOrigin,
-				PostInfo = PostDispatchInfo,
-			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>
-			+ GetDispatchInfo
-			+ From<system::Call<Self>>;
-
-		/// 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>;
-
-		/// Required origin to schedule or cancel calls.
-		type ScheduleOrigin: EnsureOrigin<
-			<Self as system::Config>::RuntimeOrigin,
-			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,
-		>;
-
-		/// Required origin to set/change calls' priority.
-		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
-
-		/// 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.
-		///
-		/// 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>;
-	}
-
-	/// A Scheduler-Runtime interface for finer payment handling.
-	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
-		/// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.
-		fn reserve_balance(
-			id: ScheduledId,
-			sponsor: <T as frame_system::Config>::AccountId,
-			call: <T as Config>::RuntimeCall,
-			count: u32,
-		) -> Result<(), DispatchError>;
-
-		/// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.
-		fn pay_for_call(
-			id: ScheduledId,
-			sponsor: <T as frame_system::Config>::AccountId,
-			call: <T as Config>::RuntimeCall,
-		) -> Result<u128, DispatchError>;
-
-		/// Resolve the call dispatch, including any post-dispatch operations.
-		fn dispatch_call(
-			signer: Option<T::AccountId>,
-			function: <T as Config>::RuntimeCall,
-		) -> Result<
-			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
-			TransactionValidityError,
-		>;
-
-		/// Release unspent reserved funds in case of a schedule cancel.
-		fn cancel_reserve(
-			id: ScheduledId,
-			sponsor: <T as frame_system::Config>::AccountId,
-		) -> Result<u128, DispatchError>;
-	}
-
-	/// 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 },
-		/// Scheduled task's priority has changed
-		PriorityChanged {
-			when: T::BlockNumber,
-			index: u32,
-			priority: schedule::Priority,
-		},
-		/// 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.
-		NotFound,
-		/// Given target block number is in the past.
-		TargetBlockNumberInPast,
-		/// Reschedule failed because it does not change scheduled time.
-		RescheduleNoChange,
-	}
-
-	#[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<_>>();
-
-			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 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 = s.maybe_id.is_some();
-
-				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));
-						} else if let Some(ref id) = s.maybe_id {
-							Lookup::<T>::remove(id);
-						}
-						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>::RuntimeOrigin 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.all_gt(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 scheduled_origin =
-					<<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(
-						s.origin.clone(),
-					);
-				let ensured_origin = T::ScheduleOrigin::ensure_origin(scheduled_origin.into());
-
-				let r = match ensured_origin {
-					Ok(ScheduledEnsureOriginSuccess::Root) => {
-						Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))
-					}
-					Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {
-						// Execute transaction via chain default pipeline
-						// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken
-						T::CallExecutor::dispatch_call(Some(sender), call.clone())
-					}
-					Err(e) => Ok(Err(e.into())),
-				};
-
-				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;
-					let is_canceled;
-
-					// If scheduled is named, place its information in `Lookup`
-					if let Some(ref id) = s.maybe_id {
-						is_canceled = Lookup::<T>::get(id).is_none();
-						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);
-
-						if !is_canceled {
-							Lookup::<T>::insert(id, (wake, wake_index as u32));
-						}
-					} else {
-						is_canceled = false;
-					}
-
-					if !is_canceled {
-						Agenda::<T>::append(wake, Some(s));
-					}
-				} else if let Some(ref id) = s.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-			}
-			total_weight
-		}
-	}
-
-	#[pallet::call]
-	impl<T: Config> Pallet<T> {
-		/// Schedule a named task.
-		#[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: Option<schedule::Priority>,
-			call: Box<CallOrHashOf<T>>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule_named(
-				id,
-				DispatchTime::At(when),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				*call,
-			)?;
-			Ok(())
-		}
-
-		/// Cancel a named scheduled task.
-		#[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>::RuntimeOrigin::from(origin);
-			Self::do_cancel_named(Some(origin.caller().clone()), id)?;
-			Ok(())
-		}
-
-		/// Schedule a named task after a delay.
-		///
-		/// # <weight>
-		/// Same as [`schedule_named`](Self::schedule_named).
-		/// # </weight>
-		#[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: Option<schedule::Priority>,
-			call: Box<CallOrHashOf<T>>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule_named(
-				id,
-				DispatchTime::After(after),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				*call,
-			)?;
-			Ok(())
-		}
-
-		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]
-		pub fn change_named_priority(
-			origin: OriginFor<T>,
-			id: ScheduledId,
-			priority: schedule::Priority,
-		) -> DispatchResult {
-			T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_change_named_priority(origin.caller().clone(), id, priority)
-		}
-	}
-}
-
-impl<T: Config> Pallet<T> {
-	#[cfg(feature = "try-runtime")]
-	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {
-		Ok(())
-	}
-
-	#[cfg(feature = "try-runtime")]
-	pub fn post_migrate_to_v3() -> Result<(), &'static str> {
-		use frame_support::dispatch::GetStorageVersion;
-
-		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<_>>(),
-			)
-		});
-	}
-
-	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
-		let now = frame_system::Pallet::<T>::block_number();
-
-		let when = match when {
-			DispatchTime::At(x) => x,
-			// The current block has already completed it's scheduled tasks, so
-			// Schedule the task at lest one block after this current block.
-			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
-		};
-
-		if when <= now {
-			return Err(Error::<T>::TargetBlockNumberInPast.into());
-		}
-
-		Ok(when)
-	}
-
-	fn do_schedule_named(
-		id: ScheduledId,
-		when: DispatchTime<T::BlockNumber>,
-		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-		priority: schedule::Priority,
-		origin: T::PalletsOrigin,
-		call: CallOrHashOf<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		// ensure id it is unique
-		if Lookup::<T>::contains_key(&id) {
-			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())
-			// Remove one from the number of repetitions since we will schedule one now.
-			.map(|(p, c)| (p, c - 1));
-
-		let s = Scheduled {
-			maybe_id: Some(id.clone()),
-			priority,
-			call: call.clone(),
-			maybe_periodic,
-			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;
-		let address = (when, index);
-		Lookup::<T>::insert(&id, &address);
-		Self::deposit_event(Event::Scheduled { when, index });
-
-		Ok(address)
-	}
-
-	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.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(Event::Canceled { when, index });
-				Ok(())
-			} else {
-				Err(Error::<T>::NotFound)?
-			}
-		})
-	}
-
-	fn do_change_named_priority(
-		origin: T::PalletsOrigin,
-		id: ScheduledId,
-		priority: schedule::Priority,
-	) -> DispatchResult {
-		match Lookup::<T>::get(id) {
-			Some((when, index)) => {
-				let i = index as usize;
-				Agenda::<T>::try_mutate(when, |agenda| {
-					if let Some(Some(s)) = agenda.get_mut(i) {
-						if matches!(
-							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),
-							Some(Ordering::Less) | None
-						) {
-							return Err(BadOrigin.into());
-						}
-
-						s.priority = priority;
-						Self::deposit_event(Event::PriorityChanged {
-							when,
-							index,
-							priority,
-						});
-					}
-					Ok(())
-				})
-			}
-			None => Err(Error::<T>::NotFound.into()),
-		}
-	}
-}
deletedpallets/scheduler/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/weights.rs
+++ /dev/null
@@ -1,369 +0,0 @@
-// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
-
-//! Autogenerated weights for pallet_unique_scheduler
-//!
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-09-14, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
-//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
-
-// Executed Command:
-// target/release/unique-collator
-// benchmark
-// pallet
-// --pallet
-// pallet-unique-scheduler
-// --wasm-execution
-// compiled
-// --extrinsic
-// *
-// --template
-// .maintain/frame-weight-template.hbs
-// --steps=50
-// --repeat=80
-// --heap-pages=4096
-// --output=./pallets/scheduler/src/weights.rs
-
-#![cfg_attr(rustfmt, rustfmt_skip)]
-#![allow(unused_parens)]
-#![allow(unused_imports)]
-#![allow(missing_docs)]
-#![allow(clippy::unnecessary_cast)]
-
-use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
-use sp_std::marker::PhantomData;
-
-/// Weight functions needed for pallet_unique_scheduler.
-pub trait WeightInfo {
-	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
-	fn on_initialize_named_resolved(s: u32, ) -> Weight;
-	fn on_initialize_periodic(s: u32, ) -> Weight;
-	fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
-	fn on_initialize_aborted(s: u32, ) -> Weight;
-	fn on_initialize_named_aborted(s: u32, ) -> Weight;
-	fn on_initialize_named(s: u32, ) -> Weight;
-	fn on_initialize(s: u32, ) -> Weight;
-	fn on_initialize_resolved(s: u32, ) -> Weight;
-	fn schedule_named(s: u32, ) -> Weight;
-	fn cancel_named(s: u32, ) -> Weight;
-	fn change_named_priority(s: u32, ) -> Weight;
-}
-
-/// Weights for pallet_unique_scheduler using the Substrate node and recommended hardware.
-pub struct SubstrateWeight<T>(PhantomData<T>);
-impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(26_641_000)
-			// Standard Error: 9_000
-			.saturating_add(Weight::from_ref_time(8_547_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(23_941_000)
-			// Standard Error: 17_000
-			.saturating_add(Weight::from_ref_time(5_282_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_858_000)
-			// Standard Error: 7_000
-			.saturating_add(Weight::from_ref_time(8_657_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_515_000)
-			// Standard Error: 14_000
-			.saturating_add(Weight::from_ref_time(8_656_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_aborted(s: u32, ) -> Weight {
-		Weight::from_ref_time(7_584_000)
-			// Standard Error: 1_000
-			.saturating_add(Weight::from_ref_time(2_065_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_aborted(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_552_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_187_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_980_000)
-			// Standard Error: 12_000
-			.saturating_add(Weight::from_ref_time(2_050_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_482_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_249_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_187_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_216_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(4 as u64))
-			.saturating_add(T::DbWeight::get().writes(4 as u64))
-			.saturating_add(T::DbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn schedule_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(17_316_000)
-			// Standard Error: 3_000
-			.saturating_add(Weight::from_ref_time(82_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn cancel_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(15_652_000)
-			// Standard Error: 1_000
-			.saturating_add(Weight::from_ref_time(436_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn change_named_priority(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_642_000)
-			// Standard Error: 0
-			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-}
-
-// For backwards compatibility and tests
-impl WeightInfo for () {
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(26_641_000)
-			// Standard Error: 9_000
-			.saturating_add(Weight::from_ref_time(8_547_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(23_941_000)
-			// Standard Error: 17_000
-			.saturating_add(Weight::from_ref_time(5_282_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_858_000)
-			// Standard Error: 7_000
-			.saturating_add(Weight::from_ref_time(8_657_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:1 w:1)
-	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_515_000)
-			// Standard Error: 14_000
-			.saturating_add(Weight::from_ref_time(8_656_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().reads((1 as u64).saturating_mul(s as u64)))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((2 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_aborted(s: u32, ) -> Weight {
-		Weight::from_ref_time(7_584_000)
-			// Standard Error: 1_000
-			.saturating_add(Weight::from_ref_time(2_065_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_aborted(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_552_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_187_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_980_000)
-			// Standard Error: 12_000
-			.saturating_add(Weight::from_ref_time(2_050_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_482_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_249_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: System Account (r:1 w:1)
-	// Storage: System AllExtrinsicsLen (r:1 w:1)
-	// Storage: System BlockWeight (r:1 w:1)
-	// Storage: Configuration WeightToFeeCoefficientOverride (r:1 w:0)
-	// Storage: TransactionPayment NextFeeMultiplier (r:1 w:0)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_resolved(s: u32, ) -> Weight {
-		Weight::from_ref_time(25_187_000)
-			// Standard Error: 4_000
-			.saturating_add(Weight::from_ref_time(5_216_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes(4 as u64))
-			.saturating_add(RocksDbWeight::get().writes((1 as u64).saturating_mul(s as u64)))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn schedule_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(17_316_000)
-			// Standard Error: 3_000
-			.saturating_add(Weight::from_ref_time(82_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn cancel_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(15_652_000)
-			// Standard Error: 1_000
-			.saturating_add(Weight::from_ref_time(436_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn change_named_priority(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_642_000)
-			// Standard Error: 0
-			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-}
modifiedruntime/common/config/pallets/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -25,9 +25,9 @@
 use codec::Decode;
 use crate::{
 	runtime_common::{scheduler::SchedulerPaymentExecutor, config::substrate::RuntimeBlockWeights},
-	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller, Balances,
+	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller,
 };
-use pallet_unique_scheduler::ScheduledEnsureOriginSuccess;
+use pallet_unique_scheduler_v2::ScheduledEnsureOriginSuccess;
 use up_common::types::AccountId;
 
 parameter_types! {
@@ -70,19 +70,17 @@
 	}
 }
 
-impl pallet_unique_scheduler::Config for Runtime {
+impl pallet_unique_scheduler_v2::Config for Runtime {
 	type RuntimeEvent = RuntimeEvent;
 	type RuntimeOrigin = RuntimeOrigin;
-	type Currency = Balances;
 	type PalletsOrigin = OriginCaller;
 	type RuntimeCall = RuntimeCall;
 	type MaximumWeight = MaximumSchedulerWeight;
 	type ScheduleOrigin = EnsureSignedOrRoot<AccountId>;
-	type PrioritySetOrigin = EnsureRoot<AccountId>;
+	type OriginPrivilegeCmp = EqualOrRootOnly;
 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
 	type WeightInfo = ();
+	type Preimages = ();
 	type CallExecutor = SchedulerPaymentExecutor;
-	type OriginPrivilegeCmp = EqualOrRootOnly;
-	type PreimageProvider = ();
-	type NoPreimagePostponement = NoPreimagePostponement;
+	type PrioritySetOrigin = EnsureRoot<AccountId>;
 }
modifiedruntime/common/config/test_pallets.rsdiffbeforeafterboth
--- a/runtime/common/config/test_pallets.rs
+++ b/runtime/common/config/test_pallets.rs
@@ -14,8 +14,9 @@
 // You should have received a copy of the GNU General Public License
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
-use crate::{Runtime, RuntimeEvent};
+use crate::{Runtime, RuntimeEvent, RuntimeCall};
 
 impl pallet_test_utils::Config for Runtime {
 	type RuntimeEvent = RuntimeEvent;
+	type RuntimeCall = RuntimeCall;
 }
modifiedruntime/common/construct_runtime/mod.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -58,7 +58,7 @@
                 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
 
                 #[runtimes(opal)]
-                Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+                Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 62,
 
                 Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
 
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -683,8 +683,8 @@
                     #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
                     list_benchmark!(list, extra, pallet_refungible, Refungible);
 
-                    // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
-                    // list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);
+                    #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+                    list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);
 
                     #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
                     list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);
@@ -743,8 +743,8 @@
                     #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
                     add_benchmark!(params, batches, pallet_refungible, Refungible);
 
-                    // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
-                    // add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);
+                    #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+                    add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);
 
                     #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
                     add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);
modifiedruntime/common/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -15,44 +15,29 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 use frame_support::{
-	traits::NamedReservableCurrency,
 	dispatch::{GetDispatchInfo, PostDispatchInfo, DispatchInfo},
 };
 use sp_runtime::{
 	traits::{Dispatchable, Applyable, Member},
-	generic::Era,
 	transaction_validity::TransactionValidityError,
-	DispatchErrorWithPostInfo, DispatchError,
+	DispatchErrorWithPostInfo,
 };
 use codec::Encode;
-use crate::{Runtime, RuntimeCall, RuntimeOrigin, Balances, maintenance};
-use up_common::types::{AccountId, Balance};
+use crate::{Runtime, RuntimeCall, RuntimeOrigin, maintenance};
+use up_common::types::AccountId;
 use fp_self_contained::SelfContainedCall;
-use pallet_unique_scheduler::DispatchCall;
+use pallet_unique_scheduler_v2::DispatchCall;
 use pallet_transaction_payment::ChargeTransactionPayment;
 
-type SponsorshipChargeTransactionPayment =
-	pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
-
 /// The SignedExtension to the basic transaction logic.
 pub type SignedExtraScheduler = (
-	frame_system::CheckSpecVersion<Runtime>,
-	frame_system::CheckGenesis<Runtime>,
-	frame_system::CheckEra<Runtime>,
-	frame_system::CheckNonce<Runtime>,
 	frame_system::CheckWeight<Runtime>,
 	maintenance::CheckMaintenance,
 	ChargeTransactionPayment<Runtime>,
 );
 
-fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+fn get_signed_extras() -> 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(),
 		maintenance::CheckMaintenance,
 		ChargeTransactionPayment::<Runtime>::from(0),
@@ -61,7 +46,7 @@
 
 pub struct SchedulerPaymentExecutor;
 
-impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler_v2::Config, SelfContainedSignedInfo>
 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::RuntimeCall: Member
@@ -71,13 +56,13 @@
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
 	RuntimeCall: From<<T as frame_system::Config>::RuntimeCall>
-		+ From<<T as pallet_unique_scheduler::Config>::RuntimeCall>
+		+ From<<T as pallet_unique_scheduler_v2::Config>::RuntimeCall>
 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
 	fn dispatch_call(
 		signer: Option<<T as frame_system::Config>::AccountId>,
-		call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
+		call: <T as pallet_unique_scheduler_v2::Config>::RuntimeCall,
 	) -> Result<
 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
 		TransactionValidityError,
@@ -88,7 +73,7 @@
 		let signed = match signer {
 			Some(signer) => fp_self_contained::CheckedSignature::Signed(
 				signer.clone().into(),
-				get_signed_extras(signer.into()),
+				get_signed_extras(),
 			),
 			None => fp_self_contained::CheckedSignature::Unsigned,
 		};
@@ -104,53 +89,5 @@
 		};
 
 		extrinsic.apply::<Runtime>(&dispatch_info, len)
-	}
-
-	fn reserve_balance(
-		id: [u8; 16],
-		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
-		count: u32,
-	) -> Result<(), DispatchError> {
-		let dispatch_info = call.get_dispatch_info();
-		let weight: Balance =
-			SponsorshipChargeTransactionPayment::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_unique_scheduler::Config>::RuntimeCall,
-	) -> Result<u128, DispatchError> {
-		let dispatch_info = call.get_dispatch_info();
-		let weight: Balance =
-			SponsorshipChargeTransactionPayment::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,
-			),
-		)
 	}
 }
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -41,7 +41,7 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
     'pallet-app-promotion/runtime-benchmarks',
-    'pallet-unique-scheduler/runtime-benchmarks',
+    'pallet-unique-scheduler-v2/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -71,7 +71,6 @@
     'cumulus-pallet-dmp-queue/try-runtime',
     'pallet-inflation/try-runtime',
     'pallet-unique/try-runtime',
-    'pallet-unique-scheduler/try-runtime',
     'pallet-configuration/try-runtime',
     'pallet-charge-transaction/try-runtime',
     'pallet-common/try-runtime',
@@ -142,7 +141,7 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unique-scheduler/std',
+    'pallet-unique-scheduler-v2/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -474,8 +473,8 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
+pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
 pallet-evm-contract-helpers = { path = '../../pallets/evm-contract-helpers', default-features = false }
 pallet-evm-transaction-payment = { path = '../../pallets/evm-transaction-payment', default-features = false }
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -40,7 +40,6 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-foreign-assets/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
-    'pallet-unique-scheduler/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -70,7 +69,6 @@
     'cumulus-pallet-dmp-queue/try-runtime',
     'pallet-inflation/try-runtime',
     'pallet-unique/try-runtime',
-    'pallet-unique-scheduler/try-runtime',
     'pallet-configuration/try-runtime',
     'pallet-charge-transaction/try-runtime',
     'pallet-common/try-runtime',
@@ -139,7 +137,6 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unique-scheduler/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -475,7 +472,6 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -40,7 +40,6 @@
     'pallet-unique/runtime-benchmarks',
     'pallet-foreign-assets/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
-    'pallet-unique-scheduler/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -71,7 +70,6 @@
     'cumulus-pallet-dmp-queue/try-runtime',
     'pallet-inflation/try-runtime',
     'pallet-unique/try-runtime',
-    'pallet-unique-scheduler/try-runtime',
     'pallet-configuration/try-runtime',
     'pallet-charge-transaction/try-runtime',
     'pallet-common/try-runtime',
@@ -140,7 +138,6 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unique-scheduler/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -469,7 +466,6 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
modifiedtest-pallets/utils/Cargo.tomldiffbeforeafterboth
--- a/test-pallets/utils/Cargo.toml
+++ b/test-pallets/utils/Cargo.toml
@@ -10,7 +10,9 @@
 scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
 frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
 frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
+# pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
+pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
 
 [features]
 default = ["std"]
@@ -19,6 +21,7 @@
 	"scale-info/std",
 	"frame-support/std",
 	"frame-system/std",
-	"pallet-unique-scheduler/std",
+	"pallet-unique-scheduler-v2/std",
+	"sp-std/std",
 ]
-try-runtime = ["frame-support/try-runtime", "pallet-unique-scheduler/try-runtime"]
+try-runtime = ["frame-support/try-runtime", "pallet-unique-scheduler-v2/try-runtime"]
modifiedtest-pallets/utils/src/lib.rsdiffbeforeafterboth
--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -22,13 +22,29 @@
 
 #[frame_support::pallet]
 pub mod pallet {
-	use frame_support::pallet_prelude::*;
+	use frame_support::{
+		pallet_prelude::*,
+		dispatch::{Dispatchable, GetDispatchInfo, PostDispatchInfo},
+		traits::{UnfilteredDispatchable, IsSubType, OriginTrait},
+	};
 	use frame_system::pallet_prelude::*;
-	use pallet_unique_scheduler::{ScheduledId, Pallet as SchedulerPallet};
+	use sp_std::vec::Vec;
+	use pallet_unique_scheduler_v2::{TaskName, Pallet as SchedulerPallet};
 
 	#[pallet::config]
-	pub trait Config: frame_system::Config + pallet_unique_scheduler::Config {
+	pub trait Config: frame_system::Config + pallet_unique_scheduler_v2::Config {
 		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
+
+		/// The overarching call type.
+		type RuntimeCall: Parameter
+			+ Dispatchable<
+				RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin,
+				PostInfo = PostDispatchInfo,
+			> + GetDispatchInfo
+			+ From<frame_system::Call<Self>>
+			+ UnfilteredDispatchable<RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin>
+			+ IsSubType<Call<Self>>
+			+ IsType<<Self as frame_system::Config>::RuntimeCall>;
 	}
 
 	#[pallet::event]
@@ -36,6 +52,7 @@
 	pub enum Event<T: Config> {
 		ValueIsSet,
 		ShouldRollback,
+		BatchCompleted,
 	}
 
 	#[pallet::pallet]
@@ -94,14 +111,13 @@
 		#[pallet::weight(10_000)]
 		pub fn self_canceling_inc(
 			origin: OriginFor<T>,
-			id: ScheduledId,
+			id: TaskName,
 			max_test_value: u32,
 		) -> DispatchResult {
 			Self::ensure_origin_and_enabled(origin.clone())?;
+			Self::inc_test_value(origin.clone())?;
 
-			if <TestValue<T>>::get() < max_test_value {
-				Self::inc_test_value(origin)?;
-			} else {
+			if <TestValue<T>>::get() == max_test_value {
 				SchedulerPallet::<T>::cancel_named(origin, id)?;
 			}
 
@@ -113,6 +129,35 @@
 			Self::ensure_origin_and_enabled(origin)?;
 			Ok(())
 		}
+
+		#[pallet::weight(10_000)]
+		pub fn batch_all(
+			origin: OriginFor<T>,
+			calls: Vec<<T as Config>::RuntimeCall>,
+		) -> DispatchResultWithPostInfo {
+			Self::ensure_origin_and_enabled(origin.clone())?;
+
+			let is_root = ensure_root(origin.clone()).is_ok();
+
+			for call in calls {
+				if is_root {
+					call.dispatch_bypass_filter(origin.clone())?;
+				} else {
+					let mut filtered_origin = origin.clone();
+					// Don't allow users to nest `batch_all` calls.
+					filtered_origin.add_filter(
+						move |c: &<T as frame_system::Config>::RuntimeCall| {
+							let c = <T as Config>::RuntimeCall::from_ref(c);
+							!matches!(c.is_sub_type(), Some(Call::batch_all { .. }))
+						},
+					);
+					call.dispatch(filtered_origin)?;
+				}
+			}
+
+			Self::deposit_event(Event::BatchCompleted);
+			Ok(None::<Weight>.into())
+		}
 	}
 }
 
modifiedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- a/tests/src/eth/scheduling.test.ts
+++ b/tests/src/eth/scheduling.test.ts
@@ -15,7 +15,7 @@
 // along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
 
 import {expect} from 'chai';
-import {EthUniqueHelper, itEth} from './util';
+import {EthUniqueHelper, itSchedEth} from './util';
 import {Pallets, usingPlaygrounds} from '../util';
 
 describe('Scheduing EVM smart contracts', () => {
@@ -26,11 +26,11 @@
     });
   });
 
-  itEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async ({helper, privateKey}) => {
+  itSchedEth.ifWithPallets('Successfully schedules and periodically executes an EVM contract', [Pallets.Scheduler], async (scheduleKind, {helper, privateKey}) => {
     const donor = await privateKey({filename: __filename});
     const [alice] = await helper.arrange.createAccounts([1000n], donor);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
 
     const deployer = await helper.eth.createAccountWithBalance(alice);
     const flipper = await helper.eth.deployFlipper(deployer);
@@ -44,7 +44,7 @@
       repetitions: 2,
     };
 
-    await helper.scheduler.scheduleAfter<EthUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<EthUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .eth.sendEVM(
         alice,
         flipper.options.address,
modifiedtests/src/eth/util/index.tsdiffbeforeafterboth
--- a/tests/src/eth/util/index.ts
+++ b/tests/src/eth/util/index.ts
@@ -8,6 +8,7 @@
 
 import {EthUniqueHelper} from './playgrounds/unique.dev';
 import {SilentLogger, SilentConsole} from '../../util/playgrounds/unique.dev';
+import {SchedKind} from '../../util';
 
 export {EthUniqueHelper} from './playgrounds/unique.dev';
 
@@ -81,3 +82,19 @@
 itEthIfWithPallet.only = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {only: true});
 itEthIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itEthIfWithPallet(name, required, cb, {skip: true});
 itEth.ifWithPallets = itEthIfWithPallet;
+
+export function itSchedEth(
+  name: string,
+  cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any,
+  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+  itEth(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+  itEth(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSchedEth.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {only: true});
+itSchedEth.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any) => itSchedEth(name, cb, {skip: true});
+itSchedEth.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: EthUniqueHelper, privateKey: (seed: string | {filename: string}) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itSchedEth(name, cb, {requiredPallets: required, ...opts});
+}
modifiedtests/src/maintenanceMode.seqtest.tsdiffbeforeafterboth
--- a/tests/src/maintenanceMode.seqtest.ts
+++ b/tests/src/maintenanceMode.seqtest.ts
@@ -16,7 +16,7 @@
 
 import {IKeyringPair} from '@polkadot/types/types';
 import {ApiPromise} from '@polkadot/api';
-import {expect, itSub, Pallets, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, usingPlaygrounds} from './util';
 import {itEth} from './eth/util';
 
 async function maintenanceEnabled(api: ApiPromise): Promise<boolean> {
@@ -162,34 +162,38 @@
     await expect(helper.balance.transferToSubstrate(bob, superuser.address, 1n)).to.be.fulfilled;
   });
 
-  itSub.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async ({helper}) => {
+  itSched.ifWithPallets('MM blocks scheduled calls and the scheduler itself', [Pallets.Scheduler], async (scheduleKind, {helper}) => {
     const collection = await helper.nft.mintCollection(bob);
 
     const nftBeforeMM = await collection.mintToken(bob);
     const nftDuringMM = await collection.mintToken(bob);
     const nftAfterMM = await collection.mintToken(bob);
 
-    const scheduledIdBeforeMM = '0x' + '0'.repeat(31) + '0';
-    const scheduledIdDuringMM = '0x' + '0'.repeat(31) + '1';
-    const scheduledIdBunkerThroughMM = '0x' + '0'.repeat(31) + '2';
-    const scheduledIdAttemptDuringMM = '0x' + '0'.repeat(31) + '3';
-    const scheduledIdAfterMM = '0x' + '0'.repeat(31) + '4';
+    const [
+      scheduledIdBeforeMM,
+      scheduledIdDuringMM,
+      scheduledIdBunkerThroughMM,
+      scheduledIdAttemptDuringMM,
+      scheduledIdAfterMM,
+    ] = scheduleKind == 'named'
+      ? helper.arrange.makeScheduledIds(5)
+      : new Array(5);
 
     const blocksToWait = 6;
 
     // Scheduling works before the maintenance
-    await nftBeforeMM.scheduleAfter(scheduledIdBeforeMM, blocksToWait)
+    await nftBeforeMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdBeforeMM})
       .transfer(bob, {Substrate: superuser.address});
 
     await helper.wait.newBlocks(blocksToWait + 1);
     expect(await nftBeforeMM.getOwner()).to.be.deep.equal({Substrate: superuser.address});
 
     // Schedule a transaction that should occur *during* the maintenance
-    await nftDuringMM.scheduleAfter(scheduledIdDuringMM, blocksToWait)
+    await nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdDuringMM})
       .transfer(bob, {Substrate: superuser.address});
     
     // Schedule a transaction that should occur *after* the maintenance
-    await nftDuringMM.scheduleAfter(scheduledIdBunkerThroughMM, blocksToWait * 2)
+    await nftDuringMM.scheduleAfter(blocksToWait * 2, {scheduledId: scheduledIdBunkerThroughMM})
       .transfer(bob, {Substrate: superuser.address});
 
     await helper.getSudo().executeExtrinsic(superuser, 'api.tx.maintenance.enable', []);
@@ -200,7 +204,7 @@
     expect(await nftDuringMM.getOwner()).to.be.deep.equal({Substrate: bob.address});
 
     // Any attempts to schedule a tx during the MM should be rejected
-    await expect(nftDuringMM.scheduleAfter(scheduledIdAttemptDuringMM, blocksToWait)
+    await expect(nftDuringMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAttemptDuringMM})
       .transfer(bob, {Substrate: superuser.address}))
       .to.be.rejectedWith(/Invalid Transaction: Transaction call is not expected/);
 
@@ -208,7 +212,7 @@
     expect(await maintenanceEnabled(helper.getApi()), 'MM is ON when it should be OFF').to.be.false;
 
     // Scheduling works after the maintenance
-    await nftAfterMM.scheduleAfter(scheduledIdAfterMM, blocksToWait)
+    await nftAfterMM.scheduleAfter(blocksToWait, {scheduledId: scheduledIdAfterMM})
       .transfer(bob, {Substrate: superuser.address});
     
     await helper.wait.newBlocks(blocksToWait + 1);
modifiedtests/src/scheduler.seqtest.tsdiffbeforeafterboth
--- a/tests/src/scheduler.seqtest.ts
+++ b/tests/src/scheduler.seqtest.ts
@@ -14,43 +14,53 @@
 // 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, itSub, Pallets, usingPlaygrounds} from './util';
+import {expect, itSched, itSub, Pallets, requirePalletsOrSkip, usingPlaygrounds} from './util';
 import {IKeyringPair} from '@polkadot/types/types';
 import {DevUniqueHelper} from './util/playgrounds/unique.dev';
 
 describe('Scheduling token and balance transfers', () => {
+  let superuser: IKeyringPair;
   let alice: IKeyringPair;
   let bob: IKeyringPair;
   let charlie: IKeyringPair;
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKeyWrapper) => {
-      alice = await privateKeyWrapper('//Alice');
-      bob = await privateKeyWrapper('//Bob');
-      charlie = await privateKeyWrapper('//Charlie');
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.Scheduler]);
 
+      superuser = await privateKey('//Alice');
+      const donor = await privateKey({filename: __filename});
+      [alice, bob, charlie] = await helper.arrange.createAccounts([100n, 100n, 100n], donor);
+
       await helper.testUtils.enable();
     });
   });
 
-  itSub.ifWithPallets('Can delay a transfer of an owned token', [Pallets.Scheduler], async ({helper}) => {
+  beforeEach(async () => {
+    await usingPlaygrounds(async (helper) => {
+      await helper.wait.noScheduledTasks();
+    });
+  });
+
+  itSched('Can delay a transfer of an owned token', async (scheduleKind, {helper}) => {
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
-    const schedulerId = await helper.arrange.makeScheduledId();
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const blocksBeforeExecution = 4;
-
-    await token.scheduleAfter(schedulerId, blocksBeforeExecution)
+    
+    await token.scheduleAfter(blocksBeforeExecution, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
 
-    await helper.wait.newBlocks(blocksBeforeExecution + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub.ifWithPallets('Can transfer funds periodically', [Pallets.Scheduler], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('Can transfer funds periodically', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 1;
 
     const amount = 1n * helper.balance.getOneTokenNominal();
@@ -61,10 +71,11 @@
 
     const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
       .balance.transferToSubstrate(alice, bob.address, amount);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
     expect(bobsBalanceAfterFirst)
@@ -73,7 +84,7 @@
         '#1 Balance of the recipient should be increased by 1 * amount',
       );
 
-    await helper.wait.newBlocks(periodic.period);
+    await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
 
     const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
     expect(bobsBalanceAfterSecond)
@@ -83,42 +94,44 @@
       );
   });
 
-  itSub.ifWithPallets('Can cancel a scheduled operation which has not yet taken effect', [Pallets.Scheduler], async ({helper}) => {
+  itSub('Can cancel a scheduled operation which has not yet taken effect', async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
     await helper.scheduler.cancelScheduled(alice, scheduledId);
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: alice.address});
   });
 
-  itSub.ifWithPallets('Can cancel a periodic operation (transfer of funds)', [Pallets.Scheduler], async ({helper}) => {
+  itSub('Can cancel a periodic operation (transfer of funds)', async ({helper}) => {
     const waitForBlocks = 1;
     const periodic = {
       period: 3,
       repetitions: 2,
     };
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
 
     const amount = 1n * helper.balance.getOneTokenNominal();
 
     const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    await helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, periodic})
       .balance.transferToSubstrate(alice, bob.address, amount);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const bobsBalanceAfterFirst = await helper.balance.getSubstrate(bob.address);
 
@@ -129,7 +142,7 @@
       );
 
     await helper.scheduler.cancelScheduled(alice, scheduledId);
-    await helper.wait.newBlocks(periodic.period);
+    await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
 
     const bobsBalanceAfterSecond = await helper.balance.getSubstrate(bob.address);
     expect(bobsBalanceAfterSecond)
@@ -139,8 +152,54 @@
       );
   });
 
-  itSub.ifWithPallets('Scheduled tasks are transactional', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('scheduler will not insert more tasks than allowed', async (scheduleKind, {helper}) => {
+    const maxScheduledPerBlock = 50;
+    let fillScheduledIds = new Array(maxScheduledPerBlock);
+    let extraScheduledId = undefined;
+    
+    if (scheduleKind == 'named') {
+      const scheduledIds = helper.arrange.makeScheduledIds(maxScheduledPerBlock + 1);
+      fillScheduledIds = scheduledIds.slice(0, maxScheduledPerBlock);
+      extraScheduledId = scheduledIds[maxScheduledPerBlock];
+    }
+
+    // Since the dev node has Instant Seal,
+    // we need a larger gap between the current block and the target one.
+    //
+    // We will schedule `maxScheduledPerBlock` transaction into the target block,
+    // so we need at least `maxScheduledPerBlock`-wide gap.
+    // We add some additional blocks to this gap to mitigate possible PolkadotJS delays.
+    const waitForBlocks = await helper.arrange.isDevNode() ? maxScheduledPerBlock + 5 : 5;
+
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks;
+
+    const amount = 1n * helper.balance.getOneTokenNominal();
+
+    const balanceBefore = await helper.balance.getSubstrate(bob.address);
+
+    // Fill the target block
+    for (let i = 0; i < maxScheduledPerBlock; i++) {
+      await helper.scheduler.scheduleAt(executionBlock, {scheduledId: fillScheduledIds[i]})
+        .balance.transferToSubstrate(superuser, bob.address, amount);
+    }
+
+    // Try to schedule a task into a full block
+    await expect(helper.scheduler.scheduleAt(executionBlock, {scheduledId: extraScheduledId})
+      .balance.transferToSubstrate(superuser, bob.address, amount))
+      .to.be.rejectedWith(/scheduler\.AgendaIsExhausted/);
+
+    await helper.wait.forParachainBlockNumber(executionBlock);
+
+    const balanceAfter = await helper.balance.getSubstrate(bob.address);
+
+    expect(balanceAfter > balanceBefore).to.be.true;
+
+    const diff = balanceAfter - balanceBefore;
+    expect(diff).to.be.equal(amount * BigInt(maxScheduledPerBlock));
+  });
+
+  itSched.ifWithPallets('Scheduled tasks are transactional', [Pallets.TestUtils], async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const initTestVal = 42;
@@ -148,18 +207,19 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks)
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId})
       .testUtils.setTestValueAndRollback(alice, changedTestVal);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const testVal = await helper.testUtils.testValue();
     expect(testVal, 'The test value should NOT be commited')
       .to.be.equal(initTestVal);
   });
 
-  itSub.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.Scheduler, Pallets.TestUtils], async function({helper}) {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched.ifWithPallets('Scheduled tasks should take correct fees', [Pallets.TestUtils], async function(scheduleKind, {helper}) {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
     const periodic = {
       period: 2,
@@ -172,15 +232,14 @@
     const expectedScheduledFee = (await helper.getPaymentInfo(alice, dummyTx, scheduledLen))
       .partialFee.toBigInt();
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .testUtils.justTakeFee(alice);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(1);
-
     const aliceInitBalance = await helper.balance.getSubstrate(alice.address);
     let diff;
 
-    await helper.wait.newBlocks(waitForBlocks);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const aliceBalanceAfterFirst = await helper.balance.getSubstrate(alice.address);
     expect(
@@ -194,7 +253,7 @@
       'Scheduled task should take the right amount of fees',
     );
 
-    await helper.wait.newBlocks(periodic.period);
+    await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
 
     const aliceBalanceAfterSecond = await helper.balance.getSubstrate(alice.address);
     expect(
@@ -211,7 +270,7 @@
 
   // Check if we can cancel a scheduled periodic operation
   // in the same block in which it is running
-  itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
+  itSub.ifWithPallets('Can cancel the periodic sheduled tx when the tx is running', [Pallets.TestUtils], async ({helper}) => {
     const currentBlockNumber = await helper.chain.getLatestBlockNumber();
     const blocksBeforeExecution = 10;
     const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
@@ -219,7 +278,7 @@
     const [
       scheduledId,
       scheduledCancelId,
-    ] = await helper.arrange.makeScheduledIds(2);
+    ] = helper.arrange.makeScheduledIds(2);
 
     const periodic = {
       period: 5,
@@ -232,14 +291,14 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAt<DevUniqueHelper>(scheduledId, firstExecutionBlockNumber, {periodic})
+    await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {scheduledId, periodic})
       .testUtils.incTestValue(alice);
 
     // Cancel the inc tx after 2 executions
     // *in the same block* in which the second execution is scheduled
     await helper.scheduler.scheduleAt(
-      scheduledCancelId,
       firstExecutionBlockNumber + periodic.period,
+      {scheduledId: scheduledCancelId},
     ).scheduler.cancelScheduled(alice, scheduledId);
 
     await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
@@ -261,8 +320,8 @@
     }
   });
 
-  itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.Scheduler, Pallets.TestUtils], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSub.ifWithPallets('A scheduled operation can cancel itself', [Pallets.TestUtils], async ({helper}) => {
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
     const periodic = {
       period: 2,
@@ -274,47 +333,49 @@
 
     await helper.testUtils.setTestValue(alice, initTestVal);
 
-    await helper.scheduler.scheduleAfter<DevUniqueHelper>(scheduledId, waitForBlocks, {periodic})
+    await helper.scheduler.scheduleAfter<DevUniqueHelper>(waitForBlocks, {scheduledId, periodic})
       .testUtils.selfCancelingInc(alice, scheduledId, maxTestVal);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     // execution #0
     expect(await helper.testUtils.testValue())
       .to.be.equal(initTestVal + 1);
 
-    await helper.wait.newBlocks(periodic.period);
+    await helper.wait.forParachainBlockNumber(executionBlock + periodic.period);
 
     // execution #1
     expect(await helper.testUtils.testValue())
       .to.be.equal(initTestVal + 2);
 
-    await helper.wait.newBlocks(periodic.period);
+    await helper.wait.forParachainBlockNumber(executionBlock + 2 * periodic.period);
 
     // <canceled>
     expect(await helper.testUtils.testValue())
       .to.be.equal(initTestVal + 2);
   });
 
-  itSub.ifWithPallets('Root can cancel any scheduled operation', [Pallets.Scheduler], async ({helper}) => {
+  itSub('Root can cancel any scheduled operation', async ({helper}) => {
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.getSudo().scheduler.cancelScheduled(alice, scheduledId);
+    await helper.getSudo().scheduler.cancelScheduled(superuser, scheduledId);
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub.ifWithPallets('Root can set prioritized scheduled operation', [Pallets.Scheduler], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched('Root can set prioritized scheduled operation', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const amount = 42n * helper.balance.getOneTokenNominal();
@@ -322,10 +383,11 @@
     const balanceBefore = await helper.balance.getSubstrate(charlie.address);
 
     await helper.getSudo()
-      .scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42})
-      .balance.forceTransferToSubstrate(alice, bob.address, charlie.address, amount);
+      .scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42})
+      .balance.forceTransferToSubstrate(superuser, bob.address, charlie.address, amount);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const balanceAfter = await helper.balance.getSubstrate(charlie.address);
 
@@ -335,18 +397,19 @@
     expect(diff).to.be.equal(amount);
   });
 
-  itSub.ifWithPallets("Root can change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+  itSub("Root can change scheduled operation's priority", async ({helper}) => {
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 6;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
     const priority = 112;
-    await helper.getSudo().scheduler.changePriority(alice, scheduledId, priority);
+    await helper.getSudo().scheduler.changePriority(superuser, scheduledId, priority);
 
     const priorityChanged = await helper.wait.event(
       waitForBlocks,
@@ -355,14 +418,19 @@
     );
 
     expect(priorityChanged !== null).to.be.true;
-    expect(priorityChanged!.event.data[2].toString()).to.be.equal(priority.toString());
+
+    const [blockNumber, index] = priorityChanged!.event.data[0].toJSON() as any[];
+    expect(blockNumber).to.be.equal(executionBlock);
+    expect(index).to.be.equal(0);
+
+    expect(priorityChanged!.event.data[1].toString()).to.be.equal(priority.toString());
   });
 
-  itSub.ifWithPallets('Prioritized operations executes in valid order', [Pallets.Scheduler], async ({helper}) => {
+  itSub('Prioritized operations execute in valid order', async ({helper}) => {
     const [
       scheduledFirstId,
       scheduledSecondId,
-    ] = await helper.arrange.makeScheduledIds(2);
+    ] = helper.arrange.makeScheduledIds(2);
 
     const currentBlockNumber = await helper.chain.getLatestBlockNumber();
     const blocksBeforeExecution = 6;
@@ -379,19 +447,25 @@
     const amount = 1n * helper.balance.getOneTokenNominal();
 
     // Scheduler a task with a lower priority first, then with a higher priority
-    await helper.getSudo().scheduler.scheduleAt(scheduledFirstId, firstExecutionBlockNumber, {priority: prioLow, periodic})
-      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+    await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+      scheduledId: scheduledFirstId,
+      priority: prioLow,
+      periodic,
+    }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
 
-    await helper.getSudo().scheduler.scheduleAt(scheduledSecondId, firstExecutionBlockNumber, {priority: prioHigh, periodic})
-      .balance.forceTransferToSubstrate(alice, alice.address, bob.address, amount);
+    await helper.getSudo().scheduler.scheduleAt(firstExecutionBlockNumber, {
+      scheduledId: scheduledSecondId,
+      priority: prioHigh,
+      periodic,
+    }).balance.forceTransferToSubstrate(superuser, alice.address, bob.address, amount);
 
     const capture = await helper.arrange.captureEvents('scheduler', 'Dispatched');
 
     await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
 
     // Flip priorities
-    await helper.getSudo().scheduler.changePriority(alice, scheduledFirstId, prioHigh);
-    await helper.getSudo().scheduler.changePriority(alice, scheduledSecondId, prioLow);
+    await helper.getSudo().scheduler.changePriority(superuser, scheduledFirstId, prioHigh);
+    await helper.getSudo().scheduler.changePriority(superuser, scheduledSecondId, prioLow);
 
     await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + periodic.period);
 
@@ -409,38 +483,123 @@
     expect(secondExecuctionIds[0]).to.be.equal(scheduledFirstId);
     expect(secondExecuctionIds[1]).to.be.equal(scheduledSecondId);
   });
+
+  itSched('Periodic operations always can be rescheduled', async (scheduleKind, {helper}) => {
+    const maxScheduledPerBlock = 50;
+    const numFilledBlocks = 3;
+    const ids = helper.arrange.makeScheduledIds(numFilledBlocks * maxScheduledPerBlock + 1);
+    const periodicId = scheduleKind == 'named' ? ids[0] : undefined;
+    const fillIds = ids.slice(1);
+
+    const fillScheduleFn = scheduleKind == 'named' ? 'scheduleNamed' : 'schedule';
+
+    const initTestVal = 0;
+    const firstExecTestVal = 1;
+    const secondExecTestVal = 2;
+    await helper.testUtils.setTestValue(alice, initTestVal);
+
+    const currentBlockNumber = await helper.chain.getLatestBlockNumber();
+    const blocksBeforeExecution = 8;
+    const firstExecutionBlockNumber = currentBlockNumber + blocksBeforeExecution;
+
+    const period = 5;
+
+    const periodic = {
+      period,
+      repetitions: 2,
+    };
+
+    // Fill `numFilledBlocks` blocks beginning from the block in which the second execution should occur
+    const txs = [];
+    for (let offset = 0; offset < numFilledBlocks; offset ++) {
+      for (let i = 0; i < maxScheduledPerBlock; i++) {
+
+        const scheduledTx = helper.constructApiCall('api.tx.balances.transfer', [bob.address, 1n]);
+
+        const when = firstExecutionBlockNumber + period + offset;
+        const mandatoryArgs = [when, null, null, scheduledTx];
+        const scheduleArgs = scheduleKind == 'named'
+          ? [fillIds[i + offset * maxScheduledPerBlock], ...mandatoryArgs]
+          : mandatoryArgs;
+
+        const tx = helper.constructApiCall(`api.tx.scheduler.${fillScheduleFn}`, scheduleArgs);
+
+        txs.push(tx);
+      }
+    }
+    await helper.executeExtrinsic(alice, 'api.tx.testUtils.batchAll', [txs], true);
+
+    await helper.scheduler.scheduleAt<DevUniqueHelper>(firstExecutionBlockNumber, {
+      scheduledId: periodicId,
+      periodic,
+    }).testUtils.incTestValue(alice);
+
+    await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber);
+    expect(await helper.testUtils.testValue()).to.be.equal(firstExecTestVal);
+
+    await helper.wait.forParachainBlockNumber(firstExecutionBlockNumber + period + numFilledBlocks);
+
+    // The periodic operation should be postponed by `numFilledBlocks`
+    for (let i = 0; i < numFilledBlocks; i++) {
+      expect(await helper.testUtils.testValue(firstExecutionBlockNumber + period + i)).to.be.equal(firstExecTestVal);
+    }
+
+    // After the `numFilledBlocks` the periodic operation will eventually be executed
+    expect(await helper.testUtils.testValue()).to.be.equal(secondExecTestVal);
+  });
+
+  itSched('scheduled operations does not change nonce', async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
+    const blocksBeforeExecution = 4;
+
+    await helper.scheduler
+      .scheduleAfter<DevUniqueHelper>(blocksBeforeExecution, {scheduledId})
+      .balance.transferToSubstrate(alice, bob.address, 1n);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + blocksBeforeExecution + 1;
+
+    const initNonce = await helper.chain.getNonce(alice.address);
+
+    await helper.wait.forParachainBlockNumber(executionBlock);
+
+    const finalNonce = await helper.chain.getNonce(alice.address);
+
+    expect(initNonce).to.be.equal(finalNonce);
+  });
 });
 
 describe('Negative Test: Scheduling', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
 
-  before(async () => {
-    await usingPlaygrounds(async (helper, privateKeyWrapper) => {
-      alice = await privateKeyWrapper('//Alice');
-      bob = await privateKeyWrapper('//Bob');
+  before(async function() {
+    await usingPlaygrounds(async (helper, privateKey) => {
+      requirePalletsOrSkip(this, helper, [Pallets.Scheduler]);
+
+      const donor = await privateKey({filename: __filename});
+      [alice, bob] = await helper.arrange.createAccounts([100n, 100n], donor);
 
       await helper.testUtils.enable();
     });
   });
 
-  itSub.ifWithPallets("Can't overwrite a scheduled ID", [Pallets.Scheduler], async ({helper}) => {
+  itSub("Can't overwrite a scheduled ID", async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
-    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks);
+    const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId});
     await expect(scheduled.balance.transferToSubstrate(alice, bob.address, 1n * helper.balance.getOneTokenNominal()))
       .to.be.rejectedWith(/scheduler\.FailedToSchedule/);
 
     const bobsBalanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const bobsBalanceAfter = await helper.balance.getSubstrate(bob.address);
 
@@ -448,58 +607,61 @@
     expect(bobsBalanceBefore).to.be.equal(bobsBalanceAfter);
   });
 
-  itSub.ifWithPallets("Can't cancel an operation which is not scheduled", [Pallets.Scheduler], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSub("Can't cancel an operation which is not scheduled", async ({helper}) => {
+    const scheduledId = helper.arrange.makeScheduledId();
     await expect(helper.scheduler.cancelScheduled(alice, scheduledId))
       .to.be.rejectedWith(/scheduler\.NotFound/);
   });
 
-  itSub.ifWithPallets("Can't cancel a non-owned scheduled operation", [Pallets.Scheduler], async ({helper}) => {
+  itSub("Can't cancel a non-owned scheduled operation", async ({helper}) => {
     const collection = await helper.nft.mintCollection(alice, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(alice);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(alice, {Substrate: bob.address});
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
 
     await expect(helper.scheduler.cancelScheduled(bob, scheduledId))
       .to.be.rejectedWith(/BadOrigin/);
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     expect(await token.getOwner()).to.be.deep.equal({Substrate: bob.address});
   });
 
-  itSub.ifWithPallets("Regular user can't set prioritized scheduled operation", [Pallets.Scheduler], async ({helper}) => {
-    const scheduledId = await helper.arrange.makeScheduledId();
+  itSched("Regular user can't set prioritized scheduled operation", async (scheduleKind, {helper}) => {
+    const scheduledId = scheduleKind == 'named' ? helper.arrange.makeScheduledId() : undefined;
     const waitForBlocks = 4;
 
     const amount = 42n * helper.balance.getOneTokenNominal();
 
     const balanceBefore = await helper.balance.getSubstrate(bob.address);
 
-    const scheduled = helper.scheduler.scheduleAfter(scheduledId, waitForBlocks, {priority: 42});
+    const scheduled = helper.scheduler.scheduleAfter(waitForBlocks, {scheduledId, priority: 42});
     
     await expect(scheduled.balance.transferToSubstrate(alice, bob.address, amount))
       .to.be.rejectedWith(/BadOrigin/);
 
-    await helper.wait.newBlocks(waitForBlocks + 1);
+    const executionBlock = await helper.chain.getLatestBlockNumber() + waitForBlocks + 1;
+
+    await helper.wait.forParachainBlockNumber(executionBlock);
 
     const balanceAfter = await helper.balance.getSubstrate(bob.address);
 
     expect(balanceAfter).to.be.equal(balanceBefore);
   });
 
-  itSub.ifWithPallets("Regular user can't change scheduled operation's priority", [Pallets.Scheduler], async ({helper}) => {
+  itSub("Regular user can't change scheduled operation's priority", async ({helper}) => {
     const collection = await helper.nft.mintCollection(bob, {tokenPrefix: 'schd'});
     const token = await collection.mintToken(bob);
 
-    const scheduledId = await helper.arrange.makeScheduledId();
+    const scheduledId = helper.arrange.makeScheduledId();
     const waitForBlocks = 4;
 
-    await token.scheduleAfter(scheduledId, waitForBlocks)
+    await token.scheduleAfter(waitForBlocks, {scheduledId})
       .transfer(bob, {Substrate: alice.address});
 
     const priority = 112;
@@ -522,9 +684,9 @@
   // let bob: IKeyringPair;
 
   // before(async() => {
-  //   await usingApi(async (_, privateKeyWrapper) => {
-  //     alice = privateKeyWrapper('//Alice');
-  //     bob = privateKeyWrapper('//Bob');
+  //   await usingApi(async (_, privateKey) => {
+  //     alice = privateKey('//Alice');
+  //     bob = privateKey('//Bob');
   //   });
   // });
 
@@ -550,9 +712,9 @@
   });
 
   it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
-    // await usingApi(async (api, privateKeyWrapper) => {
+    // await usingApi(async (api, privateKey) => {
     //   // Find an empty, unused account
-    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+    //   const zeroBalance = await findUnusedAddress(api, privateKey);
 
     //   const collectionId = await createCollectionExpectSuccess();
 
@@ -591,8 +753,8 @@
   it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
     // const collectionId = await createCollectionExpectSuccess();
 
-    // await usingApi(async (api, privateKeyWrapper) => {
-    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+    // await usingApi(async (api, privateKey) => {
+    //   const zeroBalance = await findUnusedAddress(api, privateKey);
     //   const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
     //   await submitTransactionAsync(alice, balanceTx);
 
@@ -622,8 +784,8 @@
     // await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     // await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
-    // await usingApi(async (api, privateKeyWrapper) => {
-    //   const zeroBalance = await findUnusedAddress(api, privateKeyWrapper);
+    // await usingApi(async (api, privateKey) => {
+    //   const zeroBalance = await findUnusedAddress(api, privateKey);
 
     //   await enablePublicMintingExpectSuccess(alice, collectionId);
     //   await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
modifiedtests/src/util/index.tsdiffbeforeafterboth
--- a/tests/src/util/index.ts
+++ b/tests/src/util/index.ts
@@ -130,6 +130,24 @@
 itSubIfWithPallet.skip = (name: string, required: string[], cb: (apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSubIfWithPallet(name, required, cb, {skip: true});
 itSub.ifWithPallets = itSubIfWithPallet;
 
+export type SchedKind = 'anon' | 'named';
+
+export function itSched(
+  name: string,
+  cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any,
+  opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {},
+) {
+  itSub(name + ' (anonymous scheduling)', (apis) => cb('anon', apis), opts);
+  itSub(name + ' (named scheduling)', (apis) => cb('named', apis), opts);
+}
+itSched.only = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {only: true});
+itSched.skip = (name: string, cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any) => itSched(name, cb, {skip: true});
+itSched.ifWithPallets = itSchedIfWithPallets;
+
+function itSchedIfWithPallets(name: string, required: string[], cb: (schedKind: SchedKind, apis: { helper: DevUniqueHelper, privateKey: (seed: string) => Promise<IKeyringPair> }) => any, opts: { only?: boolean, skip?: boolean, requiredPallets?: string[] } = {}) {
+  return itSched(name, cb, {requiredPallets: required, ...opts});
+}
+
 export function describeXCM(title: string, fn: (this: Mocha.Suite) => void, opts: {skip?: boolean} = {}) {
   (process.env.RUN_XCM_TESTS && !opts.skip
     ? describe
modifiedtests/src/util/playgrounds/types.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/types.ts
+++ b/tests/src/util/playgrounds/types.ts
@@ -172,6 +172,7 @@
 }
 
 export interface ISchedulerOptions {
+  scheduledId?: string,
   priority?: number,
   periodic?: {
     period: number,
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -308,11 +308,9 @@
     return encodeAddress(address);
   }
 
-  async makeScheduledIds(num: number): Promise<string[]> {
-    await this.helper.wait.noScheduledTasks();
-
+  makeScheduledIds(num: number): string[] {
     function makeId(slider: number) {
-      const scheduledIdSize = 32;
+      const scheduledIdSize = 64;
       const hexId = slider.toString(16);
       const prefixSize = scheduledIdSize - hexId.length;
 
@@ -330,8 +328,8 @@
     return ids;
   }
 
-  async makeScheduledId(): Promise<string> {
-    return (await this.makeScheduledIds(1))[0];
+  makeScheduledId(): string {
+    return (this.makeScheduledIds(1))[0];
   }
 
   async captureEvents(eventSection: string, eventMethod: string): Promise<EventCapture> {
@@ -537,8 +535,12 @@
     await this.helper.executeExtrinsic(signer, 'api.tx.testUtils.setTestValueAndRollback', [testVal], true);
   }
 
-  async testValue() {
-    return (await this.helper.callRpc('api.query.testUtils.testValue', [])).toNumber();
+  async testValue(blockIdx?: number) {
+    const api = blockIdx
+      ? await this.helper.getApi().at(await this.helper.callRpc('api.rpc.chain.getBlockHash', [blockIdx]))
+      : this.helper.getApi();
+
+    return (await api.query.testUtils.testValue()).toJSON();
   }
 
   async justTakeFee(signer: TSigner) {
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2560,24 +2560,21 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    return this.schedule<T>('scheduleNamed', scheduledId, executionBlockNumber, options);
+    return this.schedule<T>('schedule', executionBlockNumber, options);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    return this.schedule<T>('scheduleNamedAfter', scheduledId, blocksBeforeExecution, options);
+    return this.schedule<T>('scheduleAfter', blocksBeforeExecution, options);
   }
 
   schedule<T extends UniqueHelper>(
-    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
-    scheduledId: string,
+    scheduleFn: 'schedule' | 'scheduleAfter',
     blocksNum: number,
     options: ISchedulerOptions = {},
   ) {
@@ -2585,7 +2582,6 @@
     const ScheduledHelperType = ScheduledUniqueHelper(this.helper.helperBase);
     return this.helper.clone(ScheduledHelperType, {
       scheduleFn,
-      scheduledId,
       blocksNum,
       options,
     }) as T;
@@ -2874,16 +2870,14 @@
 // eslint-disable-next-line @typescript-eslint/naming-convention
 function ScheduledUniqueHelper<T extends UniqueHelperConstructor>(Base: T) {
   return class extends Base {
-    scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter';
-    scheduledId: string;
+    scheduleFn: 'schedule' | 'scheduleAfter';
     blocksNum: number;
     options: ISchedulerOptions;
 
     constructor(...args: any[]) {
       const logger = args[0] as ILogger;
       const options = args[1] as {
-        scheduleFn: 'scheduleNamed' | 'scheduleNamedAfter',
-        scheduledId: string,
+        scheduleFn: 'schedule' | 'scheduleAfter',
         blocksNum: number,
         options: ISchedulerOptions
       };
@@ -2891,25 +2885,42 @@
       super(logger);
 
       this.scheduleFn = options.scheduleFn;
-      this.scheduledId = options.scheduledId;
       this.blocksNum = options.blocksNum;
       this.options = options.options;
     }
 
     executeExtrinsic(sender: IKeyringPair, scheduledExtrinsic: string, scheduledParams: any[], expectSuccess?: boolean): Promise<ITransactionResult> {
       const scheduledTx = this.constructApiCall(scheduledExtrinsic, scheduledParams);
-      const extrinsic = 'api.tx.scheduler.' +  this.scheduleFn;
+      
+      const mandatorySchedArgs = [
+        this.blocksNum,
+        this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
+        this.options.priority ?? null,
+        scheduledTx,
+      ];
+      
+      let schedArgs;
+      let scheduleFn;
+
+      if (this.options.scheduledId) {
+        schedArgs = [this.options.scheduledId!, ...mandatorySchedArgs];
 
+        if (this.scheduleFn == 'schedule') {
+          scheduleFn = 'scheduleNamed';
+        } else if (this.scheduleFn == 'scheduleAfter') {
+          scheduleFn = 'scheduleNamedAfter';
+        }
+      } else {
+        schedArgs = mandatorySchedArgs;
+        scheduleFn = this.scheduleFn;
+      }
+
+      const extrinsic = 'api.tx.scheduler.' +  scheduleFn;
+
       return super.executeExtrinsic(
         sender,
         extrinsic,
-        [
-          this.scheduledId,
-          this.blocksNum,
-          this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
-          this.options.priority ?? null,
-          {Value: scheduledTx},
-        ],
+        schedArgs,
         expectSuccess,
       );
     }
@@ -3046,20 +3057,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueBaseCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueBaseCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3155,20 +3164,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueNFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueNFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3260,20 +3267,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueRFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueRFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3329,20 +3334,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueFTCollection(this.collectionId, scheduledHelper);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledHelper = this.helper.scheduler.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueFTCollection(this.collectionId, scheduledHelper);
   }
 
@@ -3388,20 +3391,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueBaseToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueBaseToken(this.tokenId, scheduledCollection);
   }
 
@@ -3468,20 +3469,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueNFToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueNFToken(this.tokenId, scheduledCollection);
   }
 
@@ -3543,20 +3542,18 @@
   }
 
   scheduleAt<T extends UniqueHelper>(
-    scheduledId: string,
     executionBlockNumber: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAt<T>(scheduledId, executionBlockNumber, options);
+    const scheduledCollection = this.collection.scheduleAt<T>(executionBlockNumber, options);
     return new UniqueRFToken(this.tokenId, scheduledCollection);
   }
 
   scheduleAfter<T extends UniqueHelper>(
-    scheduledId: string,
     blocksBeforeExecution: number,
     options: ISchedulerOptions = {},
   ) {
-    const scheduledCollection = this.collection.scheduleAfter<T>(scheduledId, blocksBeforeExecution, options);
+    const scheduledCollection = this.collection.scheduleAfter<T>(blocksBeforeExecution, options);
     return new UniqueRFToken(this.tokenId, scheduledCollection);
   }