git.delta.rocks / unique-network / refs/commits / 3151280b2e6d

difftreelog

Merge pull request #376 from UniqueNetwork/fix/scheduler-benchmarks

kozyrevdev2022-06-10parents: #030f1f6 #35be72c.patch.diff
in: master
Fix/scheduler benchmarks

14 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5356,7 +5356,7 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unq-scheduler",
+ "pallet-unique-scheduler",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.1.2",
@@ -6646,7 +6646,7 @@
 ]
 
 [[package]]
-name = "pallet-unq-scheduler"
+name = "pallet-unique-scheduler"
 version = "0.1.0"
 dependencies = [
  "frame-benchmarking",
@@ -8590,7 +8590,7 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unq-scheduler",
+ "pallet-unique-scheduler",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.1.2",
@@ -12643,7 +12643,7 @@
  "pallet-transaction-payment-rpc-runtime-api",
  "pallet-treasury",
  "pallet-unique",
- "pallet-unq-scheduler",
+ "pallet-unique-scheduler",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.1.2",
@@ -12688,6 +12688,7 @@
  "pallet-nonfungible",
  "pallet-refungible",
  "pallet-unique",
+ "pallet-unique-scheduler",
  "parity-scale-codec 3.1.2",
  "rmrk-rpc",
  "scale-info",
modifiedMakefilediffbeforeafterboth
--- a/Makefile
+++ b/Makefile
@@ -65,6 +65,14 @@
 	--template .maintain/frame-weight-template.hbs --steps=50 --repeat=200 --heap-pages=4096 \
 	--output=./pallets/$(PALLET)/src/weights.rs
 
+.PHONY: _bench2
+_bench2:
+	cargo run --release --features runtime-benchmarks,unique-runtime -- \
+	benchmark pallet --pallet pallet-$(PALLET) \
+	--wasm-execution compiled --extrinsic '*' \
+	--template .maintain/frame-weight-template.hbs --steps=50 --repeat=200 --heap-pages=4096 \
+	--output=./pallets/$(PALLET_DIR)/src/weights.rs
+
 .PHONY: bench-evm-migration
 bench-evm-migration:
 	make _bench PALLET=evm-migration
@@ -93,9 +101,13 @@
 bench-structure:
 	make _bench PALLET=structure
 
+.PHONY: bench-scheduler
+bench-scheduler:
+	make _bench2 PALLET=unique-scheduler PALLET_DIR=scheduler
+
 .PHONY: bench-rmrk-core
 bench-rmrk-core:
 	make _bench PALLET=proxy-rmrk-core
 
 .PHONY: bench
-bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-rmrk-core
+bench: bench-evm-migration bench-unique bench-structure bench-fungible bench-refungible bench-nonfungible bench-scheduler bench-rmrk-core
modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -1,5 +1,5 @@
 [package]
-name = "pallet-unq-scheduler"
+name = "pallet-unique-scheduler"
 version = "0.1.0"
 authors = ["Unique Network <support@uniquenetwork.io>"]
 edition = "2021"
modifiedpallets/scheduler/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/benchmarking.rs
+++ b/pallets/scheduler/src/benchmarking.rs
@@ -34,35 +34,57 @@
 
 //! Scheduler pallet benchmarking.
 
-#![cfg(feature = "runtime-benchmarks")]
-
 use super::*;
-use sp_std::{vec, prelude::*};
+use frame_benchmarking::{benchmarks, account};
+use frame_support::{
+	ensure,
+	traits::{OnInitialize},
+};
 use frame_system::RawOrigin;
-use frame_support::{ensure, traits::OnInitialize};
-use frame_benchmarking::{benchmarks, impl_benchmark_test_suite};
+use sp_runtime::traits::Hash;
+use sp_std::{prelude::*, vec};
 
-use crate::Module as Scheduler;
+use crate::Pallet as Scheduler;
 use frame_system::Pallet as System;
+use frame_support::traits::Currency;
 
 const BLOCK_NUMBER: u32 = 2;
 
-// Add `n` named items to the schedule
-fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {
-	// Essentially a no-op call.
-	let call = frame_system::Call::set_storage { items: vec![] };
+/// Add `n` named items to the schedule.
+///
+/// For `resolved`:
+/// - `None`: aborted (hash without preimage)
+/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
+/// - `Some(false)`: plain call
+fn fill_schedule<T: Config>(
+	when: T::BlockNumber,
+	n: u32,
+	periodic: bool,
+	resolved: Option<bool>,
+) -> Result<(), &'static str> {
+	let t = DispatchTime::At(when);
+	let caller = account("user", 0, 1);
+
+	// Give the sender account max funds for transfer (their account will never reasonably be killed).
+	T::Currency::make_free_balance_be(&caller, T::Currency::minimum_balance());
+
 	for i in 0..n {
-		// Named schedule is strictly heavier than anonymous
-		Scheduler::<T>::do_schedule_named(
-			i.encode(),
-			DispatchTime::At(when),
-			// Add periodicity
-			Some((T::BlockNumber::one(), 100)),
-			// HARD_DEADLINE priority means it gets executed no matter what
-			0,
-			frame_system::RawOrigin::Root.into(),
-			call.clone().into(),
-		)?;
+		let (call, hash) = call_and_hash::<T>(i);
+		let call_or_hash = match resolved {
+			Some(_) => call.into(),
+			None => CallOrHashOf::<T>::Hash(hash),
+		};
+		let period = match periodic {
+			true => Some(((i + 100).into(), 100)),
+			false => None,
+		};
+
+		let slice_id: [u8; 4] = i.encode().try_into().unwrap();
+		let mut id: [u8; 16] = [0; 16];
+		id[..4].clone_from_slice(&slice_id);
+
+		let origin = frame_system::RawOrigin::Signed(caller.clone()).into();
+		Scheduler::<T>::do_schedule_named(id, t, period, 0, origin, call_or_hash)?;
 	}
 	ensure!(
 		Agenda::<T>::get(when).len() == n as usize,
@@ -71,54 +93,121 @@
 	Ok(())
 }
 
+fn call_and_hash<T: Config>(i: u32) -> (<T as Config>::Call, T::Hash) {
+	// Essentially a no-op call.
+	let call: <T as Config>::Call = frame_system::Call::remark { remark: i.encode() }.into();
+	let hash = T::Hashing::hash_of(&call);
+	(call, hash)
+}
+
 benchmarks! {
-	schedule {
-		let s in 0 .. T::MaxScheduledPerBlock::get();
+	on_initialize_periodic_named_resolved {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
 		let when = BLOCK_NUMBER.into();
-		let periodic = Some((T::BlockNumber::one(), 100));
-		let priority = 0;
-		// Essentially a no-op call.
-		let call = Box::new(frame_system::Call::set_storage { items: vec![] }.into());
+		fill_schedule::<T>(when, s, true, Some(true))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+		assert_eq!(System::<T>::event_count(), s);
+		for i in 0..s {
+			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
+		}
+	}
 
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, when, periodic, priority, call)
+	on_initialize_named_resolved {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, Some(true))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
 	verify {
-		ensure!(
-			Agenda::<T>::get(when).len() == (s + 1) as usize,
-			"didn't add to schedule"
-		);
+		assert_eq!(System::<T>::event_count(), s);
+		assert!(Agenda::<T>::iter().count() == 0);
 	}
 
-	cancel {
+	on_initialize_periodic {
 		let s in 1 .. T::MaxScheduledPerBlock::get();
 		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, true, Some(false))?;
+	}: { Scheduler::<T>::on_initialize(when); }
+	verify {
+		assert_eq!(System::<T>::event_count(), s);
+		for i in 0..s {
+			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
+		}
+	}
 
-		fill_schedule::<T>(when, s)?;
-		assert_eq!(Agenda::<T>::get(when).len(), s as usize);
-	}: _(RawOrigin::Root, when, 0)
+	on_initialize_periodic_resolved {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, true, Some(true))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
 	verify {
-		ensure!(
-			Lookup::<T>::get(0.encode()).is_none(),
-			"didn't remove from lookup"
-		);
-		// Removed schedule is NONE
-		ensure!(
-			Agenda::<T>::get(when)[0].is_none(),
-			"didn't remove from schedule"
-		);
+		assert_eq!(System::<T>::event_count(), s );
+		for i in 0..s {
+			assert_eq!(Agenda::<T>::get(when + (i + 100).into()).len(), 1 as usize);
+		}
 	}
 
+	on_initialize_aborted {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, None)?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+		assert_eq!(System::<T>::event_count(), 0);
+	}
+
+	on_initialize_named_aborted {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, Some(false))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+	}
+
+	on_initialize_named {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, None)?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+		assert_eq!(System::<T>::event_count(), 0);
+	}
+
+	on_initialize {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, Some(false))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+		assert_eq!(System::<T>::event_count(), s);
+		assert!(Agenda::<T>::iter().count() == 0);
+	}
+
+	on_initialize_resolved {
+		let s in 1 .. T::MaxScheduledPerBlock::get();
+		let when = BLOCK_NUMBER.into();
+		fill_schedule::<T>(when, s, false, Some(true))?;
+	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
+	verify {
+		assert_eq!(System::<T>::event_count(), s);
+		assert!(Agenda::<T>::iter().count() == 0);
+	}
+
 	schedule_named {
+		let caller: T::AccountId = account("user", 0, 1);
+		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
 		let s in 0 .. T::MaxScheduledPerBlock::get();
-		let id = s.encode();
+		let slice_id: [u8; 4] = s.encode().try_into().unwrap();
+		let mut id: [u8; 16] =  [0; 16];
+		id[..4].clone_from_slice(&slice_id);
 		let when = BLOCK_NUMBER.into();
 		let periodic = Some((T::BlockNumber::one(), 100));
 		let priority = 0;
 		// Essentially a no-op call.
-		let call = Box::new(frame_system::Call::set_storage { items: vec![] }.into());
-
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, id, when, periodic, priority, call)
+		let inner_call = frame_system::Call::set_storage { items: vec![] }.into();
+		let call = Box::new(CallOrHashOf::<T>::Value(inner_call));
+		fill_schedule::<T>(when, s, true, Some(false))?;
+	}: _(origin, id, when, periodic, priority, call)
 	verify {
 		ensure!(
 			Agenda::<T>::get(when).len() == (s + 1) as usize,
@@ -127,14 +216,16 @@
 	}
 
 	cancel_named {
+		let caller: T::AccountId = account("user", 0, 1);
+		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Signed(caller.clone());
 		let s in 1 .. T::MaxScheduledPerBlock::get();
 		let when = BLOCK_NUMBER.into();
-
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, 0.encode())
+		let id = 0.encode().try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+		fill_schedule::<T>(when, s, true, Some(false))?;
+	}: _(origin, id)
 	verify {
 		ensure!(
-			Lookup::<T>::get(0.encode()).is_none(),
+			Lookup::<T>::get(id).is_none(),
 			"didn't remove from lookup"
 		);
 		// Removed schedule is NONE
@@ -144,21 +235,5 @@
 		);
 	}
 
