git.delta.rocks / unique-network / refs/commits / 4161c8ea6c50

difftreelog

refactor drop legacy unique scheduler

Yaroslav Bolyukin2023-10-02parent: #bce2cc1.patch.diff
in: master

9 files changed

deletedpallets/scheduler-v2/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler-v2/Cargo.toml
+++ /dev/null
@@ -1,45 +0,0 @@
-[package]
-authors = ["Unique Network <support@uniquenetwork.io>"]
-description = "Unique Scheduler pallet"
-edition = "2021"
-homepage = "https://unique.network"
-license = "GPLv3"
-name = "pallet-unique-scheduler-v2"
-readme = "README.md"
-repository = "https://github.com/UniqueNetwork/unique-chain"
-version = "0.1.0"
-
-[dependencies]
-# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
-codec = { workspace = true, package = "parity-scale-codec" }
-
-frame-benchmarking = { workspace = true, optional = true }
-frame-support = { workspace = true }
-frame-system = { workspace = true }
-log = { workspace = true }
-scale-info = { workspace = true }
-sp-core = { workspace = true }
-sp-io = { workspace = true }
-sp-runtime = { workspace = true }
-sp-std = { workspace = true }
-
-[dev-dependencies]
-pallet-preimage = { workspace = true }
-substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.43" }
-
-[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-core/std",
-	"sp-io/std",
-	"sp-runtime/std",
-	"sp-std/std",
-]
-try-runtime = ["frame-support/try-runtime"]
deletedpallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/benchmarking.rs
+++ /dev/null
@@ -1,374 +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-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.clamp(
-				bound,
-				<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2,
-			) - 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);
-}
deletedpallets/scheduler-v2/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/lib.rs
+++ /dev/null
@@ -1,1338 +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.
-
-//! # 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
-//! 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.
-
-// Ensure we're `no_std` when compiling for Wasm.
-#![cfg_attr(not(feature = "std"), no_std)]
-#![deny(missing_docs)]
-
-#[cfg(feature = "runtime-benchmarks")]
-mod benchmarking;
-#[cfg(test)]
-mod mock;
-#[cfg(test)]
-mod tests;
-// We dont use this pallet right now
-#[allow(deprecated)]
-pub mod weights;
-
-use codec::{Codec, Decode, Encode, MaxEncodedLen};
-use frame_support::{
-	dispatch::{
-		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,
-	},
-	traits::{
-		schedule::{self, DispatchTime, LOWEST_PRIORITY},
-		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,
-		ConstU32, UnfilteredDispatchable,
-	},
-	weights::Weight,
-	unsigned::TransactionValidityError,
-};
-
-use frame_system::{self as system};
-use scale_info::TypeInfo;
-use sp_runtime::{
-	traits::{BadOrigin, One, Saturating, Zero, Hash},
-	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,
-};
-use sp_core::H160;
-use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};
-pub use weights::WeightInfo;
-
-pub use pallet::*;
-
-/// Just a simple index for naming period tasks.
-pub type PeriodicIndex = u32;
-/// The location of a scheduled task that can be used to remove it.
-pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
-
-/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.
-pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;
-
-#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
-#[scale_info(skip_type_params(T))]
-/// A scheduled call is stored as is or as a preimage hash to lookup.
-/// This enum represents both variants.
-pub enum ScheduledCall<T: Config> {
-	/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.
-	Inline(EncodedCall),
-
-	/// A Blake2-256 hash of the call together with an upper limit for its size.
-	PreimageLookup {
-		/// A call hash to lookup
-		hash: T::Hash,
-
-		/// The length of the decoded call
-		unbounded_len: u32,
-	},
-}
-
-impl<T: Config> ScheduledCall<T> {
-	/// Convert an otherwise unbounded or large value into a type ready for placing in storage.
-	///
-	/// NOTE: Once this API is used, you should use either `drop` or `realize`.
-	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {
-		let encoded = call.encode();
-		let len = encoded.len();
-
-		match EncodedCall::try_from(encoded.clone()) {
-			Ok(bounded) => Ok(Self::Inline(bounded)),
-			Err(_) => {
-				let hash = <T as system::Config>::Hashing::hash_of(&encoded);
-				<T as Config>::Preimages::note_preimage(
-					encoded
-						.try_into()
-						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,
-				);
-
-				Ok(Self::PreimageLookup {
-					hash,
-					unbounded_len: len as u32,
-				})
-			}
-		}
-	}
-
-	/// The maximum length of the lookup that is needed to peek `Self`.
-	pub fn lookup_len(&self) -> Option<u32> {
-		match self {
-			Self::Inline(..) => None,
-			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),
-		}
-	}
-
-	/// Returns whether the image will require a lookup to be peeked.
-	pub fn lookup_needed(&self) -> bool {
-		match self {
-			Self::Inline(_) => false,
-			Self::PreimageLookup { .. } => true,
-		}
-	}
-
-	// Decodes a runtime call
-	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {
-		<T as Config>::RuntimeCall::decode(&mut data)
-			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())
-	}
-}
-
-/// Weight Info for the Preimages fetches.
-pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {
-	/// Get the weight of a task fetches with a given decoded length.
-	fn service_task_fetched(call_length: u32) -> Weight;
-}
-
-impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {
-	fn service_task_fetched(_call_length: u32) -> Weight {
-		W::service_task_base()
-	}
-}
-
-/// A scheduler's interface for managing preimages to hashes
-/// and looking up preimages from their hash on-chain.
-pub trait SchedulerPreimages<T: Config>:
-	PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>
-{
-	/// No longer request that the data for decoding the given `call` is available.
-	fn drop(call: &ScheduledCall<T>);
-
-	/// Convert the given `call` instance back into its original instance, also returning the
-	/// exact size of its encoded form if it needed to be looked-up from a stored preimage.
-	///
-	/// NOTE: This does not remove any data needed for realization. If you will no longer use the
-	/// `call`, use `realize` instead or use `drop` afterwards.
-	fn peek(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
-
-	/// Convert the given scheduled `call` value back into its original instance. If successful,
-	/// `drop` any data backing it. This will not break the realisability of independently
-	/// created instances of `ScheduledCall` which happen to have identical data.
-	fn realize(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
-}
-
-impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>
-	SchedulerPreimages<T> for PP
-{
-	fn drop(call: &ScheduledCall<T>) {
-		match call {
-			ScheduledCall::Inline(_) => {}
-			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),
-		}
-	}
-
-	fn peek(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
-		match call {
-			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),
-			ScheduledCall::PreimageLookup {
-				hash,
-				unbounded_len,
-			} => {
-				let (preimage, len) = Self::get_preimage(hash)
-					.ok_or(<Error<T>>::PreimageNotFound)
-					.map(|preimage| (preimage, *unbounded_len))?;
-
-				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))
-			}
-		}
-	}
-
-	fn realize(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
-		let r = Self::peek(call)?;
-		Self::drop(call);
-		Ok(r)
-	}
-}
-
-/// Scheduler's supported origins.
-pub enum ScheduledEnsureOriginSuccess<AccountId> {
-	/// A scheduled transaction has the Root origin.
-	Root,
-
-	/// A specific account has signed a scheduled transaction.
-	Signed(AccountId),
-}
-
-/// An identifier of a scheduled task.
-pub type TaskName = [u8; 32];
-
-/// Information regarding an item to be executed in the future.
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
-#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
-pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {
-	/// The unique identity for this task, if there is one.
-	maybe_id: Option<Name>,
-
-	/// 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 with which to dispatch the call.
-	origin: PalletsOrigin,
-	_phantom: PhantomData<AccountId>,
-}
-
-/// Information regarding an item to be executed in the future.
-pub type ScheduledOf<T> = Scheduled<
-	TaskName,
-	ScheduledCall<T>,
-	<T as frame_system::Config>::BlockNumber,
-	<T as Config>::PalletsOrigin,
-	<T as frame_system::Config>::AccountId,
->;
-
-#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
-#[scale_info(skip_type_params(T))]
-/// A structure for storing scheduled tasks in a block.
-/// The `BlockAgenda` tracks the available free space for a new task in a block.4
-///
-/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.
-pub struct BlockAgenda<T: Config> {
-	agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,
-	free_places: u32,
-}
-
-impl<T: Config> BlockAgenda<T> {
-	/// Tries to push a new scheduled task into the block's agenda.
-	/// If there is a free place, the new task will take it,
-	/// and the `BlockAgenda` will record that the number of free places has decreased.
-	///
-	/// An error containing the scheduled task will be returned if there are no free places.
-	///
-	/// The complexity of the check for the *existence* of a free place is O(1).
-	/// The complexity of *finding* the free slot is O(n).
-	fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {
-		if self.free_places == 0 {
-			return Err(scheduled);
-		}
-
-		self.free_places = self.free_places.saturating_sub(1);
-
-		if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
-			// will always succeed due to the above check.
-			let _ = self.agenda.try_push(Some(scheduled));
-			Ok((self.agenda.len() - 1) as u32)
-		} else {
-			match self.agenda.iter().position(|i| i.is_none()) {
-				Some(hole_index) => {
-					self.agenda[hole_index] = Some(scheduled);
-					Ok(hole_index as u32)
-				}
-				None => unreachable!("free_places was greater than 0; qed"),
-			}
-		}
-	}
-
-	/// Sets a slot by the given index and the slot value.
-	///
-	/// ### Panics
-	/// If the index is out of range, the function will panic.
-	fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {
-		self.agenda[index as usize] = slot;
-	}
-
-	/// Returns an iterator containing references to the agenda's slots.
-	fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {
-		self.agenda.iter()
-	}
-
-	/// Returns an immutable reference to a scheduled task if there is one under the given index.
-	///
-	///  The function returns `None` if:
-	/// * The `index` is out of range
-	/// * No scheduled task occupies the agenda slot under the given index.
-	fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {
-		match self.agenda.get(index as usize) {
-			Some(Some(scheduled)) => Some(scheduled),
-			_ => None,
-		}
-	}
-
-	/// Returns a mutable reference to a scheduled task if there is one under the given index.
-	///
-	///  The function returns `None` if:
-	/// * The `index` is out of range
-	/// * No scheduled task occupies the agenda slot under the given index.
-	fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {
-		match self.agenda.get_mut(index as usize) {
-			Some(Some(scheduled)) => Some(scheduled),
-			_ => None,
-		}
-	}
-
-	/// Take a scheduled task by the given index.
-	///
-	/// If there is a task under the index, the function will:
-	/// * Free the corresponding agenda slot.
-	/// * Decrease the number of free places.
-	/// * Return the scheduled task.
-	///
-	/// The function returns `None` if there is no task under the index.
-	fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {
-		let removed = self.agenda.get_mut(index as usize)?.take();
-
-		if removed.is_some() {
-			self.free_places = self.free_places.saturating_add(1);
-		}
-
-		removed
-	}
-}
-
-impl<T: Config> Default for BlockAgenda<T> {
-	fn default() -> Self {
-		let agenda = Default::default();
-		let free_places = T::MaxScheduledPerBlock::get();
-
-		Self {
-			agenda,
-			free_places,
-		}
-	}
-}
-/// A structure for tracking the used weight
-/// and checking if it does not exceed the weight limit.
-struct WeightCounter {
-	used: Weight,
-	limit: Weight,
-}
-
-impl WeightCounter {
-	/// Checks if the weight `w` can be accommodated by the counter.
-	///
-	/// If there is room for the additional weight `w`,
-	/// the function will update the used weight and return true.
-	fn check_accrue(&mut self, w: Weight) -> bool {
-		let test = self.used.saturating_add(w);
-		if test.any_gt(self.limit) {
-			false
-		} else {
-			self.used = test;
-			true
-		}
-	}
-
-	/// Checks if the weight `w` can be accommodated by the counter.
-	fn can_accrue(&mut self, w: Weight) -> bool {
-		self.used.saturating_add(w).all_lte(self.limit)
-	}
-}
-
-pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);
-
-impl<T: Config> MarginalWeightInfo<T> {
-	/// Return the weight of servicing a single task.
-	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {
-		let base = T::WeightInfo::service_task_base();
-		let mut total = match maybe_lookup_len {
-			None => base,
-			Some(l) => T::Preimages::service_task_fetched(l as u32),
-		};
-		if named {
-			total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));
-		}
-		if periodic {
-			total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));
-		}
-		total
-	}
-}
-
-#[frame_support::pallet]
-pub mod pallet {
-	use super::*;
-	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};
-	use system::pallet_prelude::*;
-
-	/// The current storage version.
-	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
-
-	#[pallet::pallet]
-	#[pallet::storage_version(STORAGE_VERSION)]
-	pub struct Pallet<T>(_);
-
-	#[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>
-			+ Clone;
-
-		/// The caller origin, overarching type of all pallets origins.
-		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>
-			+ Codec
-			+ Clone
-			+ Eq
-			+ TypeInfo
-			+ MaxEncodedLen;
-
-		/// 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.
-		#[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>,
-		>;
-
-		/// 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.
-		#[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 Preimages: SchedulerPreimages<Self>;
-
-		/// The helper type used for custom transaction fee logic.
-		type CallExecutor: DispatchCall<Self, H160>;
-
-		/// Required origin to set/change calls' priority.
-		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
-	}
-
-	/// It contains the block number from which we should service tasks.
-	/// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.
-	#[pallet::storage]
-	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;
-
-	/// 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, BlockAgenda<T>, ValueQuery>;
-
-	/// Lookup from a name to the block number and index of the task.
-	#[pallet::storage]
-	pub(crate) type Lookup<T: Config> =
-		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;
-
-	/// Events type.
-	#[pallet::event]
-	#[pallet::generate_deposit(pub(super) fn deposit_event)]
-	pub enum Event<T: Config> {
-		/// Scheduled some task.
-		Scheduled {
-			/// The block number in which the scheduled task should be executed.
-			when: T::BlockNumber,
-
-			/// The index of the block's agenda slot.
-			index: u32,
-		},
-		/// Canceled some task.
-		Canceled {
-			/// The block number in which the canceled task has been.
-			when: T::BlockNumber,
-
-			/// The index of the block's agenda slot that had become available.
-			index: u32,
-		},
-		/// Dispatched some task.
-		Dispatched {
-			/// The task's address - the block number and the block's agenda index.
-			task: TaskAddress<T::BlockNumber>,
-
-			/// The task's name if it is not anonymous.
-			id: Option<[u8; 32]>,
-
-			/// The task's execution result.
-			result: DispatchResult,
-		},
-		/// Scheduled task's priority has changed
-		PriorityChanged {
-			/// The task's address - the block number and the block's agenda index.
-			task: TaskAddress<T::BlockNumber>,
-
-			/// The new priority of the task.
-			priority: schedule::Priority,
-		},
-		/// The call for the provided hash was not found so the task has been aborted.
-		CallUnavailable {
-			/// The task's address - the block number and the block's agenda index.
-			task: TaskAddress<T::BlockNumber>,
-
-			/// The task's name if it is not anonymous.
-			id: Option<[u8; 32]>,
-		},
-		/// The given task can never be executed since it is overweight.
-		PermanentlyOverweight {
-			/// The task's address - the block number and the block's agenda index.
-			task: TaskAddress<T::BlockNumber>,
-
-			/// The task's name if it is not anonymous.
-			id: Option<[u8; 32]>,
-		},
-	}
-
-	#[pallet::error]
-	pub enum Error<T> {
-		/// Failed to schedule a call
-		FailedToSchedule,
-		/// There is no place for a new task in the agenda
-		AgendaIsExhausted,
-		/// Scheduled call is corrupted
-		ScheduledCallCorrupted,
-		/// Scheduled call preimage is not found
-		PreimageNotFound,
-		/// Scheduled call is too big
-		TooBigScheduledCall,
-		/// Cannot find the scheduled call.
-		NotFound,
-		/// Given target block number is in the past.
-		TargetBlockNumberInPast,
-		/// Attempt to use a non-named function on a named task.
-		Named,
-	}
-
-	#[pallet::hooks]
-	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		/// Execute the scheduled calls
-		fn on_initialize(now: T::BlockNumber) -> Weight {
-			let mut weight_counter = WeightCounter {
-				used: Weight::zero(),
-				limit: T::MaximumWeight::get(),
-			};
-			Self::service_agendas(&mut weight_counter, now, u32::max_value());
-			weight_counter.used
-		}
-	}
-
-	#[pallet::call]
-	impl<T: Config> Pallet<T> {
-		/// Anonymously schedule a task.
-		///
-		/// Only `T::ScheduleOrigin` is allowed to schedule a task.
-		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
-		#[pallet::call_index(0)]
-		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule(
-			origin: OriginFor<T>,
-			when: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> 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(
-				DispatchTime::At(when),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Cancel an anonymously scheduled task.
-		///
-		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.
-		#[pallet::call_index(1)]
-		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]
-		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
-			Ok(())
-		}
-
-		/// Schedule a named task.
-		///
-		/// Only `T::ScheduleOrigin` is allowed to schedule a task.
-		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
-		#[pallet::call_index(2)]
-		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_named(
-			origin: OriginFor<T>,
-			id: TaskName,
-			when: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> 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(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Cancel a named scheduled task.
-		///
-		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.
-		#[pallet::call_index(3)]
-		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
-		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> 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(())
-		}
-
-		/// Anonymously schedule a task after a delay.
-		///
-		/// # <weight>
-		/// Same as [`schedule`].
-		/// # </weight>
-		#[pallet::call_index(4)]
-		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_after(
-			origin: OriginFor<T>,
-			after: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> 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(
-				DispatchTime::After(after),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Schedule a named task after a delay.
-		///
-		/// Only `T::ScheduleOrigin` is allowed to schedule a task.
-		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.
-		///
-		/// # <weight>
-		/// Same as [`schedule_named`](Self::schedule_named).
-		/// # </weight>
-		#[pallet::call_index(5)]
-		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_named_after(
-			origin: OriginFor<T>,
-			id: TaskName,
-			after: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> 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(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Change a named task's priority.
-		///
-		/// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.
-		#[pallet::call_index(6)]
-		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]
-		pub fn change_named_priority(
-			origin: OriginFor<T>,
-			id: TaskName,
-			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> {
-	/// Converts the `DispatchTime` to the `BlockNumber`.
-	///
-	/// Returns an error if the block number is in the past.
-	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)
-	}
-
-	/// Places the mandatory task.
-	///
-	/// It will try to place the task into the block pointed by the `when` parameter.
-	///
-	/// If the block has no room for a task,
-	/// the function will search for a future block that can accommodate the task.
-	fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {
-		Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");
-	}
-
-	/// Tries to place a task `what` into the given block `when`.
-	///
-	/// Returns an error if the block has no room for the task.
-	fn try_place_task(
-		when: T::BlockNumber,
-		what: ScheduledOf<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		Self::place_task(when, what, false)
-	}
-
-	/// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);
-	/// otherwise it acts like [`try_place_task`](Self::try_place_task).
-	///
-	/// The function also updates the `Lookup` storage.
-	fn place_task(
-		mut when: T::BlockNumber,
-		what: ScheduledOf<T>,
-		is_mandatory: bool,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		let maybe_name = what.maybe_id;
-		let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;
-		let address = (when, index);
-		if let Some(name) = maybe_name {
-			Lookup::<T>::insert(name, address)
-		}
-		Self::deposit_event(Event::Scheduled {
-			when: address.0,
-			index: address.1,
-		});
-		Ok(address)
-	}
-
-	/// Pushes the scheduled task into the block's agenda.
-	///
-	/// If `is_mandatory` is true, it searches for a block with a free slot for the given task.
-	///
-	/// If `is_mandatory` is false and there is no free slot, the function returns an error.
-	fn push_to_agenda(
-		when: &mut T::BlockNumber,
-		mut what: ScheduledOf<T>,
-		is_mandatory: bool,
-	) -> Result<u32, DispatchError> {
-		let mut agenda;
-
-		let index = loop {
-			agenda = Agenda::<T>::get(*when);
-
-			match agenda.try_push(what) {
-				Ok(index) => break index,
-				Err(returned_what) if is_mandatory => {
-					what = returned_what;
-					when.saturating_inc();
-				}
-				Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),
-			}
-		};
-
-		Agenda::<T>::insert(when, agenda);
-		Ok(index)
-	}
-
-	fn do_schedule(
-		when: DispatchTime<T::BlockNumber>,
-		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-		priority: schedule::Priority,
-		origin: T::PalletsOrigin,
-		call: ScheduledCall<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		let when = Self::resolve_time(when)?;
-
-		// 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 task = Scheduled {
-			maybe_id: None,
-			priority,
-			call,
-			maybe_periodic,
-			origin,
-			_phantom: PhantomData,
-		};
-		Self::try_place_task(when, task)
-	}
-
-	fn do_cancel(
-		origin: Option<T::PalletsOrigin>,
-		(when, index): TaskAddress<T::BlockNumber>,
-	) -> Result<(), DispatchError> {
-		let scheduled = Agenda::<T>::try_mutate(
-			when,
-			|agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
-				let scheduled = match agenda.get(index) {
-					Some(scheduled) => scheduled,
-					None => return Ok(None),
-				};
-
-				if let Some(ref o) = origin {
-					if matches!(
-						T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),
-						Some(Ordering::Less) | None
-					) {
-						return Err(BadOrigin.into());
-					}
-				}
-
-				Ok(agenda.take(index))
-			},
-		)?;
-		if let Some(s) = scheduled {
-			T::Preimages::drop(&s.call);
-
-			if let Some(id) = s.maybe_id {
-				Lookup::<T>::remove(id);
-			}
-			Self::deposit_event(Event::Canceled { when, index });
-			Ok(())
-		} else {
-			Err(Error::<T>::NotFound.into())
-		}
-	}
-
-	fn do_schedule_named(
-		id: TaskName,
-		when: DispatchTime<T::BlockNumber>,
-		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-		priority: schedule::Priority,
-		origin: T::PalletsOrigin,
-		call: ScheduledCall<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		// ensure id it is unique
-		if Lookup::<T>::contains_key(id) {
-			return Err(Error::<T>::FailedToSchedule.into());
-		}
-
-		let when = Self::resolve_time(when)?;
-
-		// 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 task = Scheduled {
-			maybe_id: Some(id),
-			priority,
-			call,
-			maybe_periodic,
-			origin,
-			_phantom: Default::default(),
-		};
-		Self::try_place_task(when, task)
-	}
-
-	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
-		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
-			if let Some((when, index)) = lookup.take() {
-				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
-					let scheduled = match agenda.get(index) {
-						Some(scheduled) => scheduled,
-						None => return Ok(()),
-					};
-
-					if let Some(ref o) = origin {
-						if matches!(
-							T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),
-							Some(Ordering::Less) | None
-						) {
-							return Err(BadOrigin.into());
-						}
-						T::Preimages::drop(&scheduled.call);
-					}
-
-					agenda.take(index);
-
-					Ok(())
-				})?;
-				Self::deposit_event(Event::Canceled { when, index });
-				Ok(())
-			} else {
-				Err(Error::<T>::NotFound.into())
-			}
-		})
-	}
-
-	fn do_change_named_priority(
-		origin: T::PalletsOrigin,
-		id: TaskName,
-		priority: schedule::Priority,
-	) -> DispatchResult {
-		match Lookup::<T>::get(id) {
-			Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {
-				let scheduled = match agenda.get_mut(index) {
-					Some(scheduled) => scheduled,
-					None => return Ok(()),
-				};
-
-				if matches!(
-					T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),
-					Some(Ordering::Less) | None
-				) {
-					return Err(BadOrigin.into());
-				}
-
-				scheduled.priority = priority;
-				Self::deposit_event(Event::PriorityChanged {
-					task: (when, index),
-					priority,
-				});
-
-				Ok(())
-			}),
-			None => Err(Error::<T>::NotFound.into()),
-		}
-	}
-}
-
-enum ServiceTaskError {
-	/// Could not be executed due to missing preimage.
-	Unavailable,
-	/// Could not be executed due to weight limitations.
-	Overweight,
-}
-use ServiceTaskError::*;
-
-/// A Scheduler-Runtime interface for finer payment handling.
-pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
-	/// 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,
-	>;
-}
-
-impl<T: Config> Pallet<T> {
-	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.
-	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {
-		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {
-			return;
-		}
-
-		let mut incomplete_since = now + One::one();
-		let mut when = IncompleteSince::<T>::take().unwrap_or(now);
-		let mut executed = 0;
-
-		let max_items = T::MaxScheduledPerBlock::get();
-		let mut count_down = max;
-		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);
-		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {
-			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {
-				incomplete_since = incomplete_since.min(when);
-			}
-			when.saturating_inc();
-			count_down.saturating_dec();
-		}
-		incomplete_since = incomplete_since.min(when);
-		if incomplete_since <= now {
-			IncompleteSince::<T>::put(incomplete_since);
-		}
-	}
-
-	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a
-	/// later block.
-	fn service_agenda(
-		weight: &mut WeightCounter,
-		executed: &mut u32,
-		now: T::BlockNumber,
-		when: T::BlockNumber,
-		max: u32,
-	) -> bool {
-		let mut agenda = Agenda::<T>::get(when);
-		let mut ordered = agenda
-			.iter()
-			.enumerate()
-			.filter_map(|(index, maybe_item)| {
-				maybe_item
-					.as_ref()
-					.map(|item| (index as u32, item.priority))
-			})
-			.collect::<Vec<_>>();
-		ordered.sort_by_key(|k| k.1);
-		let within_limit =
-			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));
-		debug_assert!(
-			within_limit,
-			"weight limit should have been checked in advance"
-		);
-
-		// Items which we know can be executed and have postponed for execution in a later block.
-		let mut postponed = (ordered.len() as u32).saturating_sub(max);
-		// Items which we don't know can ever be executed.
-		let mut dropped = 0;
-
-		for (agenda_index, _) in ordered.into_iter().take(max as usize) {
-			let task = match agenda.take(agenda_index).take() {
-				None => continue,
-				Some(t) => t,
-			};
-			let base_weight = MarginalWeightInfo::<T>::service_task(
-				task.call.lookup_len().map(|x| x as usize),
-				task.maybe_id.is_some(),
-				task.maybe_periodic.is_some(),
-			);
-			if !weight.can_accrue(base_weight) {
-				postponed += 1;
-				break;
-			}
-			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);
-			match result {
-				Err((Unavailable, slot)) => {
-					dropped += 1;
-					agenda.set_slot(agenda_index, slot);
-				}
-				Err((Overweight, slot)) => {
-					postponed += 1;
-					agenda.set_slot(agenda_index, slot);
-				}
-				Ok(()) => {
-					*executed += 1;
-				}
-			};
-		}
-		if postponed > 0 || dropped > 0 {
-			Agenda::<T>::insert(when, agenda);
-		} else {
-			Agenda::<T>::remove(when);
-		}
-		postponed == 0
-	}
-
-	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.
-	///
-	/// This involves:
-	/// - removing and potentially replacing the `Lookup` entry for the task.
-	/// - realizing the task's call which can include a preimage lookup.
-	/// - Rescheduling the task for execution in a later agenda if periodic.
-	fn service_task(
-		weight: &mut WeightCounter,
-		now: T::BlockNumber,
-		when: T::BlockNumber,
-		agenda_index: u32,
-		is_first: bool,
-		mut task: ScheduledOf<T>,
-	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {
-		let (call, lookup_len) = match T::Preimages::peek(&task.call) {
-			Ok(c) => c,
-			Err(_) => {
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				return Err((Unavailable, Some(task)));
-			}
-		};
-
-		weight.check_accrue(MarginalWeightInfo::<T>::service_task(
-			lookup_len.map(|x| x as usize),
-			task.maybe_id.is_some(),
-			task.maybe_periodic.is_some(),
-		));
-
-		match Self::execute_dispatch(weight, task.origin.clone(), call) {
-			Err(Unavailable) => {
-				debug_assert!(false, "Checked to exist with `peek`");
-
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				Self::deposit_event(Event::CallUnavailable {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-				});
-				Err((Unavailable, Some(task)))
-			}
-			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {
-				T::Preimages::drop(&task.call);
-
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				Self::deposit_event(Event::PermanentlyOverweight {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-				});
-				Err((Unavailable, Some(task)))
-			}
-			Err(Overweight) => {
-				// Preserve Lookup -- the task will be postponed.
-				Err((Overweight, Some(task)))
-			}
-			Ok(result) => {
-				Self::deposit_event(Event::Dispatched {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-					result,
-				});
-
-				let is_canceled = task
-					.maybe_id
-					.as_ref()
-					.map(|id| !Lookup::<T>::contains_key(id))
-					.unwrap_or(false);
-
-				match &task.maybe_periodic {
-					&Some((period, count)) if !is_canceled => {
-						if count > 1 {
-							task.maybe_periodic = Some((period, count - 1));
-						} else {
-							task.maybe_periodic = None;
-						}
-						let wake = now.saturating_add(period);
-						Self::mandatory_place_task(wake, task);
-					}
-					_ => {
-						if let Some(ref id) = task.maybe_id {
-							Lookup::<T>::remove(id);
-						}
-
-						T::Preimages::drop(&task.call)
-					}
-				}
-				Ok(())
-			}
-		}
-	}
-
-	fn is_runtime_upgraded() -> bool {
-		let last = system::LastRuntimeUpgrade::<T>::get();
-		let current = T::Version::get();
-
-		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)
-	}
-
-	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`
-	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using
-	/// post info if available).
-	///
-	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the
-	/// call itself).
-	fn execute_dispatch(
-		weight: &mut WeightCounter,
-		origin: T::PalletsOrigin,
-		call: <T as Config>::RuntimeCall,
-	) -> Result<DispatchResult, ServiceTaskError> {
-		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();
-		let base_weight = match dispatch_origin.clone().as_signed() {
-			Some(_) => T::WeightInfo::execute_dispatch_signed(),
-			_ => T::WeightInfo::execute_dispatch_unsigned(),
-		};
-		let call_weight = call.get_dispatch_info().weight;
-		// We only allow a scheduled call if it cannot push the weight past the limit.
-		let max_weight = base_weight.saturating_add(call_weight);
-
-		if !weight.can_accrue(max_weight) {
-			return Err(Overweight);
-		}
-
-		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_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)
-			}
-			Err(e) => Ok(Err(e.into())),
-		};
-
-		let (maybe_actual_call_weight, result) = match r {
-			Ok(result) => match result {
-				Ok(post_info) => (post_info.actual_weight, Ok(())),
-				Err(error_and_info) => (
-					error_and_info.post_info.actual_weight,
-					Err(error_and_info.error),
-				),
-			},
-			Err(_) => {
-				log::error!(
-					target: "runtime::scheduler",
-					"Warning: Scheduler has failed to execute a post-dispatch transaction. \
-					This block might have become invalid.");
-				(None, Err(DispatchError::CannotLookup))
-			}
-		};
-		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);
-		weight.check_accrue(base_weight);
-		weight.check_accrue(call_weight);
-		Ok(result)
-	}
-}
deletedpallets/scheduler-v2/src/mock.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/mock.rs
+++ /dev/null
@@ -1,292 +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.
-
-//! # Scheduler test environment.
-#![allow(deprecated)]
-
-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]
-	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::call_index(0)]
-		#[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::call_index(1)]
-		#[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)),
-		})
-	}
-	#[cfg(feature = "runtime-benchmarks")]
-	fn try_successful_origin() -> Result<O, ()> {
-		Ok(O::from(RawOrigin::Root))
-	}
-}
-
-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()
-}
deletedpallets/scheduler-v2/src/tests.rsdiffbeforeafterboth
before · pallets/scheduler-v2/src/tests.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//! # Scheduler tests.36#![allow(deprecated)]3738use super::*;39use crate::mock::{40	logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,41};42use frame_support::{43	assert_noop, assert_ok,44	traits::{Contains, OnInitialize},45	assert_err,46};4748#[test]49fn basic_scheduling_works() {50	new_test_ext().execute_with(|| {51		let call = RuntimeCall::Logger(LoggerCall::log {52			i: 42,53			weight: Weight::from_ref_time(10),54		});55		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(56			&call57		));58		assert_ok!(Scheduler::do_schedule(59			DispatchTime::At(4),60			None,61			127,62			root(),63			<ScheduledCall<Test>>::new(call).unwrap(),64		));65		run_to_block(3);66		assert!(logger::log().is_empty());67		run_to_block(4);68		assert_eq!(logger::log(), vec![(root(), 42u32)]);69		run_to_block(100);70		assert_eq!(logger::log(), vec![(root(), 42u32)]);71	});72}7374#[test]75fn schedule_after_works() {76	new_test_ext().execute_with(|| {77		run_to_block(2);78		let call = RuntimeCall::Logger(LoggerCall::log {79			i: 42,80			weight: Weight::from_ref_time(10),81		});82		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(83			&call84		));85		// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 686		assert_ok!(Scheduler::do_schedule(87			DispatchTime::After(3),88			None,89			127,90			root(),91			<ScheduledCall<Test>>::new(call).unwrap(),92		));93		run_to_block(5);94		assert!(logger::log().is_empty());95		run_to_block(6);96		assert_eq!(logger::log(), vec![(root(), 42u32)]);97		run_to_block(100);98		assert_eq!(logger::log(), vec![(root(), 42u32)]);99	});100}101102#[test]103fn schedule_after_zero_works() {104	new_test_ext().execute_with(|| {105		run_to_block(2);106		let call = RuntimeCall::Logger(LoggerCall::log {107			i: 42,108			weight: Weight::from_ref_time(10),109		});110		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(111			&call112		));113		assert_ok!(Scheduler::do_schedule(114			DispatchTime::After(0),115			None,116			127,117			root(),118			<ScheduledCall<Test>>::new(call).unwrap(),119		));120		// Will trigger on the next block.121		run_to_block(3);122		assert_eq!(logger::log(), vec![(root(), 42u32)]);123		run_to_block(100);124		assert_eq!(logger::log(), vec![(root(), 42u32)]);125	});126}127128#[test]129fn periodic_scheduling_works() {130	new_test_ext().execute_with(|| {131		// at #4, every 3 blocks, 3 times.132		assert_ok!(Scheduler::do_schedule(133			DispatchTime::At(4),134			Some((3, 3)),135			127,136			root(),137			<ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {138				i: 42,139				weight: Weight::from_ref_time(10)140			}))141			.unwrap()142		));143		run_to_block(3);144		assert!(logger::log().is_empty());145		run_to_block(4);146		assert_eq!(logger::log(), vec![(root(), 42u32)]);147		run_to_block(6);148		assert_eq!(logger::log(), vec![(root(), 42u32)]);149		run_to_block(7);150		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);151		run_to_block(9);152		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);153		run_to_block(10);154		assert_eq!(155			logger::log(),156			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]157		);158		run_to_block(100);159		assert_eq!(160			logger::log(),161			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]162		);163	});164}165166#[test]167fn cancel_named_scheduling_works_with_normal_cancel() {168	new_test_ext().execute_with(|| {169		// at #4.170		Scheduler::do_schedule_named(171			[1u8; 32],172			DispatchTime::At(4),173			None,174			127,175			root(),176			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {177				i: 69,178				weight: Weight::from_ref_time(10),179			}))180			.unwrap(),181		)182		.unwrap();183		let i = Scheduler::do_schedule(184			DispatchTime::At(4),185			None,186			127,187			root(),188			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {189				i: 42,190				weight: Weight::from_ref_time(10),191			}))192			.unwrap(),193		)194		.unwrap();195		run_to_block(3);196		assert!(logger::log().is_empty());197		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));198		assert_ok!(Scheduler::do_cancel(None, i));199		run_to_block(100);200		assert!(logger::log().is_empty());201	});202}203204#[test]205fn cancel_named_periodic_scheduling_works() {206	new_test_ext().execute_with(|| {207		// at #4, every 3 blocks, 3 times.208		Scheduler::do_schedule_named(209			[1u8; 32],210			DispatchTime::At(4),211			Some((3, 3)),212			127,213			root(),214			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {215				i: 42,216				weight: Weight::from_ref_time(10),217			}))218			.unwrap(),219		)220		.unwrap();221		// same id results in error.222		assert!(Scheduler::do_schedule_named(223			[1u8; 32],224			DispatchTime::At(4),225			None,226			127,227			root(),228			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {229				i: 69,230				weight: Weight::from_ref_time(10)231			}))232			.unwrap(),233		)234		.is_err());235		// different id is ok.236		Scheduler::do_schedule_named(237			[2u8; 32],238			DispatchTime::At(8),239			None,240			127,241			root(),242			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {243				i: 69,244				weight: Weight::from_ref_time(10),245			}))246			.unwrap(),247		)248		.unwrap();249		run_to_block(3);250		assert!(logger::log().is_empty());251		run_to_block(4);252		assert_eq!(logger::log(), vec![(root(), 42u32)]);253		run_to_block(6);254		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));255		run_to_block(100);256		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);257	});258}259260#[test]261fn scheduler_respects_weight_limits() {262	let max_weight: Weight = <Test as Config>::MaximumWeight::get();263	new_test_ext().execute_with(|| {264		let call = RuntimeCall::Logger(LoggerCall::log {265			i: 42,266			weight: max_weight / 3 * 2,267		});268		assert_ok!(Scheduler::do_schedule(269			DispatchTime::At(4),270			None,271			127,272			root(),273			<ScheduledCall<Test>>::new(call).unwrap(),274		));275		let call = RuntimeCall::Logger(LoggerCall::log {276			i: 69,277			weight: max_weight / 3 * 2,278		});279		assert_ok!(Scheduler::do_schedule(280			DispatchTime::At(4),281			None,282			127,283			root(),284			<ScheduledCall<Test>>::new(call).unwrap(),285		));286		// 69 and 42 do not fit together287		run_to_block(4);288		assert_eq!(logger::log(), vec![(root(), 42u32)]);289		run_to_block(5);290		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);291	});292}293294/// Permanently overweight calls are not deleted but also not executed.295#[test]296fn scheduler_does_not_delete_permanently_overweight_call() {297	let max_weight: Weight = <Test as Config>::MaximumWeight::get();298	new_test_ext().execute_with(|| {299		let call = RuntimeCall::Logger(LoggerCall::log {300			i: 42,301			weight: max_weight,302		});303		assert_ok!(Scheduler::do_schedule(304			DispatchTime::At(4),305			None,306			127,307			root(),308			<ScheduledCall<Test>>::new(call).unwrap(),309		));310		// Never executes.311		run_to_block(100);312		assert_eq!(logger::log(), vec![]);313314		// Assert the `PermanentlyOverweight` event.315		assert_eq!(316			System::events().last().unwrap().event,317			crate::Event::PermanentlyOverweight {318				task: (4, 0),319				id: None320			}321			.into(),322		);323		// The call is still in the agenda.324		assert!(Agenda::<Test>::get(4).agenda[0].is_some());325	});326}327328#[test]329fn scheduler_periodic_tasks_always_find_place() {330	let max_weight: Weight = <Test as Config>::MaximumWeight::get();331	let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();332333	new_test_ext().execute_with(|| {334		let call = RuntimeCall::Logger(LoggerCall::log {335			i: 42,336			weight: (max_weight / 3) * 2,337		});338		let call = <ScheduledCall<Test>>::new(call).unwrap();339340		assert_ok!(Scheduler::do_schedule(341			DispatchTime::At(4),342			Some((4, u32::MAX)),343			127,344			root(),345			call.clone(),346		));347		// Executes 5 times till block 20.348		run_to_block(20);349		assert_eq!(logger::log().len(), 5);350351		// Block 28 will already be full.352		for _ in 0..max_per_block {353			assert_ok!(Scheduler::do_schedule(354				DispatchTime::At(28),355				None,356				120,357				root(),358				call.clone(),359			));360		}361362		run_to_block(24);363		assert_eq!(logger::log().len(), 6);364365		// The periodic task should be postponed366		assert_eq!(<Agenda<Test>>::get(29).agenda.len(), 1);367368		run_to_block(27); // will call on_initialize(28)369		assert_eq!(logger::log().len(), 6);370371		run_to_block(28); // will call on_initialize(29)372		assert_eq!(logger::log().len(), 7);373	});374}375376#[test]377fn scheduler_respects_priority_ordering() {378	let max_weight: Weight = <Test as Config>::MaximumWeight::get();379	new_test_ext().execute_with(|| {380		let call = RuntimeCall::Logger(LoggerCall::log {381			i: 42,382			weight: max_weight / 3,383		});384		assert_ok!(Scheduler::do_schedule(385			DispatchTime::At(4),386			None,387			1,388			root(),389			<ScheduledCall<Test>>::new(call).unwrap(),390		));391		let call = RuntimeCall::Logger(LoggerCall::log {392			i: 69,393			weight: max_weight / 3,394		});395		assert_ok!(Scheduler::do_schedule(396			DispatchTime::At(4),397			None,398			0,399			root(),400			<ScheduledCall<Test>>::new(call).unwrap(),401		));402		run_to_block(4);403		assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);404	});405}406407#[test]408fn scheduler_respects_priority_ordering_with_soft_deadlines() {409	new_test_ext().execute_with(|| {410		let max_weight: Weight = <Test as Config>::MaximumWeight::get();411		let call = RuntimeCall::Logger(LoggerCall::log {412			i: 42,413			weight: max_weight / 5 * 2,414		});415		assert_ok!(Scheduler::do_schedule(416			DispatchTime::At(4),417			None,418			255,419			root(),420			<ScheduledCall<Test>>::new(call).unwrap(),421		));422		let call = RuntimeCall::Logger(LoggerCall::log {423			i: 69,424			weight: max_weight / 5 * 2,425		});426		assert_ok!(Scheduler::do_schedule(427			DispatchTime::At(4),428			None,429			127,430			root(),431			<ScheduledCall<Test>>::new(call).unwrap(),432		));433		let call = RuntimeCall::Logger(LoggerCall::log {434			i: 2600,435			weight: max_weight / 5 * 4,436		});437		assert_ok!(Scheduler::do_schedule(438			DispatchTime::At(4),439			None,440			126,441			root(),442			<ScheduledCall<Test>>::new(call).unwrap(),443		));444445		// 2600 does not fit with 69 or 42, but has higher priority, so will go through446		run_to_block(4);447		assert_eq!(logger::log(), vec![(root(), 2600u32)]);448		// 69 and 42 fit together449		run_to_block(5);450		assert_eq!(451			logger::log(),452			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]453		);454	});455}456457#[test]458fn on_initialize_weight_is_correct() {459	new_test_ext().execute_with(|| {460		let call_weight = Weight::from_ref_time(25);461462		// Named463		let call = RuntimeCall::Logger(LoggerCall::log {464			i: 3,465			weight: call_weight + Weight::from_ref_time(1),466		});467		assert_ok!(Scheduler::do_schedule_named(468			[1u8; 32],469			DispatchTime::At(3),470			None,471			255,472			root(),473			<ScheduledCall<Test>>::new(call).unwrap(),474		));475		let call = RuntimeCall::Logger(LoggerCall::log {476			i: 42,477			weight: call_weight + Weight::from_ref_time(2),478		});479		// Anon Periodic480		assert_ok!(Scheduler::do_schedule(481			DispatchTime::At(2),482			Some((1000, 3)),483			128,484			root(),485			<ScheduledCall<Test>>::new(call).unwrap(),486		));487		let call = RuntimeCall::Logger(LoggerCall::log {488			i: 69,489			weight: call_weight + Weight::from_ref_time(3),490		});491		// Anon492		assert_ok!(Scheduler::do_schedule(493			DispatchTime::At(2),494			None,495			127,496			root(),497			<ScheduledCall<Test>>::new(call).unwrap(),498		));499		// Named Periodic500		let call = RuntimeCall::Logger(LoggerCall::log {501			i: 2600,502			weight: call_weight + Weight::from_ref_time(4),503		});504		assert_ok!(Scheduler::do_schedule_named(505			[2u8; 32],506			DispatchTime::At(1),507			Some((1000, 3)),508			126,509			root(),510			<ScheduledCall<Test>>::new(call).unwrap(),511		));512513		// Will include the named periodic only514		assert_eq!(515			Scheduler::on_initialize(1),516			TestWeightInfo::service_agendas_base()517				+ TestWeightInfo::service_agenda_base(1)518				+ <MarginalWeightInfo<Test>>::service_task(None, true, true)519				+ TestWeightInfo::execute_dispatch_unsigned()520				+ call_weight + Weight::from_ref_time(4)521		);522		assert_eq!(IncompleteSince::<Test>::get(), None);523		assert_eq!(logger::log(), vec![(root(), 2600u32)]);524525		// Will include anon and anon periodic526		assert_eq!(527			Scheduler::on_initialize(2),528			TestWeightInfo::service_agendas_base()529				+ TestWeightInfo::service_agenda_base(2)530				+ <MarginalWeightInfo<Test>>::service_task(None, false, true)531				+ TestWeightInfo::execute_dispatch_unsigned()532				+ call_weight + Weight::from_ref_time(3)533				+ <MarginalWeightInfo<Test>>::service_task(None, false, false)534				+ TestWeightInfo::execute_dispatch_unsigned()535				+ call_weight + Weight::from_ref_time(2)536		);537		assert_eq!(IncompleteSince::<Test>::get(), None);538		assert_eq!(539			logger::log(),540			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]541		);542543		// Will include named only544		assert_eq!(545			Scheduler::on_initialize(3),546			TestWeightInfo::service_agendas_base()547				+ TestWeightInfo::service_agenda_base(1)548				+ <MarginalWeightInfo<Test>>::service_task(None, true, false)549				+ TestWeightInfo::execute_dispatch_unsigned()550				+ call_weight + Weight::from_ref_time(1)551		);552		assert_eq!(IncompleteSince::<Test>::get(), None);553		assert_eq!(554			logger::log(),555			vec![556				(root(), 2600u32),557				(root(), 69u32),558				(root(), 42u32),559				(root(), 3u32)560			]561		);562563		// Will contain none564		let actual_weight = Scheduler::on_initialize(4);565		assert_eq!(566			actual_weight,567			TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)568		);569	});570}571572#[test]573fn root_calls_works() {574	new_test_ext().execute_with(|| {575		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {576			i: 69,577			weight: Weight::from_ref_time(10),578		}));579		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {580			i: 42,581			weight: Weight::from_ref_time(10),582		}));583		assert_ok!(Scheduler::schedule_named(584			RuntimeOrigin::root(),585			[1u8; 32],586			4,587			None,588			Some(127),589			call,590		));591		assert_ok!(Scheduler::schedule(592			RuntimeOrigin::root(),593			4,594			None,595			Some(127),596			call2597		));598		run_to_block(3);599		// Scheduled calls are in the agenda.600		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);601		assert!(logger::log().is_empty());602		assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));603		assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));604		// Scheduled calls are made NONE, so should not effect state605		run_to_block(100);606		assert!(logger::log().is_empty());607	});608}609610#[test]611fn fails_to_schedule_task_in_the_past() {612	new_test_ext().execute_with(|| {613		run_to_block(3);614615		let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {616			i: 69,617			weight: Weight::from_ref_time(10),618		}));619		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {620			i: 42,621			weight: Weight::from_ref_time(10),622		}));623		let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {624			i: 42,625			weight: Weight::from_ref_time(10),626		}));627628		assert_noop!(629			Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),630			Error::<Test>::TargetBlockNumberInPast,631		);632633		assert_noop!(634			Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),635			Error::<Test>::TargetBlockNumberInPast,636		);637638		assert_noop!(639			Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),640			Error::<Test>::TargetBlockNumberInPast,641		);642	});643}644645#[test]646fn should_use_origin() {647	new_test_ext().execute_with(|| {648		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {649			i: 69,650			weight: Weight::from_ref_time(10),651		}));652		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {653			i: 42,654			weight: Weight::from_ref_time(10),655		}));656		assert_ok!(Scheduler::schedule_named(657			system::RawOrigin::Signed(1).into(),658			[1u8; 32],659			4,660			None,661			None,662			call,663		));664		assert_ok!(Scheduler::schedule(665			system::RawOrigin::Signed(1).into(),666			4,667			None,668			None,669			call2,670		));671		run_to_block(3);672		// Scheduled calls are in the agenda.673		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);674		assert!(logger::log().is_empty());675		assert_ok!(Scheduler::cancel_named(676			system::RawOrigin::Signed(1).into(),677			[1u8; 32]678		));679		assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));680		// Scheduled calls are made NONE, so should not effect state681		run_to_block(100);682		assert!(logger::log().is_empty());683	});684}685686#[test]687fn should_check_origin() {688	new_test_ext().execute_with(|| {689		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {690			i: 69,691			weight: Weight::from_ref_time(10),692		}));693		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {694			i: 42,695			weight: Weight::from_ref_time(10),696		}));697		assert_noop!(698			Scheduler::schedule_named(699				system::RawOrigin::Signed(2).into(),700				[1u8; 32],701				4,702				None,703				None,704				call705			),706			BadOrigin707		);708		assert_noop!(709			Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),710			BadOrigin711		);712	});713}714715#[test]716fn should_check_origin_for_cancel() {717	new_test_ext().execute_with(|| {718		let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {719			i: 69,720			weight: Weight::from_ref_time(10),721		}));722		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {723			i: 42,724			weight: Weight::from_ref_time(10),725		}));726		assert_ok!(Scheduler::schedule_named(727			system::RawOrigin::Signed(1).into(),728			[1u8; 32],729			4,730			None,731			None,732			call,733		));734		assert_ok!(Scheduler::schedule(735			system::RawOrigin::Signed(1).into(),736			4,737			None,738			None,739			call2,740		));741		run_to_block(3);742		// Scheduled calls are in the agenda.743		assert_eq!(Agenda::<Test>::get(4).agenda.len(), 2);744		assert!(logger::log().is_empty());745		assert_noop!(746			Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),747			BadOrigin748		);749		assert_noop!(750			Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),751			BadOrigin752		);753		assert_noop!(754			Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),755			BadOrigin756		);757		assert_noop!(758			Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),759			BadOrigin760		);761		run_to_block(5);762		assert_eq!(763			logger::log(),764			vec![765				(system::RawOrigin::Signed(1).into(), 69u32),766				(system::RawOrigin::Signed(1).into(), 42u32)767			]768		);769	});770}771772/// Cancelling a call and then scheduling a second call for the same773/// block results in different addresses.774#[test]775fn schedule_does_not_resuse_addr() {776	new_test_ext().execute_with(|| {777		let call = RuntimeCall::Logger(LoggerCall::log {778			i: 42,779			weight: Weight::from_ref_time(10),780		});781782		// Schedule both calls.783		let addr_1 = Scheduler::do_schedule(784			DispatchTime::At(4),785			None,786			127,787			root(),788			<ScheduledCall<Test>>::new(call.clone()).unwrap(),789		)790		.unwrap();791		// Cancel the call.792		assert_ok!(Scheduler::do_cancel(None, addr_1));793		let addr_2 = Scheduler::do_schedule(794			DispatchTime::At(4),795			None,796			127,797			root(),798			<ScheduledCall<Test>>::new(call).unwrap(),799		)800		.unwrap();801802		// Should not re-use the address.803		assert!(addr_1 != addr_2);804	});805}806807#[test]808fn schedule_agenda_overflows() {809	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();810811	new_test_ext().execute_with(|| {812		let call = RuntimeCall::Logger(LoggerCall::log {813			i: 42,814			weight: Weight::from_ref_time(10),815		});816		let call = <ScheduledCall<Test>>::new(call).unwrap();817818		// Schedule the maximal number allowed per block.819		for _ in 0..max {820			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();821		}822823		// One more time and it errors.824		assert_noop!(825			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),826			<Error<Test>>::AgendaIsExhausted,827		);828829		run_to_block(4);830		// All scheduled calls are executed.831		assert_eq!(logger::log().len() as u32, max);832	});833}834835/// Cancelling and scheduling does not overflow the agenda but fills holes.836#[test]837fn cancel_and_schedule_fills_holes() {838	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();839	assert!(840		max > 3,841		"This test only makes sense for MaxScheduledPerBlock > 3"842	);843844	new_test_ext().execute_with(|| {845		let call = RuntimeCall::Logger(LoggerCall::log {846			i: 42,847			weight: Weight::from_ref_time(10),848		});849		let call = <ScheduledCall<Test>>::new(call).unwrap();850		let mut addrs = Vec::<_>::default();851852		// Schedule the maximal number allowed per block.853		for _ in 0..max {854			addrs.push(855				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())856					.unwrap(),857			);858		}859		// Cancel three of them.860		for addr in addrs.into_iter().take(3) {861			Scheduler::do_cancel(None, addr).unwrap();862		}863		// Schedule three new ones.864		for i in 0..3 {865			let (_block, index) =866				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())867					.unwrap();868			assert_eq!(i, index);869		}870871		run_to_block(4);872		// Maximum number of calls are executed.873		assert_eq!(logger::log().len() as u32, max);874	});875}876877#[test]878fn cannot_schedule_too_big_tasks() {879	new_test_ext().execute_with(|| {880		let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {881			remark: vec![0; EncodedCall::bound() - 4],882		}));883884		assert_ok!(Scheduler::schedule(885			RuntimeOrigin::root(),886			4,887			None,888			Some(127),889			call890		));891892		let call = Box::new(<<Test as Config>::RuntimeCall>::from(SystemCall::remark {893			remark: vec![0; EncodedCall::bound() - 3],894		}));895896		assert_err!(897			Scheduler::schedule(RuntimeOrigin::root(), 4, None, Some(127), call),898			<Error<Test>>::TooBigScheduledCall899		);900	});901}
deletedpallets/scheduler-v2/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/weights.rs
+++ /dev/null
@@ -1,234 +0,0 @@
-// 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))
-	}
-}
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -329,7 +329,6 @@
 pallet-refungible = { workspace = true }
 pallet-structure = { workspace = true }
 pallet-unique = { workspace = true }
-pallet-unique-scheduler-v2 = { workspace = true }
 precompile-utils-macro = { workspace = true }
 scale-info = { workspace = true }
 up-common = { workspace = true }
modifiedtest-pallets/utils/Cargo.tomldiffbeforeafterboth
--- a/test-pallets/utils/Cargo.toml
+++ b/test-pallets/utils/Cargo.toml
@@ -12,8 +12,6 @@
 frame-support = { workspace = true }
 frame-system = { workspace = true }
 scale-info = { workspace = true }
-# pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
-pallet-unique-scheduler-v2 = { workspace = true }
 sp-std = { workspace = true }
 
 [features]
@@ -22,7 +20,6 @@
 	"codec/std",
 	"frame-support/std",
 	"frame-system/std",
-	"pallet-unique-scheduler-v2/std",
 	"scale-info/std",
 	"sp-std/std",
 ]
modifiedtest-pallets/utils/src/lib.rsdiffbeforeafterboth
--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -29,7 +29,6 @@
 	};
 	use frame_system::pallet_prelude::*;
 	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_v2::Config*/ {