-	// TODO [#7141]: Make this more complex and flexible so it can be used in automation.
-	#[extra]
-	on_initialize {
-		let s in 0 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		fill_schedule::<T>(when, s)?;
-	}: { Scheduler::<T>::on_initialize(BLOCK_NUMBER.into()); }
-	verify {
-		assert_eq!(System::<T>::event_count(), s);
-		// Next block should have all the schedules again
-		ensure!(
-			Agenda::<T>::get(when + T::BlockNumber::one()).len() == s as usize,
-			"didn't append schedule"
-		);
-	}
+	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
 }
-
-impl_benchmark_test_suite!(Scheduler, crate::tests::new_test_ext(), crate::tests::Test,);
modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Schedulerdo_reschedule36//!37//! This Pallet exposes capabilities for scheduling dispatches to occur at a38//! specified block number or at a specified period. These scheduled dispatches39//! may be named or anonymous and may be canceled.40//!41//! **NOTE:** The scheduled calls will be dispatched with the default filter42//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin43//! except root which will get no filter. And not the filter contained in origin44//! use to call `fn schedule`.45//!46//! If a call is scheduled using proxy or whatever mecanism which adds filter,47//! then those filter will not be used when dispatching the schedule call.48//!49//! ## Interface50//!51//! ### Dispatchable Functions52//!53//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and54//!   with a specified priority.55//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.56//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter57//!   that can be used for identification.58//! * `cancel_named` - the named complement to the cancel function.5960// Ensure we're `no_std` when compiling for Wasm.61#![cfg_attr(not(feature = "std"), no_std)]6263// FIXME64// #[cfg(feature = "runtime-benchmarks")]65// mod benchmarking;6667pub mod weights;6869use sp_core::H160;70use codec::{Codec, Decode, Encode};71use frame_system::{self as system, ensure_signed};72pub use pallet::*;73use scale_info::TypeInfo;74use sp_runtime::{75	traits::{BadOrigin, One, Saturating, Zero},76	RuntimeDebug, DispatchErrorWithPostInfo,77};78use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7980use frame_support::{81	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},82	traits::{83		schedule::{self, DispatchTime, MaybeHashed},84		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,85		StorageVersion,86	},87	weights::{GetDispatchInfo, Weight},88};8990pub use weights::WeightInfo;9192/// Just a simple index for naming period tasks.93pub type PeriodicIndex = u32;94/// The location of a scheduled task that can be used to remove it.95pub type TaskAddress<BlockNumber> = (BlockNumber, u32);96pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9798type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];99pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;100101/// Information regarding an item to be executed in the future.102#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]103#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]104pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {105	/// The unique identity for this task, if there is one.106	maybe_id: Option<ScheduledId>,107	/// This task's priority.108	priority: schedule::Priority,109	/// The call to be dispatched.110	call: Call,111	/// If the call is periodic, then this points to the information concerning that.112	maybe_periodic: Option<schedule::Period<BlockNumber>>,113	/// The origin to dispatch the call.114	origin: PalletsOrigin,115	_phantom: PhantomData<AccountId>,116}117118pub type ScheduledV3Of<T> = ScheduledV3<119	CallOrHashOf<T>,120	<T as frame_system::Config>::BlockNumber,121	<T as Config>::PalletsOrigin,122	<T as frame_system::Config>::AccountId,123>;124125pub type ScheduledOf<T> = ScheduledV3Of<T>;126127/// The current version of Scheduled struct.128pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =129	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;130131#[cfg(feature = "runtime-benchmarks")]132mod preimage_provider {133	use frame_support::traits::PreimageRecipient;134	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}135	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}136}137138#[cfg(not(feature = "runtime-benchmarks"))]139mod preimage_provider {140	use frame_support::traits::PreimageProvider;141	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}142	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}143}144145pub use preimage_provider::PreimageProviderAndMaybeRecipient;146147pub(crate) trait MarginalWeightInfo: WeightInfo {148	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {149		match (periodic, named, resolved) {150			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),151			(_, true, None) => {152				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)153			}154			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),155			(false, true, Some(false)) => {156				Self::on_initialize_named(2) - Self::on_initialize_named(1)157			}158			(true, false, Some(false)) => {159				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)160			}161			(true, true, Some(false)) => {162				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)163			}164			(false, false, Some(true)) => {165				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)166			}167			(false, true, Some(true)) => {168				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)169			}170			(true, false, Some(true)) => {171				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)172			}173			(true, true, Some(true)) => {174				Self::on_initialize_periodic_named_resolved(2)175					- Self::on_initialize_periodic_named_resolved(1)176			}177		}178	}179}180impl<T: WeightInfo> MarginalWeightInfo for T {}181182#[frame_support::pallet]183pub mod pallet {184	use super::*;185	use frame_support::{186		dispatch::PostDispatchInfo,187		pallet_prelude::*,188		traits::{schedule::LookupError, PreimageProvider},189	};190	use frame_system::pallet_prelude::*;191192	/// The current storage version.193	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);194195	#[pallet::pallet]196	#[pallet::generate_store(pub(super) trait Store)]197	#[pallet::storage_version(STORAGE_VERSION)]198	#[pallet::without_storage_info]199	pub struct Pallet<T>(_);200201	/// `system::Config` should always be included in our implied traits.202	#[pallet::config]203	pub trait Config: frame_system::Config {204		/// The overarching event type.205		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;206207		/// The aggregated origin which the dispatch will take.208		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>209			+ From<Self::PalletsOrigin>210			+ IsType<<Self as system::Config>::Origin>;211212		/// The caller origin, overarching type of all pallets origins.213		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;214215		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;216217		/// The aggregated call type.218		type Call: Parameter219			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>220			+ GetDispatchInfo221			+ From<system::Call<Self>>;222223		/// The maximum weight that may be scheduled per block for any dispatchables of less224		/// priority than `schedule::HARD_DEADLINE`.225		#[pallet::constant]226		type MaximumWeight: Get<Weight>;227228		/// Required origin to schedule or cancel calls.229		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;230231		/// Compare the privileges of origins.232		///233		/// This will be used when canceling a task, to ensure that the origin that tries234		/// to cancel has greater or equal privileges as the origin that created the scheduled task.235		///236		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can237		/// be used. This will only check if two given origins are equal.238		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;239240		/// The maximum number of scheduled calls in the queue for a single block.241		/// Not strictly enforced, but used for weight estimation.242		#[pallet::constant]243		type MaxScheduledPerBlock: Get<u32>;244245		/// Weight information for extrinsics in this pallet.246		type WeightInfo: WeightInfo;247248		/// The preimage provider with which we look up call hashes to get the call.249		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;250251		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.252		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;253254		/// Sponsoring function.255		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;256257		/// The helper type used for custom transaction fee logic.258		type CallExecutor: DispatchCall<Self, H160>;259	}260261	/// A Scheduler-Runtime interface for finer payment handling.262	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {263		fn reserve_balance(264			id: ScheduledId,265			sponsor: <T as frame_system::Config>::AccountId,266			call: <T as Config>::Call,267			count: u32,268		) -> Result<(), DispatchError>;269270		fn pay_for_call(271			id: ScheduledId,272			sponsor: <T as frame_system::Config>::AccountId,273			call: <T as Config>::Call,274		) -> Result<u128, DispatchError>;275276		/// Resolve the call dispatch, including any post-dispatch operations.277		fn dispatch_call(278			signer: T::AccountId,279			function: <T as Config>::Call,280		) -> Result<281			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,282			TransactionValidityError,283		>;284285		fn cancel_reserve(286			id: ScheduledId,287			sponsor: <T as frame_system::Config>::AccountId,288		) -> Result<u128, DispatchError>;289	}290291	/// Items to be executed, indexed by the block number that they should be executed on.292	#[pallet::storage]293	pub type Agenda<T: Config> =294		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;295296	/// Lookup from identity to the block number and index of the task.297	#[pallet::storage]298	pub(crate) type Lookup<T: Config> =299		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;300301	/// Events type.302	#[pallet::event]303	#[pallet::generate_deposit(pub(super) fn deposit_event)]304	pub enum Event<T: Config> {305		/// Scheduled some task.306		Scheduled { when: T::BlockNumber, index: u32 },307		/// Canceled some task.308		Canceled { when: T::BlockNumber, index: u32 },309		/// Dispatched some task.310		Dispatched {311			task: TaskAddress<T::BlockNumber>,312			id: Option<ScheduledId>,313			result: DispatchResult,314		},315		/// The call for the provided hash was not found so the task has been aborted.316		CallLookupFailed {317			task: TaskAddress<T::BlockNumber>,318			id: Option<ScheduledId>,319			error: LookupError,320		},321	}322323	#[pallet::error]324	pub enum Error<T> {325		/// Failed to schedule a call326		FailedToSchedule,327		/// Cannot find the scheduled call.328		NotFound,329		/// Given target block number is in the past.330		TargetBlockNumberInPast,331		/// Reschedule failed because it does not change scheduled time.332		RescheduleNoChange,333	}334335	#[pallet::hooks]336	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {337		/// Execute the scheduled calls338		fn on_initialize(now: T::BlockNumber) -> Weight {339			let limit = T::MaximumWeight::get();340341			let mut queued = Agenda::<T>::take(now)342				.into_iter()343				.enumerate()344				.filter_map(|(index, s)| Some((index as u32, s?)))345				.collect::<Vec<_>>();346347			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {348				log::warn!(349					target: "runtime::scheduler",350					"Warning: This block has more items queued in Scheduler than \351					expected from the runtime configuration. An update might be needed."352				);353			}354355			queued.sort_by_key(|(_, s)| s.priority);356357			let next = now + One::one();358359			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);360			for (order, (index, mut s)) in queued.into_iter().enumerate() {361				let named = if let Some(ref id) = s.maybe_id {362					Lookup::<T>::remove(id);363					true364				} else {365					false366				};367368				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();369				s.call = call;370371				let resolved = if let Some(completed) = maybe_completed {372					T::PreimageProvider::unrequest_preimage(&completed);373					true374				} else {375					false376				};377				let call = match s.call.as_value().cloned() {378					Some(c) => c,379					None => {380						// Preimage not available - postpone until some block.381						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));382						if let Some(delay) = T::NoPreimagePostponement::get() {383							let until = now.saturating_add(delay);384							if let Some(ref id) = s.maybe_id {385								let index = Agenda::<T>::decode_len(until).unwrap_or(0);386								Lookup::<T>::insert(id, (until, index as u32));387							}388							Agenda::<T>::append(until, Some(s));389						}390						continue;391					}392				};393394				let periodic = s.maybe_periodic.is_some();395				let call_weight = call.get_dispatch_info().weight;396				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));397				let origin =398					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())399						.into();400				if ensure_signed(origin).is_ok() {401					// Weights of Signed dispatches expect their signing account to be whitelisted.402					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));403				}404405				// We allow a scheduled call if any is true:406				// - It's priority is `HARD_DEADLINE`407				// - It does not push the weight past the limit.408				// - It is the first item in the schedule409				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;410				let test_weight = total_weight411					.saturating_add(call_weight)412					.saturating_add(item_weight);413				if !hard_deadline && order > 0 && test_weight > limit {414					// Cannot be scheduled this block - postpone until next.415					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));416					if let Some(ref id) = s.maybe_id {417						// NOTE: We could reasonably not do this (in which case there would be one418						// block where the named and delayed item could not be referenced by name),419						// but we will do it anyway since it should be mostly free in terms of420						// weight and it is slightly cleaner.421						let index = Agenda::<T>::decode_len(next).unwrap_or(0);422						Lookup::<T>::insert(id, (next, index as u32));423					}424					Agenda::<T>::append(next, Some(s));425					continue;426				}427428				let sender = ensure_signed(429					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())430						.into(),431				)432				.unwrap();433434				// // if call have id it was be reserved435				// if s.maybe_id.is_some() {436				// 	let _ = T::CallExecutor::pay_for_call(437				// 		s.maybe_id.unwrap(),438				// 		sender.clone(),439				// 		call.clone(),440				// 	);441				// }442443				let r = T::CallExecutor::dispatch_call(sender, call.clone());444445				let mut actual_call_weight: Weight = item_weight;446				let result: Result<_, DispatchError> = match r {447					Ok(o) => match o {448						Ok(di) => {449							actual_call_weight = di.actual_weight.unwrap_or(item_weight);450							Ok(())451						}452						Err(err) => Err(err.error),453					},454					Err(_) => {455						log::error!(456							target: "runtime::scheduler",457							"Warning: Scheduler has failed to execute a post-dispatch transaction. \458							This block might have become invalid.");459						Err(DispatchError::CannotLookup)460					} // todo possibly force a skip/return here, do something with the error461				};462463				total_weight.saturating_accrue(item_weight);464				total_weight.saturating_accrue(actual_call_weight);465466				Self::deposit_event(Event::Dispatched {467					task: (now, index),468					id: s.maybe_id.clone(),469					result,470				});471472				if let &Some((period, count)) = &s.maybe_periodic {473					if count > 1 {474						s.maybe_periodic = Some((period, count - 1));475					} else {476						s.maybe_periodic = None;477					}478					let wake = now + period;479					// If scheduled is named, place its information in `Lookup`480					if let Some(ref id) = s.maybe_id {481						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);482						Lookup::<T>::insert(id, (wake, wake_index as u32));483					}484					Agenda::<T>::append(wake, Some(s));485				}486			}487			0488			//total_weight489		}490	}491492	#[pallet::call]493	impl<T: Config> Pallet<T> {494		/// Schedule a named task.495		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]496		pub fn schedule_named(497			origin: OriginFor<T>,498			id: ScheduledId,499			when: T::BlockNumber,500			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,501			priority: schedule::Priority,502			call: Box<CallOrHashOf<T>>,503		) -> DispatchResult {504			T::ScheduleOrigin::ensure_origin(origin.clone())?;505			let origin = <T as Config>::Origin::from(origin);506			Self::do_schedule_named(507				id,508				DispatchTime::At(when),509				maybe_periodic,510				priority,511				origin.caller().clone(),512				*call,513			)?;514			Ok(())515		}516517		/// Cancel a named scheduled task.518		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]519		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {520			T::ScheduleOrigin::ensure_origin(origin.clone())?;521			let origin = <T as Config>::Origin::from(origin);522			Self::do_cancel_named(Some(origin.caller().clone()), id)?;523			Ok(())524		}525526		/// Schedule a named task after a delay.527		///528		/// # <weight>529		/// Same as [`schedule_named`](Self::schedule_named).530		/// # </weight>531		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]532		pub fn schedule_named_after(533			origin: OriginFor<T>,534			id: ScheduledId,535			after: T::BlockNumber,536			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,537			priority: schedule::Priority,538			call: Box<CallOrHashOf<T>>,539		) -> DispatchResult {540			T::ScheduleOrigin::ensure_origin(origin.clone())?;541			let origin = <T as Config>::Origin::from(origin);542			Self::do_schedule_named(543				id,544				DispatchTime::After(after),545				maybe_periodic,546				priority,547				origin.caller().clone(),548				*call,549			)?;550			Ok(())551		}552	}553}554555impl<T: Config> Pallet<T> {556	#[cfg(feature = "try-runtime")]557	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {558		Ok(())559	}560561	#[cfg(feature = "try-runtime")]562	pub fn post_migrate_to_v3() -> Result<(), &'static str> {563		use frame_support::dispatch::GetStorageVersion;564565		assert!(Self::current_storage_version() == 3);566		for k in Agenda::<T>::iter_keys() {567			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;568		}569		Ok(())570	}571572	/// Helper to migrate scheduler when the pallet origin type has changed.573	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {574		Agenda::<T>::translate::<575			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,576			_,577		>(|_, agenda| {578			Some(579				agenda580					.into_iter()581					.map(|schedule| {582						schedule.map(|schedule| Scheduled {583							maybe_id: schedule.maybe_id,584							priority: schedule.priority,585							call: schedule.call,586							maybe_periodic: schedule.maybe_periodic,587							origin: schedule.origin.into(),588							_phantom: Default::default(),589						})590					})591					.collect::<Vec<_>>(),592			)593		});594	}595596	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {597		let now = frame_system::Pallet::<T>::block_number();598599		let when = match when {600			DispatchTime::At(x) => x,601			// The current block has already completed it's scheduled tasks, so602			// Schedule the task at lest one block after this current block.603			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),604		};605606		if when <= now {607			return Err(Error::<T>::TargetBlockNumberInPast.into());608		}609610		Ok(when)611	}612613	fn do_schedule(614		when: DispatchTime<T::BlockNumber>,615		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,616		priority: schedule::Priority,617		origin: T::PalletsOrigin,618		call: CallOrHashOf<T>,619	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {620		let when = Self::resolve_time(when)?;621		call.ensure_requested::<T::PreimageProvider>();622623		// sanitize maybe_periodic624		let maybe_periodic = maybe_periodic625			.filter(|p| p.1 > 1 && !p.0.is_zero())626			// Remove one from the number of repetitions since we will schedule one now.627			.map(|(p, c)| (p, c - 1));628		let s = Some(Scheduled {629			maybe_id: None,630			priority,631			call,632			maybe_periodic,633			origin,634			_phantom: PhantomData::<T::AccountId>::default(),635		});636		Agenda::<T>::append(when, s);637		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;638		Self::deposit_event(Event::Scheduled { when, index });639640		Ok((when, index))641	}642643	fn do_cancel(644		origin: Option<T::PalletsOrigin>,645		(when, index): TaskAddress<T::BlockNumber>,646	) -> Result<(), DispatchError> {647		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {648			agenda.get_mut(index as usize).map_or(649				Ok(None),650				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {651					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {652						if matches!(653							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),654							Some(Ordering::Less) | None655						) {656							return Err(BadOrigin.into());657						}658					};659					Ok(s.take())660				},661			)662		})?;663		if let Some(s) = scheduled {664			s.call.ensure_unrequested::<T::PreimageProvider>();665			if let Some(id) = s.maybe_id {666				Lookup::<T>::remove(id);667			}668			Self::deposit_event(Event::Canceled { when, index });669			Ok(())670		} else {671			Err(Error::<T>::NotFound)?672		}673	}674675	fn do_reschedule(676		(when, index): TaskAddress<T::BlockNumber>,677		new_time: DispatchTime<T::BlockNumber>,678	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {679		let new_time = Self::resolve_time(new_time)?;680681		if new_time == when {682			return Err(Error::<T>::RescheduleNoChange.into());683		}684685		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {686			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;687			let task = task.take().ok_or(Error::<T>::NotFound)?;688			Agenda::<T>::append(new_time, Some(task));689			Ok(())690		})?;691692		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;693		Self::deposit_event(Event::Canceled { when, index });694		Self::deposit_event(Event::Scheduled {695			when: new_time,696			index: new_index,697		});698699		Ok((new_time, new_index))700	}701702	fn do_schedule_named(703		id: ScheduledId,704		when: DispatchTime<T::BlockNumber>,705		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,706		priority: schedule::Priority,707		origin: T::PalletsOrigin,708		call: CallOrHashOf<T>,709	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {710		// ensure id it is unique711		if Lookup::<T>::contains_key(&id) {712			return Err(Error::<T>::FailedToSchedule)?;713		}714715		let when = Self::resolve_time(when)?;716717		call.ensure_requested::<T::PreimageProvider>();718719		// sanitize maybe_periodic720		let maybe_periodic = maybe_periodic721			.filter(|p| p.1 > 1 && !p.0.is_zero())722			// Remove one from the number of repetitions since we will schedule one now.723			.map(|(p, c)| (p, c - 1));724725		let s = Scheduled {726			maybe_id: Some(id.clone()),727			priority,728			call: call.clone(),729			maybe_periodic,730			origin: origin.clone(),731			_phantom: Default::default(),732		};733734		// reserve balance for periodic execution735		// let sender =736		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;737		// let repeats = match maybe_periodic {738		// 	Some(p) => p.1,739		// 	None => 1,740		// };741		// let _ = T::CallExecutor::reserve_balance(742		// 	id.clone(),743		// 	sender,744		// 	call.as_value().unwrap().clone(),745		// 	repeats,746		// );747748		Agenda::<T>::append(when, Some(s));749		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;750		let address = (when, index);751		Lookup::<T>::insert(&id, &address);752		Self::deposit_event(Event::Scheduled { when, index });753754		Ok(address)755	}756757	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {758		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {759			if let Some((when, index)) = lookup.take() {760				let i = index as usize;761				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {762					if let Some(s) = agenda.get_mut(i) {763						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {764							if matches!(765								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),766								Some(Ordering::Less) | None767							) {768								return Err(BadOrigin.into());769							}770							// release balance reserve771							// let sender = ensure_signed(772							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(773							// 		origin.unwrap(),774							// 	)775							// 	.into(),776							// )?;777							// let _ = T::CallExecutor::cancel_reserve(id, sender);778779							s.call.ensure_unrequested::<T::PreimageProvider>();780						}781						*s = None;782					}783					Ok(())784				})?;785786				Self::deposit_event(Event::Canceled { when, index });787				Ok(())788			} else {789				Err(Error::<T>::NotFound)?790			}791		})792	}793794	fn do_reschedule_named(795		id: ScheduledId,796		new_time: DispatchTime<T::BlockNumber>,797	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {798		let new_time = Self::resolve_time(new_time)?;799800		Lookup::<T>::try_mutate_exists(801			id,802			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {803				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;804805				if new_time == when {806					return Err(Error::<T>::RescheduleNoChange.into());807				}808809				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {810					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;811					let task = task.take().ok_or(Error::<T>::NotFound)?;812					Agenda::<T>::append(new_time, Some(task));813814					Ok(())815				})?;816817				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;818				Self::deposit_event(Event::Canceled { when, index });819				Self::deposit_event(Event::Scheduled {820					when: new_time,821					index: new_index,822				});823824				*lookup = Some((new_time, new_index));825826				Ok((new_time, new_index))827			},828		)829	}830}831832impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>833	for Pallet<T>834{835	type Address = TaskAddress<T::BlockNumber>;836	type Hash = T::Hash;837838	fn schedule(839		when: DispatchTime<T::BlockNumber>,840		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,841		priority: schedule::Priority,842		origin: T::PalletsOrigin,843		call: CallOrHashOf<T>,844	) -> Result<Self::Address, DispatchError> {845		Self::do_schedule(when, maybe_periodic, priority, origin, call)846	}847848	fn cancel((when, index): Self::Address) -> Result<(), ()> {849		Self::do_cancel(None, (when, index)).map_err(|_| ())850	}851852	fn reschedule(853		address: Self::Address,854		when: DispatchTime<T::BlockNumber>,855	) -> Result<Self::Address, DispatchError> {856		Self::do_reschedule(address, when)857	}858859	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {860		Agenda::<T>::get(when)861			.get(index as usize)862			.ok_or(())863			.map(|_| when)864	}865}866867impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>868	for Pallet<T>869{870	type Address = TaskAddress<T::BlockNumber>;871	type Hash = T::Hash;872873	fn schedule_named(874		id: Vec<u8>,875		when: DispatchTime<T::BlockNumber>,876		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,877		priority: schedule::Priority,878		origin: T::PalletsOrigin,879		call: CallOrHashOf<T>,880	) -> Result<Self::Address, ()> {881		let inner_id: ScheduledId = id882			.try_into()883			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);884		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)885			.map_err(|_| ())886	}887888	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {889		let inner_id: ScheduledId = id890			.try_into()891			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);892		Self::do_cancel_named(None, inner_id).map_err(|_| ())893	}894895	fn reschedule_named(896		id: Vec<u8>,897		when: DispatchTime<T::BlockNumber>,898	) -> Result<Self::Address, DispatchError> {899		let inner_id: ScheduledId = id900			.try_into()901			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);902		Self::do_reschedule_named(inner_id, when)903	}904905	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {906		let inner_id: ScheduledId = id907			.try_into()908			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);909		Lookup::<T>::get(inner_id)910			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))911			.ok_or(())912	}913}
after · pallets/scheduler/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Schedulerdo_reschedule36//!37//! This Pallet exposes capabilities for scheduling dispatches to occur at a38//! specified block number or at a specified period. These scheduled dispatches39//! may be named or anonymous and may be canceled.40//!41//! **NOTE:** The scheduled calls will be dispatched with the default filter42//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin43//! except root which will get no filter. And not the filter contained in origin44//! use to call `fn schedule`.45//!46//! If a call is scheduled using proxy or whatever mecanism which adds filter,47//! then those filter will not be used when dispatching the schedule call.48//!49//! ## Interface50//!51//! ### Dispatchable Functions52//!53//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and54//!   with a specified priority.55//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.56//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter57//!   that can be used for identification.58//! * `cancel_named` - the named complement to the cancel function.5960// Ensure we're `no_std` when compiling for Wasm.61#![cfg_attr(not(feature = "std"), no_std)]6263#[cfg(feature = "runtime-benchmarks")]64mod benchmarking;6566pub mod weights;6768use sp_core::H160;69use codec::{Codec, Decode, Encode};70use frame_system::{self as system, ensure_signed};71pub use pallet::*;72use scale_info::TypeInfo;73use sp_runtime::{74	traits::{BadOrigin, One, Saturating, Zero},75	RuntimeDebug, DispatchErrorWithPostInfo,76};77use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7879use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},81	traits::{82		schedule::{self, DispatchTime, MaybeHashed},83		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,84		StorageVersion,85	},86	weights::{GetDispatchInfo, Weight},87};8889pub use weights::WeightInfo;9091/// Just a simple index for naming period tasks.92pub type PeriodicIndex = u32;93/// The location of a scheduled task that can be used to remove it.94pub type TaskAddress<BlockNumber> = (BlockNumber, u32);95pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9697type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];98pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;99100/// Information regarding an item to be executed in the future.101#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]102#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]103pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {104	/// The unique identity for this task, if there is one.105	maybe_id: Option<ScheduledId>,106	/// This task's priority.107	priority: schedule::Priority,108	/// The call to be dispatched.109	call: Call,110	/// If the call is periodic, then this points to the information concerning that.111	maybe_periodic: Option<schedule::Period<BlockNumber>>,112	/// The origin to dispatch the call.113	origin: PalletsOrigin,114	_phantom: PhantomData<AccountId>,115}116117pub type ScheduledV3Of<T> = ScheduledV3<118	CallOrHashOf<T>,119	<T as frame_system::Config>::BlockNumber,120	<T as Config>::PalletsOrigin,121	<T as frame_system::Config>::AccountId,122>;123124pub type ScheduledOf<T> = ScheduledV3Of<T>;125126/// The current version of Scheduled struct.127pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =128	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;129130#[cfg(feature = "runtime-benchmarks")]131mod preimage_provider {132	use frame_support::traits::PreimageRecipient;133	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}134	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}135}136137#[cfg(not(feature = "runtime-benchmarks"))]138mod preimage_provider {139	use frame_support::traits::PreimageProvider;140	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}141	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}142}143144pub use preimage_provider::PreimageProviderAndMaybeRecipient;145146pub(crate) trait MarginalWeightInfo: WeightInfo {147	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {148		match (periodic, named, resolved) {149			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),150			(_, true, None) => {151				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)152			}153			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),154			(false, true, Some(false)) => {155				Self::on_initialize_named(2) - Self::on_initialize_named(1)156			}157			(true, false, Some(false)) => {158				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)159			}160			(true, true, Some(false)) => {161				Self::on_initialize_periodic_named_resolved(2)162					- Self::on_initialize_periodic_named_resolved(1)163			}164			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),165			(false, true, Some(true)) => {166				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)167			}168			(true, false, Some(true)) => {169				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)170			}171			(true, true, Some(true)) => {172				Self::on_initialize_periodic_named_resolved(2)173					- Self::on_initialize_periodic_named_resolved(1)174			}175		}176	}177}178impl<T: WeightInfo> MarginalWeightInfo for T {}179180#[frame_support::pallet]181pub mod pallet {182	use super::*;183	use frame_support::{184		dispatch::PostDispatchInfo,185		pallet_prelude::*,186		traits::{schedule::LookupError, PreimageProvider},187	};188	use frame_system::pallet_prelude::*;189190	/// The current storage version.191	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);192193	#[pallet::pallet]194	#[pallet::generate_store(pub(super) trait Store)]195	#[pallet::storage_version(STORAGE_VERSION)]196	#[pallet::without_storage_info]197	pub struct Pallet<T>(_);198199	/// `system::Config` should always be included in our implied traits.200	#[pallet::config]201	pub trait Config: frame_system::Config {202		/// The overarching event type.203		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;204205		/// The aggregated origin which the dispatch will take.206		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>207			+ From<Self::PalletsOrigin>208			+ IsType<<Self as system::Config>::Origin>;209210		/// The caller origin, overarching type of all pallets origins.211		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;212213		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;214215		/// The aggregated call type.216		type Call: Parameter217			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>218			+ GetDispatchInfo219			+ From<system::Call<Self>>;220221		/// The maximum weight that may be scheduled per block for any dispatchables of less222		/// priority than `schedule::HARD_DEADLINE`.223		#[pallet::constant]224		type MaximumWeight: Get<Weight>;225226		/// Required origin to schedule or cancel calls.227		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;228229		/// Compare the privileges of origins.230		///231		/// This will be used when canceling a task, to ensure that the origin that tries232		/// to cancel has greater or equal privileges as the origin that created the scheduled task.233		///234		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can235		/// be used. This will only check if two given origins are equal.236		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;237238		/// The maximum number of scheduled calls in the queue for a single block.239		/// Not strictly enforced, but used for weight estimation.240		#[pallet::constant]241		type MaxScheduledPerBlock: Get<u32>;242243		/// Weight information for extrinsics in this pallet.244		type WeightInfo: WeightInfo;245246		/// The preimage provider with which we look up call hashes to get the call.247		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;248249		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.250		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;251252		/// Sponsoring function.253		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;254255		/// The helper type used for custom transaction fee logic.256		type CallExecutor: DispatchCall<Self, H160>;257	}258259	/// A Scheduler-Runtime interface for finer payment handling.260	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {261		fn reserve_balance(262			id: ScheduledId,263			sponsor: <T as frame_system::Config>::AccountId,264			call: <T as Config>::Call,265			count: u32,266		) -> Result<(), DispatchError>;267268		fn pay_for_call(269			id: ScheduledId,270			sponsor: <T as frame_system::Config>::AccountId,271			call: <T as Config>::Call,272		) -> Result<u128, DispatchError>;273274		/// Resolve the call dispatch, including any post-dispatch operations.275		fn dispatch_call(276			signer: T::AccountId,277			function: <T as Config>::Call,278		) -> Result<279			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,280			TransactionValidityError,281		>;282283		fn cancel_reserve(284			id: ScheduledId,285			sponsor: <T as frame_system::Config>::AccountId,286		) -> Result<u128, DispatchError>;287	}288289	/// Items to be executed, indexed by the block number that they should be executed on.290	#[pallet::storage]291	pub type Agenda<T: Config> =292		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;293294	/// Lookup from identity to the block number and index of the task.295	#[pallet::storage]296	pub(crate) type Lookup<T: Config> =297		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;298299	/// Events type.300	#[pallet::event]301	#[pallet::generate_deposit(pub(super) fn deposit_event)]302	pub enum Event<T: Config> {303		/// Scheduled some task.304		Scheduled { when: T::BlockNumber, index: u32 },305		/// Canceled some task.306		Canceled { when: T::BlockNumber, index: u32 },307		/// Dispatched some task.308		Dispatched {309			task: TaskAddress<T::BlockNumber>,310			id: Option<ScheduledId>,311			result: DispatchResult,312		},313		/// The call for the provided hash was not found so the task has been aborted.314		CallLookupFailed {315			task: TaskAddress<T::BlockNumber>,316			id: Option<ScheduledId>,317			error: LookupError,318		},319	}320321	#[pallet::error]322	pub enum Error<T> {323		/// Failed to schedule a call324		FailedToSchedule,325		/// Cannot find the scheduled call.326		NotFound,327		/// Given target block number is in the past.328		TargetBlockNumberInPast,329		/// Reschedule failed because it does not change scheduled time.330		RescheduleNoChange,331	}332333	#[pallet::hooks]334	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {335		/// Execute the scheduled calls336		fn on_initialize(now: T::BlockNumber) -> Weight {337			let limit = T::MaximumWeight::get();338339			let mut queued = Agenda::<T>::take(now)340				.into_iter()341				.enumerate()342				.filter_map(|(index, s)| Some((index as u32, s?)))343				.collect::<Vec<_>>();344345			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {346				log::warn!(347					target: "runtime::scheduler",348					"Warning: This block has more items queued in Scheduler than \349					expected from the runtime configuration. An update might be needed."350				);351			}352353			queued.sort_by_key(|(_, s)| s.priority);354355			let next = now + One::one();356357			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);358			for (order, (index, mut s)) in queued.into_iter().enumerate() {359				let named = if let Some(ref id) = s.maybe_id {360					Lookup::<T>::remove(id);361					true362				} else {363					false364				};365366				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();367				s.call = call;368369				let resolved = if let Some(completed) = maybe_completed {370					T::PreimageProvider::unrequest_preimage(&completed);371					true372				} else {373					false374				};375				let call = match s.call.as_value().cloned() {376					Some(c) => c,377					None => {378						// Preimage not available - postpone until some block.379						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));380						if let Some(delay) = T::NoPreimagePostponement::get() {381							let until = now.saturating_add(delay);382							if let Some(ref id) = s.maybe_id {383								let index = Agenda::<T>::decode_len(until).unwrap_or(0);384								Lookup::<T>::insert(id, (until, index as u32));385							}386							Agenda::<T>::append(until, Some(s));387						}388						continue;389					}390				};391392				let periodic = s.maybe_periodic.is_some();393				let call_weight = call.get_dispatch_info().weight;394				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));395				let origin =396					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())397						.into();398				if ensure_signed(origin).is_ok() {399					// Weights of Signed dispatches expect their signing account to be whitelisted.400					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));401				}402403				// We allow a scheduled call if any is true:404				// - It's priority is `HARD_DEADLINE`405				// - It does not push the weight past the limit.406				// - It is the first item in the schedule407				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;408				let test_weight = total_weight409					.saturating_add(call_weight)410					.saturating_add(item_weight);411				if !hard_deadline && order > 0 && test_weight > limit {412					// Cannot be scheduled this block - postpone until next.413					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));414					if let Some(ref id) = s.maybe_id {415						// NOTE: We could reasonably not do this (in which case there would be one416						// block where the named and delayed item could not be referenced by name),417						// but we will do it anyway since it should be mostly free in terms of418						// weight and it is slightly cleaner.419						let index = Agenda::<T>::decode_len(next).unwrap_or(0);420						Lookup::<T>::insert(id, (next, index as u32));421					}422					Agenda::<T>::append(next, Some(s));423					continue;424				}425426				let sender = ensure_signed(427					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())428						.into(),429				)430				.unwrap();431432				// // if call have id it was be reserved433				// if s.maybe_id.is_some() {434				// 	let _ = T::CallExecutor::pay_for_call(435				// 		s.maybe_id.unwrap(),436				// 		sender.clone(),437				// 		call.clone(),438				// 	);439				// }440441				let r = T::CallExecutor::dispatch_call(sender, call.clone());442443				let mut actual_call_weight: Weight = item_weight;444				let result: Result<_, DispatchError> = match r {445					Ok(o) => match o {446						Ok(di) => {447							actual_call_weight = di.actual_weight.unwrap_or(item_weight);448							Ok(())449						}450						Err(err) => Err(err.error),451					},452					Err(_) => {453						log::error!(454							target: "runtime::scheduler",455							"Warning: Scheduler has failed to execute a post-dispatch transaction. \456							This block might have become invalid.");457						Err(DispatchError::CannotLookup)458					} // todo possibly force a skip/return here, do something with the error459				};460461				total_weight.saturating_accrue(item_weight);462				total_weight.saturating_accrue(actual_call_weight);463464				Self::deposit_event(Event::Dispatched {465					task: (now, index),466					id: s.maybe_id.clone(),467					result,468				});469470				if let &Some((period, count)) = &s.maybe_periodic {471					if count > 1 {472						s.maybe_periodic = Some((period, count - 1));473					} else {474						s.maybe_periodic = None;475					}476					let wake = now + period;477					// If scheduled is named, place its information in `Lookup`478					if let Some(ref id) = s.maybe_id {479						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);480						Lookup::<T>::insert(id, (wake, wake_index as u32));481					}482					Agenda::<T>::append(wake, Some(s));483				}484			}485			0486			//total_weight487		}488	}489490	#[pallet::call]491	impl<T: Config> Pallet<T> {492		/// Schedule a named task.493		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]494		pub fn schedule_named(495			origin: OriginFor<T>,496			id: ScheduledId,497			when: T::BlockNumber,498			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,499			priority: schedule::Priority,500			call: Box<CallOrHashOf<T>>,501		) -> DispatchResult {502			T::ScheduleOrigin::ensure_origin(origin.clone())?;503			let origin = <T as Config>::Origin::from(origin);504			Self::do_schedule_named(505				id,506				DispatchTime::At(when),507				maybe_periodic,508				priority,509				origin.caller().clone(),510				*call,511			)?;512			Ok(())513		}514515		/// Cancel a named scheduled task.516		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]517		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {518			T::ScheduleOrigin::ensure_origin(origin.clone())?;519			let origin = <T as Config>::Origin::from(origin);520			Self::do_cancel_named(Some(origin.caller().clone()), id)?;521			Ok(())522		}523524		/// Schedule a named task after a delay.525		///526		/// # <weight>527		/// Same as [`schedule_named`](Self::schedule_named).528		/// # </weight>529		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]530		pub fn schedule_named_after(531			origin: OriginFor<T>,532			id: ScheduledId,533			after: T::BlockNumber,534			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,535			priority: schedule::Priority,536			call: Box<CallOrHashOf<T>>,537		) -> DispatchResult {538			T::ScheduleOrigin::ensure_origin(origin.clone())?;539			let origin = <T as Config>::Origin::from(origin);540			Self::do_schedule_named(541				id,542				DispatchTime::After(after),543				maybe_periodic,544				priority,545				origin.caller().clone(),546				*call,547			)?;548			Ok(())549		}550	}551}552553impl<T: Config> Pallet<T> {554	#[cfg(feature = "try-runtime")]555	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {556		Ok(())557	}558559	#[cfg(feature = "try-runtime")]560	pub fn post_migrate_to_v3() -> Result<(), &'static str> {561		use frame_support::dispatch::GetStorageVersion;562563		assert!(Self::current_storage_version() == 3);564		for k in Agenda::<T>::iter_keys() {565			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;566		}567		Ok(())568	}569570	/// Helper to migrate scheduler when the pallet origin type has changed.571	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {572		Agenda::<T>::translate::<573			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,574			_,575		>(|_, agenda| {576			Some(577				agenda578					.into_iter()579					.map(|schedule| {580						schedule.map(|schedule| Scheduled {581							maybe_id: schedule.maybe_id,582							priority: schedule.priority,583							call: schedule.call,584							maybe_periodic: schedule.maybe_periodic,585							origin: schedule.origin.into(),586							_phantom: Default::default(),587						})588					})589					.collect::<Vec<_>>(),590			)591		});592	}593594	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {595		let now = frame_system::Pallet::<T>::block_number();596597		let when = match when {598			DispatchTime::At(x) => x,599			// The current block has already completed it's scheduled tasks, so600			// Schedule the task at lest one block after this current block.601			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),602		};603604		if when <= now {605			return Err(Error::<T>::TargetBlockNumberInPast.into());606		}607608		Ok(when)609	}610611	fn do_schedule_named(612		id: ScheduledId,613		when: DispatchTime<T::BlockNumber>,614		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,615		priority: schedule::Priority,616		origin: T::PalletsOrigin,617		call: CallOrHashOf<T>,618	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {619		// ensure id it is unique620		if Lookup::<T>::contains_key(&id) {621			return Err(Error::<T>::FailedToSchedule)?;622		}623624		let when = Self::resolve_time(when)?;625626		call.ensure_requested::<T::PreimageProvider>();627628		// sanitize maybe_periodic629		let maybe_periodic = maybe_periodic630			.filter(|p| p.1 > 1 && !p.0.is_zero())631			// Remove one from the number of repetitions since we will schedule one now.632			.map(|(p, c)| (p, c - 1));633634		let s = Scheduled {635			maybe_id: Some(id.clone()),636			priority,637			call: call.clone(),638			maybe_periodic,639			origin: origin.clone(),640			_phantom: Default::default(),641		};642643		// reserve balance for periodic execution644		// let sender =645		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;646		// let repeats = match maybe_periodic {647		// 	Some(p) => p.1,648		// 	None => 1,649		// };650		// let _ = T::CallExecutor::reserve_balance(651		// 	id.clone(),652		// 	sender,653		// 	call.as_value().unwrap().clone(),654		// 	repeats,655		// );656657		Agenda::<T>::append(when, Some(s));658		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;659		let address = (when, index);660		Lookup::<T>::insert(&id, &address);661		Self::deposit_event(Event::Scheduled { when, index });662663		Ok(address)664	}665666	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {667		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {668			if let Some((when, index)) = lookup.take() {669				let i = index as usize;670				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {671					if let Some(s) = agenda.get_mut(i) {672						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {673							if matches!(674								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),675								Some(Ordering::Less) | None676							) {677								return Err(BadOrigin.into());678							}679							// release balance reserve680							// let sender = ensure_signed(681							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(682							// 		origin.unwrap(),683							// 	)684							// 	.into(),685							// )?;686							// let _ = T::CallExecutor::cancel_reserve(id, sender);687688							s.call.ensure_unrequested::<T::PreimageProvider>();689						}690						*s = None;691					}692					Ok(())693				})?;694695				Self::deposit_event(Event::Canceled { when, index });696				Ok(())697			} else {698				Err(Error::<T>::NotFound)?699			}700		})701	}702}
modifiedpallets/scheduler/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler/src/weights.rs
+++ b/pallets/scheduler/src/weights.rs
@@ -1,213 +1,183 @@
-// This file is part of Substrate.
-
-// Copyright (C) 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.
+// Template adopted from https://github.com/paritytech/substrate/blob/master/.maintain/frame-weight-template.hbs
 
-//! Autogenerated weights for pallet_scheduler
+//! Autogenerated weights for pallet_unique_scheduler
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
-//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
+//! DATE: 2022-06-09, STEPS: `50`, REPEAT: 200, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
-// ./target/production/substrate
+// target/release/unique-collator
 // benchmark
-// --chain=dev
+// pallet
+// --pallet
+// pallet-unique-scheduler
+// --wasm-execution
+// compiled
+// --extrinsic
+// *
+// --template
+// .maintain/frame-weight-template.hbs
 // --steps=50
-// --repeat=20
-// --pallet=pallet_scheduler
-// --extrinsic=*
-// --execution=wasm
-// --wasm-execution=compiled
+// --repeat=200
 // --heap-pages=4096
-// --output=./frame/scheduler/src/weights.rs
-// --template=.maintain/frame-weight-template.hbs
-// --header=HEADER-APACHE2
-// --raw
+// --output=./pallets/scheduler/src/weights.rs
 
 #![cfg_attr(rustfmt, rustfmt_skip)]
 #![allow(unused_parens)]
 #![allow(unused_imports)]
+#![allow(clippy::unnecessary_cast)]
 
 use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
 use sp_std::marker::PhantomData;
 
-/// Weight functions needed for pallet_scheduler.
+/// Weight functions needed for pallet_unique_scheduler.
 pub trait WeightInfo {
 	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
 	fn on_initialize_named_resolved(s: u32, ) -> Weight;
+	fn on_initialize_periodic(s: u32, ) -> Weight;
 	fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
-	fn on_initialize_resolved(s: u32, ) -> Weight;
+	fn on_initialize_aborted(s: u32, ) -> Weight;
 	fn on_initialize_named_aborted(s: u32, ) -> Weight;
-	fn on_initialize_aborted(s: u32, ) -> Weight;
-	fn on_initialize_periodic_named(s: u32, ) -> Weight;
-	fn on_initialize_periodic(s: u32, ) -> Weight;
 	fn on_initialize_named(s: u32, ) -> Weight;
 	fn on_initialize(s: u32, ) -> Weight;
-	fn schedule(s: u32, ) -> Weight;
-	fn cancel(s: u32, ) -> Weight;
+	fn on_initialize_resolved(s: u32, ) -> Weight;
 	fn schedule_named(s: u32, ) -> Weight;
 	fn cancel_named(s: u32, ) -> Weight;
 }
 
-/// Weights for pallet_scheduler using the Substrate node and recommended hardware.
+/// Weights for pallet_unique_scheduler using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
-		(11_587_000 as Weight)
-			// Standard Error: 17_000
-			.saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+		(35_999_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((32_234_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_named_resolved(s: u32, ) -> Weight {
-		(8_965_000 as Weight)
-			// Standard Error: 11_000
-			.saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
+		(34_874_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((23_114_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
-		(8_654_000 as Weight)
-			// Standard Error: 17_000
-			.saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	fn on_initialize_resolved(s: u32, ) -> Weight {
-		(9_303_000 as Weight)
-			// Standard Error: 10_000
-			.saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic(s: u32, ) -> Weight {
+		(36_469_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((32_202_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_aborted(s: u32, ) -> Weight {
-		(7_506_000 as Weight)
+	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+		(35_352_000 as Weight)
 			// Standard Error: 3_000
-			.saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add((32_309_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
 			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(2 as Weight))
-			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_aborted(s: u32, ) -> Weight {
-		(8_046_000 as Weight)
-			// Standard Error: 3_000
-			.saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+		(11_267_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((9_368_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
-			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
-	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_periodic_named(s: u32, ) -> Weight {
-		(13_704_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	fn on_initialize_periodic(s: u32, ) -> Weight {
-		(12_668_000 as Weight)
-			// Standard Error: 5_000
-			.saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+	fn on_initialize_named_aborted(s: u32, ) -> Weight {
+		(35_937_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((23_037_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
-	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Agenda (r:2 w:2)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_named(s: u32, ) -> Weight {
-		(13_946_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+		(10_338_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((9_422_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(2 as Weight))
+			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize(s: u32, ) -> Weight {
-		(13_151_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
+		(37_448_000 as Weight)
+			// Standard Error: 7_000
+			.saturating_add((22_907_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
-	fn schedule(s: u32, ) -> Weight {
-		(14_040_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((89_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn cancel(s: u32, ) -> Weight {
-		(14_376_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((576_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(2 as Weight))
+	fn on_initialize_resolved(s: u32, ) -> Weight {
+		(34_841_000 as Weight)
+			// Standard Error: 7_000
+			.saturating_add((22_966_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(T::DbWeight::get().reads(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+			.saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Lookup (r:1 w:1)
 	// Storage: Scheduler Agenda (r:1 w:1)
 	fn schedule_named(s: u32, ) -> Weight {
-		(16_806_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+		(33_845_000 as Weight)
+			// Standard Error: 0
+			.saturating_add((168_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
 	// Storage: Scheduler Lookup (r:1 w:1)
 	// Storage: Scheduler Agenda (r:1 w:1)
 	fn cancel_named(s: u32, ) -> Weight {
-		(15_852_000 as Weight)
-			// Standard Error: 2_000
-			.saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+		(31_169_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((1_565_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(2 as Weight))
 	}
@@ -216,148 +186,134 @@
 // For backwards compatibility and tests
 impl WeightInfo for () {
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
-		(11_587_000 as Weight)
-			// Standard Error: 17_000
-			.saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+		(35_999_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((32_234_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_named_resolved(s: u32, ) -> Weight {
-		(8_965_000 as Weight)
-			// Standard Error: 11_000
-			.saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
+		(34_874_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((23_114_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
-		(8_654_000 as Weight)
-			// Standard Error: 17_000
-			.saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	fn on_initialize_resolved(s: u32, ) -> Weight {
-		(9_303_000 as Weight)
-			// Standard Error: 10_000
-			.saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
+	fn on_initialize_periodic(s: u32, ) -> Weight {
+		(36_469_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((32_202_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_named_aborted(s: u32, ) -> Weight {
-		(7_506_000 as Weight)
+	fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+		(35_352_000 as Weight)
 			// Standard Error: 3_000
-			.saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add((32_309_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
 			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
-			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:2 w:2)
-	// Storage: Preimage PreimageFor (r:1 w:0)
+	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_aborted(s: u32, ) -> Weight {
-		(8_046_000 as Weight)
-			// Standard Error: 3_000
-			.saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+		(11_267_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((9_368_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
-	// Storage: Scheduler Agenda (r:2 w:2)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn on_initialize_periodic_named(s: u32, ) -> Weight {
-		(13_704_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
-	}
-	// Storage: Scheduler Agenda (r:2 w:2)
-	fn on_initialize_periodic(s: u32, ) -> Weight {
-		(12_668_000 as Weight)
-			// Standard Error: 5_000
-			.saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+	fn on_initialize_named_aborted(s: u32, ) -> Weight {
+		(35_937_000 as Weight)
+			// Standard Error: 3_000
+			.saturating_add((23_037_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
-	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: Scheduler Agenda (r:2 w:2)
 	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize_named(s: u32, ) -> Weight {
-		(13_946_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+		(10_338_000 as Weight)
+			// Standard Error: 2_000
+			.saturating_add((9_422_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
+	// Storage: Scheduler Lookup (r:0 w:1)
 	fn on_initialize(s: u32, ) -> Weight {
-		(13_151_000 as Weight)
-			// Standard Error: 4_000
-			.saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
+		(37_448_000 as Weight)
+			// Standard Error: 7_000
+			.saturating_add((22_907_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Agenda (r:1 w:1)
-	fn schedule(s: u32, ) -> Weight {
-		(14_040_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((89_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
+	// Storage: System Account (r:1 w:1)
+	// Storage: System AllExtrinsicsLen (r:1 w:1)
+	// Storage: System BlockWeight (r:1 w:1)
 	// Storage: Scheduler Lookup (r:0 w:1)
-	fn cancel(s: u32, ) -> Weight {
-		(14_376_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((576_000 as Weight).saturating_mul(s as Weight))
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
+	fn on_initialize_resolved(s: u32, ) -> Weight {
+		(34_841_000 as Weight)
+			// Standard Error: 7_000
+			.saturating_add((22_966_000 as Weight).saturating_mul(s as Weight))
+			.saturating_add(RocksDbWeight::get().reads(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+			.saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
 	}
 	// Storage: Scheduler Lookup (r:1 w:1)
 	// Storage: Scheduler Agenda (r:1 w:1)
 	fn schedule_named(s: u32, ) -> Weight {
-		(16_806_000 as Weight)
-			// Standard Error: 1_000
-			.saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+		(33_845_000 as Weight)
+			// Standard Error: 0
+			.saturating_add((168_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
 	// Storage: Scheduler Lookup (r:1 w:1)
 	// Storage: Scheduler Agenda (r:1 w:1)
 	fn cancel_named(s: u32, ) -> Weight {
-		(15_852_000 as Weight)
-			// Standard Error: 2_000
-			.saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+		(31_169_000 as Weight)
+			// Standard Error: 1_000
+			.saturating_add((1_565_000 as Weight).saturating_mul(s as Weight))
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
 	}
modifiedruntime/common/Cargo.tomldiffbeforeafterboth
--- a/runtime/common/Cargo.toml
+++ b/runtime/common/Cargo.toml
@@ -89,6 +89,10 @@
 default-features = false
 path = "../../pallets/refungible"
 
+[dependencies.pallet-unique-scheduler]
+default-features = false
+path = "../../pallets/scheduler"
+
 [dependencies.up-data-structs]
 default-features = false
 path = "../../primitives/data-structs"
modifiedruntime/common/src/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -843,6 +843,7 @@
                     list_benchmark!(list, extra, pallet_fungible, Fungible);
                     list_benchmark!(list, extra, pallet_refungible, Refungible);
                     list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);
+                    list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);
                     list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);
                     // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);
 
@@ -887,6 +888,7 @@
                     add_benchmark!(params, batches, pallet_fungible, Fungible);
                     add_benchmark!(params, batches, pallet_refungible, Refungible);
                     add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);
+                    add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);
                     add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);
                     // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);
 
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -36,6 +36,7 @@
     'pallet-proxy-rmrk-core/runtime-benchmarks',
     'pallet-unique/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
+    'pallet-unique-scheduler/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -93,7 +94,7 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unq-scheduler/std',
+    'pallet-unique-scheduler/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -412,7 +413,7 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
+pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
modifiedruntime/opal/src/lib.rsdiffbeforeafterboth
--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -68,7 +68,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use pallet_unq_scheduler::DispatchCall;
+use pallet_unique_scheduler::DispatchCall;
 use up_data_structs::{
 	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
 	CollectionStats, RpcCollection,
@@ -969,7 +969,7 @@
 }
 
 pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::Call: Member
@@ -979,13 +979,13 @@
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
 	Call: From<<T as frame_system::Config>::Call>
-		+ From<<T as pallet_unq_scheduler::Config>::Call>
+		+ From<<T as pallet_unique_scheduler::Config>::Call>
 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
 	fn dispatch_call(
 		signer: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<
 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
 		TransactionValidityError,
@@ -1011,7 +1011,7 @@
 	fn reserve_balance(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 		count: u32,
 	) -> Result<(), DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
@@ -1028,7 +1028,7 @@
 	fn pay_for_call(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<u128, DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
 		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
@@ -1069,7 +1069,7 @@
 	}
 }
 
-impl pallet_unq_scheduler::Config for Runtime {
+impl pallet_unique_scheduler::Config for Runtime {
 	type Event = Event;
 	type Origin = Origin;
 	type Currency = Balances;
@@ -1158,7 +1158,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -37,6 +37,7 @@
     'pallet-proxy-rmrk-equip/runtime-benchmarks',
     'pallet-unique/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
+    'pallet-unique-scheduler/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -94,7 +95,7 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unq-scheduler/std',
+    'pallet-unique-scheduler/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -419,7 +420,7 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
+pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
modifiedruntime/quartz/src/lib.rsdiffbeforeafterboth
--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -68,7 +68,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use pallet_unq_scheduler::DispatchCall;
+use pallet_unique_scheduler::DispatchCall;
 use up_data_structs::{
 	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
 	CollectionStats, RpcCollection,
@@ -968,7 +968,7 @@
 }
 
 pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::Call: Member
@@ -978,13 +978,13 @@
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
 	Call: From<<T as frame_system::Config>::Call>
-		+ From<<T as pallet_unq_scheduler::Config>::Call>
+		+ From<<T as pallet_unique_scheduler::Config>::Call>
 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
 	fn dispatch_call(
 		signer: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<
 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
 		TransactionValidityError,
@@ -1010,7 +1010,7 @@
 	fn reserve_balance(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 		count: u32,
 	) -> Result<(), DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
@@ -1027,7 +1027,7 @@
 	fn pay_for_call(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<u128, DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
 		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
@@ -1068,7 +1068,7 @@
 	}
 }
 
-impl pallet_unq_scheduler::Config for Runtime {
+impl pallet_unique_scheduler::Config for Runtime {
 	type Event = Event;
 	type Origin = Origin;
 	type Currency = Balances;
@@ -1156,7 +1156,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -37,6 +37,7 @@
     'pallet-proxy-rmrk-equip/runtime-benchmarks',
     'pallet-unique/runtime-benchmarks',
     'pallet-inflation/runtime-benchmarks',
+    'pallet-unique-scheduler/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -95,7 +96,7 @@
     'pallet-proxy-rmrk-core/std',
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
-    'pallet-unq-scheduler/std',
+    'pallet-unique-scheduler/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -412,7 +413,7 @@
 pallet-nonfungible = { default-features = false, path = "../../pallets/nonfungible" }
 pallet-proxy-rmrk-core = { default-features = false, path = "../../pallets/proxy-rmrk-core", package = "pallet-rmrk-core" }
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
-pallet-unq-scheduler = { path = '../../pallets/scheduler', default-features = false }
+pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 # pallet-contract-helpers = { path = '../pallets/contract-helpers', default-features = false, version = '0.1.0' }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
modifiedruntime/unique/src/lib.rsdiffbeforeafterboth
--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -68,7 +68,7 @@
 		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
 	},
 };
-use pallet_unq_scheduler::DispatchCall;
+use pallet_unique_scheduler::DispatchCall;
 use up_data_structs::{
 	CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
 	CollectionStats, RpcCollection,
@@ -967,7 +967,7 @@
 }
 
 pub struct SchedulerPaymentExecutor;
-impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::Call: Member
@@ -977,13 +977,13 @@
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
 	Call: From<<T as frame_system::Config>::Call>
-		+ From<<T as pallet_unq_scheduler::Config>::Call>
+		+ From<<T as pallet_unique_scheduler::Config>::Call>
 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
 	fn dispatch_call(
 		signer: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<
 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
 		TransactionValidityError,
@@ -1009,7 +1009,7 @@
 	fn reserve_balance(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 		count: u32,
 	) -> Result<(), DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
@@ -1026,7 +1026,7 @@
 	fn pay_for_call(
 		id: [u8; 16],
 		sponsor: <T as frame_system::Config>::AccountId,
-		call: <T as pallet_unq_scheduler::Config>::Call,
+		call: <T as pallet_unique_scheduler::Config>::Call,
 	) -> Result<u128, DispatchError> {
 		let dispatch_info = call.get_dispatch_info();
 		let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
@@ -1067,7 +1067,7 @@
 	}
 }
 
-impl pallet_unq_scheduler::Config for Runtime {
+impl pallet_unique_scheduler::Config for Runtime {
 	type Event = Event;
 	type Origin = Origin;
 	type Currency = Balances;
@@ -1155,7 +1155,7 @@
 		// Unique Pallets
 		Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
 		Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
-		Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+		Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 		// free = 63
 		Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
 		// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,