git.delta.rocks / unique-network / refs/commits / 04e0d1087094

difftreelog

Merge branch 'develop' into feature/ci-refactoring

Konstantin Astakhov2022-10-28parents: #5a2c2b9 #f1d8c96.patch.diff
in: master

19 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5385,7 +5385,6 @@
  "pallet-treasury",
  "pallet-unique",
  "pallet-unique-scheduler",
- "pallet-unique-scheduler-v2",
  "pallet-xcm",
  "parachain-info",
  "parity-scale-codec 3.2.1",
@@ -6709,7 +6708,7 @@
 dependencies = [
  "frame-support",
  "frame-system",
- "pallet-unique-scheduler-v2",
+ "pallet-unique-scheduler",
  "parity-scale-codec 3.2.1",
  "scale-info",
 ]
@@ -6851,24 +6850,6 @@
  "sp-std",
  "substrate-test-utils",
  "up-sponsorship",
-]
-
-[[package]]
-name = "pallet-unique-scheduler-v2"
-version = "0.1.0"
-dependencies = [
- "frame-benchmarking",
- "frame-support",
- "frame-system",
- "log",
- "pallet-preimage",
- "parity-scale-codec 3.2.1",
- "scale-info",
- "sp-core",
- "sp-io",
- "sp-runtime",
- "sp-std",
- "substrate-test-utils",
 ]
 
 [[package]]
modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -545,13 +545,16 @@
 		keys: Option<Vec<String>>
 	) -> Vec<PropertyKeyPermission>, unique_api);
 
-	pass_method!(token_data(
-		collection: CollectionId,
-		token_id: TokenId,
+	pass_method!(
+		token_data(
+			collection: CollectionId,
+			token_id: TokenId,
 
-		#[map(|keys| string_keys_to_bytes_keys(keys))]
-		keys: Option<Vec<String>>,
-	) -> TokenData<CrossAccountId>, unique_api);
+			#[map(|keys| string_keys_to_bytes_keys(keys))]
+			keys: Option<Vec<String>>,
+		) -> TokenData<CrossAccountId>, unique_api;
+		changed_in 3, token_data_before_version_3(collection, token_id, string_keys_to_bytes_keys(keys)) => |value| value.into()
+	);
 
 	pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);
 	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);
addedkb/how-not-to-break-rpc.mddiffbeforeafterboth
--- /dev/null
+++ b/kb/how-not-to-break-rpc.md
@@ -0,0 +1,169 @@
+# How not to break RPC
+
+Let's discuss how to avoid the breaking of RPC with an example of how the `colection_by_id` RPC method was broken.
+
+The `collection_by_id` was broken due to the change of the result type `RpcCollection`.
+The new version of the `RpcCollection` was incompatible with the old one due to addition of the `flags` field:
+
+```rust
+// The new version of the `RpcCollection`
+pub struct RpcCollection<AccountId> {
+	/// Collection owner account.
+	pub owner: AccountId,
+	/// Collection mode.
+	pub mode: CollectionMode,
+	/// Collection name.
+	pub name: Vec<u16>,
+	/// Collection description.
+	pub description: Vec<u16>,
+	/// Token prefix.
+	pub token_prefix: Vec<u8>,
+	/// The state of sponsorship of the collection.
+	pub sponsorship: SponsorshipState<AccountId>,
+	/// Collection limits.
+	pub limits: CollectionLimits,
+	/// Collection permissions.
+	pub permissions: CollectionPermissions,
+	/// Token property permissions.
+	pub token_property_permissions: Vec<PropertyKeyPermission>,
+	/// Collection properties.
+	pub properties: Vec<Property>,
+	/// Is collection read only.
+	pub read_only: bool,
+
+	/// Extra collection flags
+	pub flags: RpcCollectionFlags, // <-- THIS IS A NEW FIELD!
+}
+```
+
+### Where exactly was RPC broken?
+
+To answer this question, we need to describe the process of handling an RPC call.
+
+1. A user calls an RPC method.
+2. The node sees what method with what arguments should be executed.
+3. Since the code of each RPC method is located inside the runtime, the node does the following:
+    - The node encodes the RPC arguments into the [SCALE format](https://docs.substrate.io/reference/scale-codec/), and then it will call the corresponding method of the runtime API with the encoded arguments.
+    - The runtime executes the RPC logic and then returns the SCALE-encoded result.
+    - The node receives the result from the runtime and then decodes it. **It is the place where RPC could break!**
+
+Point #3 describes a process implemented inside the [`pass_method`](https://github.com/UniqueNetwork/unique-chain/blob/1c7179877b5fb1eacf86c5ecf607317d11999675/client/rpc/src/lib.rs#L435-L472) macro.
+
+Using the `pass_method` macro the node maps each RPC method onto the corresponding runtime API method.
+
+See how [the node's RPC is implemented](https://github.com/UniqueNetwork/unique-chain/blob/1c7179877b5fb1eacf86c5ecf607317d11999675/client/rpc/src/lib.rs#L493-L569) and how [the runtime API is declared](https://github.com/UniqueNetwork/unique-chain/blob/1c7179877b5fb1eacf86c5ecf607317d11999675/primitives/rpc/src/lib.rs#L32-L129).
+
+### How can the node use the old runtime API? 
+
+As you can see from the previous section -- RPC breaks if the runtime API data format is incompatible with the node's RPC data format.
+
+When the node is working with an old runtime and exposes the new version of RPC that contains some methods with a changed signature, the node should call only the old versions of these methods to avoid RPC failure.
+
+The node should do the following to get an old runtime API method to run correctly:
+* The node should convert all the RPC arguments into the old runtime API format.
+* It should convert the result from the runtime to the new data format (it is the only action needed in the case of `collection_by_id`). 
+
+The `pass_method` macro can call the old runtime API methods.
+For instance, the correct implementation of the `collection_by_id` RPC method looks like this: 
+```rust
+pass_method!(
+	/* line 1 */ collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api;
+	/* line 2 */ changed_in 3, collection_by_id_before_version_3(collection) => |value| value.map(|coll| coll.into())
+);
+```
+
+The first line describes the newest RPC signature.
+
+The second line tells us what should be called in the case if we're dealing with an old runtime API.
+* `collection_by_id_before_version_3` -- the name of the corresponding runtime API method with an old signature.
+* `(collection)` -- what arguments should the node pass to the old method. In the case of `collection_by_id`, we pass the arguments as is since there were no changes to the arguments' types.
+* `=> |value| value.map(|coll| coll.into())` -- describes how to transform the return value from the old runtime API data format into the new RPC data format.
+
+### Runtime API backward compatibility support
+
+Methods like `collection_by_id_before_version_3` doesn't appear automatically.
+
+When changing the runtime API methods' signatures, we need to:
+* Specify the number of the new version of the runtime API.
+* Specify the old versions of the changed methods.
+
+See the documentation of the `decl_runtime_apis` macro: [runtime api trait versioning](https://docs.rs/sp-api/latest/sp_api/macro.decl_runtime_apis.html#runtime-api-trait-versioning).
+
+### How to easily implement the converting from the old structure into the new ones
+
+To describe structures that can have some fields changing over different versions, we use the `#[struct_versioning::versioned]` attribute.
+
+Let's take a look at the `RpcCollection` declaration.
+
+```rust
+/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).
+#[struct_versioning::versioned(version = 2, upper)]
+#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
+pub struct RpcCollection<AccountId> {
+	/// Collection owner account.
+	pub owner: AccountId,
+
+	/// Collection mode.
+	pub mode: CollectionMode,
+
+	/// Collection name.
+	pub name: Vec<u16>,
+
+	/// Collection description.
+	pub description: Vec<u16>,
+
+	/// Token prefix.
+	pub token_prefix: Vec<u8>,
+
+	/// The state of sponsorship of the collection.
+	pub sponsorship: SponsorshipState<AccountId>,
+
+	/// Collection limits.
+	pub limits: CollectionLimits,
+
+	/// Collection permissions.
+	pub permissions: CollectionPermissions,
+
+	/// Token property permissions.
+	pub token_property_permissions: Vec<PropertyKeyPermission>,
+
+	/// Collection properties.
+	pub properties: Vec<Property>,
+
+	/// Is collection read only.
+	pub read_only: bool,
+
+	/// Extra collection flags
+	#[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]
+	pub flags: RpcCollectionFlags,
+}
+```
+
+The `#[struct_versioning::versioned]` will create 2 types for us: the `RpcCollectionVersion1` (the old version) and the `RpcCollection` (the new version).
+
+This attribute automatically implements the `impl From<RpcCollectionVersion1> for RpcCollection`.
+
+The attribute understands how to map the old fields to new ones with the help of the `#[version(...)]` field attribute, which should be placed right before the field in question.
+
+There were no field `flags` in the `RpcCollectionVersion1` structure. The `#[version(2.., upper(<expr>))]` tells the attribute to assign the `flags` field to `<expr>` in the new version of the `RpcCollection` structure.
+
+Given that we have the `From` trait implemented for the new version of the `RpcCollection`, we can use `.into()` to convert the old version to the new one as we did in the `pass_method` macro above.
+
+Here is the description of the `struct_versioning` attribute:
+```
+Generate versioned variants of a struct
+
+ `#[versioned(version = 1[, first_version = 1][, upper][, versions])]`
+ - *version* - current version of a struct
+ - *first_version* - allows to skip generation of structs, which predates first supported version
+ - *upper* - generate From impls, which converts old version of structs to new
+ - *versions* - generate enum, which contains all possible versions of struct
+
+ Each field may have version attribute
+ `#[version([1]..[2][, upper(old)])]`
+ - *1* - version, on which this field is appeared
+ - *2* - version, in which this field was removed
+ (i.e if set to 2, this field was exist on version 1, and no longer exist on version 2)
+ - *upper* - code, which should be executed to transform old value to new/create new value
+```
deletedpallets/scheduler-v2/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler-v2/Cargo.toml
+++ /dev/null
@@ -1,48 +0,0 @@
-[package]
-name = "pallet-unique-scheduler-v2"
-version = "0.1.0"
-authors = ["Unique Network <support@uniquenetwork.io>"]
-edition = "2021"
-license = "GPLv3"
-homepage = "https://unique.network"
-repository = "https://github.com/UniqueNetwork/unique-chain"
-description = "Unique Scheduler pallet"
-readme = "README.md"
-
-[dependencies]
-codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = ["derive"] }
-log = { version = "0.4.17", default-features = false }
-scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
-frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-io = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-runtime = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-std = { version = "4.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-[dev-dependencies]
-pallet-preimage = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-sp-core = { version = "6.0.0", default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-substrate-test-utils = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-
-[features]
-default = ["std"]
-runtime-benchmarks = [
-	"frame-benchmarking",
-	"frame-support/runtime-benchmarks",
-	"frame-system/runtime-benchmarks",
-]
-std = [
-	"codec/std",
-	"frame-benchmarking?/std",
-	"frame-support/std",
-	"frame-system/std",
-	"log/std",
-	"scale-info/std",
-	"sp-io/std",
-	"sp-runtime/std",
-	"sp-std/std",
-	"sp-core/std",
-]
-try-runtime = ["frame-support/try-runtime"]
deletedpallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/benchmarking.rs
+++ /dev/null
@@ -1,349 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license:
-// This file is part of Substrate.
-
-// Copyright (C) 2020-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! Scheduler pallet benchmarking.
-
-use super::*;
-use frame_benchmarking::{account, benchmarks};
-use frame_support::{
-	ensure,
-	traits::{schedule::Priority, PreimageRecipient},
-};
-use frame_system::RawOrigin;
-use sp_std::{prelude::*, vec};
-use sp_io::hashing::blake2_256;
-
-use crate::{Pallet as Scheduler, ScheduledCall, EncodedCall};
-use frame_system::Call as SystemCall;
-
-const SEED: u32 = 0;
-
-const BLOCK_NUMBER: u32 = 2;
-
-type SystemOrigin<T> = <T as frame_system::Config>::Origin;
-
-/// Add `n` items to the schedule.
-///
-/// For `resolved`:
-/// - `
-/// - `None`: aborted (hash without preimage)
-/// - `Some(true)`: hash resolves into call if possible, plain call otherwise
-/// - `Some(false)`: plain call
-fn fill_schedule<T: Config>(when: T::BlockNumber, n: u32) -> Result<(), &'static str> {
-	let t = DispatchTime::At(when);
-	let origin: <T as Config>::PalletsOrigin = frame_system::RawOrigin::Root.into();
-	for i in 0..n {
-		let call = make_call::<T>(None);
-		let period = Some(((i + 100).into(), 100));
-		let name = u32_to_name(i);
-		Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;
-	}
-	ensure!(
-		Agenda::<T>::get(when).len() == n as usize,
-		"didn't fill schedule"
-	);
-	Ok(())
-}
-
-fn u32_to_name(i: u32) -> TaskName {
-	i.using_encoded(blake2_256)
-}
-
-fn make_task<T: Config>(
-	periodic: bool,
-	named: bool,
-	signed: bool,
-	maybe_lookup_len: Option<u32>,
-	priority: Priority,
-) -> ScheduledOf<T> {
-	let call = make_call::<T>(maybe_lookup_len);
-	let maybe_periodic = match periodic {
-		true => Some((100u32.into(), 100)),
-		false => None,
-	};
-	let maybe_id = match named {
-		true => Some(u32_to_name(0)),
-		false => None,
-	};
-	let origin = make_origin::<T>(signed);
-	Scheduled {
-		maybe_id,
-		priority,
-		call,
-		maybe_periodic,
-		origin,
-		_phantom: PhantomData,
-	}
-}
-
-fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {
-	let call = <<T as Config>::Call>::from(SystemCall::remark {
-		remark: vec![0; len as usize],
-	});
-	ScheduledCall::new(call).ok()
-}
-
-fn make_call<T: Config>(maybe_lookup_len: Option<u32>) -> ScheduledCall<T> {
-	let bound = EncodedCall::bound() as u32;
-	let mut len = match maybe_lookup_len {
-		Some(len) => {
-			len.min(<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get() - 2)
-				.max(bound) - 3
-		}
-		None => bound.saturating_sub(4),
-	};
-
-	loop {
-		let c = match bounded::<T>(len) {
-			Some(x) => x,
-			None => {
-				len -= 1;
-				continue;
-			}
-		};
-		if c.lookup_needed() == maybe_lookup_len.is_some() {
-			break c;
-		}
-		if maybe_lookup_len.is_some() {
-			len += 1;
-		} else {
-			if len > 0 {
-				len -= 1;
-			} else {
-				break c;
-			}
-		}
-	}
-}
-
-fn make_origin<T: Config>(signed: bool) -> <T as Config>::PalletsOrigin {
-	match signed {
-		true => frame_system::RawOrigin::Signed(account("origin", 0, SEED)).into(),
-		false => frame_system::RawOrigin::Root.into(),
-	}
-}
-
-fn dummy_counter() -> WeightCounter {
-	WeightCounter {
-		used: Weight::zero(),
-		limit: Weight::MAX,
-	}
-}
-
-benchmarks! {
-	// `service_agendas` when no work is done.
-	service_agendas_base {
-		let now = T::BlockNumber::from(BLOCK_NUMBER);
-		IncompleteSince::<T>::put(now - One::one());
-	}: {
-		Scheduler::<T>::service_agendas(&mut dummy_counter(), now, 0);
-	} verify {
-		assert_eq!(IncompleteSince::<T>::get(), Some(now - One::one()));
-	}
-
-	// `service_agenda` when no work is done.
-	service_agenda_base {
-		let now = BLOCK_NUMBER.into();
-		let s in 0 .. T::MaxScheduledPerBlock::get();
-		fill_schedule::<T>(now, s)?;
-		let mut executed = 0;
-	}: {
-		Scheduler::<T>::service_agenda(&mut dummy_counter(), &mut executed, now, now, 0);
-	} verify {
-		assert_eq!(executed, 0);
-	}
-
-	// `service_task` when the task is a non-periodic, non-named, non-fetched call which is not
-	// dispatched (e.g. due to being overweight).
-	service_task_base {
-		let now = BLOCK_NUMBER.into();
-		let task = make_task::<T>(false, false, false, None, 0);
-		// prevent any tasks from actually being executed as we only want the surrounding weight.
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
-	}: {
-		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
-	} verify {
-		//assert_eq!(result, Ok(()));
-	}
-
-	// `service_task` when the task is a non-periodic, non-named, fetched call (with a known
-	// preimage length) and which is not dispatched (e.g. due to being overweight).
-	service_task_fetched {
-		let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());
-		let now = BLOCK_NUMBER.into();
-		let task = make_task::<T>(false, false, false, Some(s), 0);
-		// prevent any tasks from actually being executed as we only want the surrounding weight.
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
-	}: {
-		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
-	} verify {
-	}
-
-	// `service_task` when the task is a non-periodic, named, non-fetched call which is not
-	// dispatched (e.g. due to being overweight).
-	service_task_named {
-		let now = BLOCK_NUMBER.into();
-		let task = make_task::<T>(false, true, false, None, 0);
-		// prevent any tasks from actually being executed as we only want the surrounding weight.
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
-	}: {
-		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
-	} verify {
-	}
-
-	// `service_task` when the task is a periodic, non-named, non-fetched call which is not
-	// dispatched (e.g. due to being overweight).
-	service_task_periodic {
-		let now = BLOCK_NUMBER.into();
-		let task = make_task::<T>(true, false, false, None, 0);
-		// prevent any tasks from actually being executed as we only want the surrounding weight.
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
-	}: {
-		let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
-	} verify {
-	}
-
-	// `execute_dispatch` when the origin is `Signed`, not counting the dispatable's weight.
-	execute_dispatch_signed {
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
-		let origin = make_origin::<T>(true);
-		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
-	}: {
-		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
-	}
-	verify {
-	}
-
-	// `execute_dispatch` when the origin is not `Signed`, not counting the dispatable's weight.
-	execute_dispatch_unsigned {
-		let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::MAX };
-		let origin = make_origin::<T>(false);
-		let call = T::Preimages::realize(&make_call::<T>(None)).unwrap().0;
-	}: {
-		assert!(Scheduler::<T>::execute_dispatch(&mut counter, origin, call).is_ok());
-	}
-	verify {
-	}
-
-	schedule {
-		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
-		let when = BLOCK_NUMBER.into();
-		let periodic = Some((T::BlockNumber::one(), 100));
-		let priority = Some(0);
-		// Essentially a no-op call.
-		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
-
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, when, periodic, priority, call)
-	verify {
-		ensure!(
-			Agenda::<T>::get(when).len() == (s + 1) as usize,
-			"didn't add to schedule"
-		);
-	}
-
-	cancel {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-
-		fill_schedule::<T>(when, s)?;
-		assert_eq!(Agenda::<T>::get(when).len(), s as usize);
-		let schedule_origin = T::ScheduleOrigin::successful_origin();
-	}: _<SystemOrigin<T>>(schedule_origin, when, 0)
-	verify {
-		ensure!(
-			Lookup::<T>::get(u32_to_name(0)).is_none(),
-			"didn't remove from lookup"
-		);
-		// Removed schedule is NONE
-		ensure!(
-			Agenda::<T>::get(when)[0].is_none(),
-			"didn't remove from schedule"
-		);
-	}
-
-	schedule_named {
-		let s in 0 .. (T::MaxScheduledPerBlock::get() - 1);
-		let id = u32_to_name(s);
-		let when = BLOCK_NUMBER.into();
-		let periodic = Some((T::BlockNumber::one(), 100));
-		let priority = Some(0);
-		// Essentially a no-op call.
-		let call = Box::new(SystemCall::set_storage { items: vec![] }.into());
-
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, id, when, periodic, priority, call)
-	verify {
-		ensure!(
-			Agenda::<T>::get(when).len() == (s + 1) as usize,
-			"didn't add to schedule"
-		);
-	}
-
-	cancel_named {
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-
-		fill_schedule::<T>(when, s)?;
-	}: _(RawOrigin::Root, u32_to_name(0))
-	verify {
-		ensure!(
-			Lookup::<T>::get(u32_to_name(0)).is_none(),
-			"didn't remove from lookup"
-		);
-		// Removed schedule is NONE
-		ensure!(
-			Agenda::<T>::get(when)[0].is_none(),
-			"didn't remove from schedule"
-		);
-	}
-
-	change_named_priority {
-		let origin: RawOrigin<T::AccountId> = frame_system::RawOrigin::Root;
-		let s in 1 .. T::MaxScheduledPerBlock::get();
-		let when = BLOCK_NUMBER.into();
-		let idx = s - 1;
-		let id = u32_to_name(idx);
-		let priority = 42;
-		fill_schedule::<T>(when, s)?;
-	}: _(origin, id, priority)
-	verify {
-		ensure!(
-			Agenda::<T>::get(when)[idx as usize].clone().unwrap().priority == priority,
-			"didn't change the priority"
-		);
-	}
-
-	impl_benchmark_test_suite!(Scheduler, crate::mock::new_test_ext(), crate::mock::Test);
-}
deletedpallets/scheduler-v2/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/lib.rs
+++ /dev/null
@@ -1,1102 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license:
-// This file is part of Substrate.
-
-// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! # Scheduler
-//! A Pallet for scheduling dispatches.
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Pallet`]
-//!
-//! ## Overview
-//!
-//! This Pallet exposes capabilities for scheduling dispatches to occur at a
-//! specified block number or at a specified period. These scheduled dispatches
-//! may be named or anonymous and may be canceled.
-//!
-//! **NOTE:** The scheduled calls will be dispatched with the default filter
-//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin
-//! except root which will get no filter. And not the filter contained in origin
-//! use to call `fn schedule`.
-//!
-//! If a call is scheduled using proxy or whatever mecanism which adds filter,
-//! then those filter will not be used when dispatching the schedule call.
-//!
-//! ## Interface
-//!
-//! ### Dispatchable Functions
-//!
-//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and
-//!   with a specified priority.
-//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.
-//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter
-//!   that can be used for identification.
-//! * `cancel_named` - the named complement to the cancel function.
-
-// Ensure we're `no_std` when compiling for Wasm.
-#![cfg_attr(not(feature = "std"), no_std)]
-
-#[cfg(feature = "runtime-benchmarks")]
-mod benchmarking;
-#[cfg(test)]
-mod mock;
-#[cfg(test)]
-mod tests;
-pub mod weights;
-
-use codec::{Codec, Decode, Encode, MaxEncodedLen};
-use frame_support::{
-	dispatch::{
-		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,
-	},
-	traits::{
-		schedule::{self, DispatchTime, LOWEST_PRIORITY},
-		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,
-		ConstU32, UnfilteredDispatchable,
-	},
-	weights::Weight,
-	unsigned::TransactionValidityError,
-};
-
-use frame_system::{self as system};
-use scale_info::TypeInfo;
-use sp_runtime::{
-	traits::{BadOrigin, One, Saturating, Zero, Hash},
-	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,
-};
-use sp_core::H160;
-use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
-pub use weights::WeightInfo;
-
-pub use pallet::*;
-
-/// Just a simple index for naming period tasks.
-pub type PeriodicIndex = u32;
-/// The location of a scheduled task that can be used to remove it.
-pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
-
-pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;
-
-#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
-#[scale_info(skip_type_params(T))]
-pub enum ScheduledCall<T: Config> {
-	Inline(EncodedCall),
-	PreimageLookup { hash: T::Hash, unbounded_len: u32 },
-}
-
-impl<T: Config> ScheduledCall<T> {
-	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {
-		let encoded = call.encode();
-		let len = encoded.len();
-
-		match EncodedCall::try_from(encoded.clone()) {
-			Ok(bounded) => Ok(Self::Inline(bounded)),
-			Err(_) => {
-				let hash = <T as system::Config>::Hashing::hash_of(&encoded);
-				<T as Config>::Preimages::note_preimage(
-					encoded
-						.try_into()
-						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,
-				);
-
-				Ok(Self::PreimageLookup {
-					hash,
-					unbounded_len: len as u32,
-				})
-			}
-		}
-	}
-
-	/// The maximum length of the lookup that is needed to peek `Self`.
-	pub fn lookup_len(&self) -> Option<u32> {
-		match self {
-			Self::Inline(..) => None,
-			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),
-		}
-	}
-
-	/// Returns whether the image will require a lookup to be peeked.
-	pub fn lookup_needed(&self) -> bool {
-		match self {
-			Self::Inline(_) => false,
-			Self::PreimageLookup { .. } => true,
-		}
-	}
-
-	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {
-		<T as Config>::RuntimeCall::decode(&mut data)
-			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())
-	}
-}
-
-pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {
-	fn drop(call: &ScheduledCall<T>);
-
-	fn peek(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
-
-	/// Convert the given scheduled `call` value back into its original instance. If successful,
-	/// `drop` any data backing it. This will not break the realisability of independently
-	/// created instances of `ScheduledCall` which happen to have identical data.
-	fn realize(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;
-}
-
-impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {
-	fn drop(call: &ScheduledCall<T>) {
-		match call {
-			ScheduledCall::Inline(_) => {}
-			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),
-		}
-	}
-
-	fn peek(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
-		match call {
-			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),
-			ScheduledCall::PreimageLookup {
-				hash,
-				unbounded_len,
-			} => {
-				let (preimage, len) = Self::get_preimage(hash)
-					.ok_or(<Error<T>>::PreimageNotFound)
-					.map(|preimage| (preimage, *unbounded_len))?;
-
-				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))
-			}
-		}
-	}
-
-	fn realize(
-		call: &ScheduledCall<T>,
-	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {
-		let r = Self::peek(call)?;
-		Self::drop(call);
-		Ok(r)
-	}
-}
-
-pub enum ScheduledEnsureOriginSuccess<AccountId> {
-	Root,
-	Signed(AccountId),
-}
-
-pub type TaskName = [u8; 32];
-
-/// Information regarding an item to be executed in the future.
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
-#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]
-pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {
-	/// The unique identity for this task, if there is one.
-	maybe_id: Option<Name>,
-
-	/// This task's priority.
-	priority: schedule::Priority,
-
-	/// The call to be dispatched.
-	call: Call,
-
-	/// If the call is periodic, then this points to the information concerning that.
-	maybe_periodic: Option<schedule::Period<BlockNumber>>,
-
-	/// The origin with which to dispatch the call.
-	origin: PalletsOrigin,
-	_phantom: PhantomData<AccountId>,
-}
-
-pub type ScheduledOf<T> = Scheduled<
-	TaskName,
-	ScheduledCall<T>,
-	<T as frame_system::Config>::BlockNumber,
-	<T as Config>::PalletsOrigin,
-	<T as frame_system::Config>::AccountId,
->;
-
-struct WeightCounter {
-	used: Weight,
-	limit: Weight,
-}
-
-impl WeightCounter {
-	fn check_accrue(&mut self, w: Weight) -> bool {
-		let test = self.used.saturating_add(w);
-		if test.any_gt(self.limit) {
-			false
-		} else {
-			self.used = test;
-			true
-		}
-	}
-
-	fn can_accrue(&mut self, w: Weight) -> bool {
-		self.used.saturating_add(w).all_lte(self.limit)
-	}
-}
-
-pub(crate) trait MarginalWeightInfo: WeightInfo {
-	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {
-		let base = Self::service_task_base();
-		let mut total = match maybe_lookup_len {
-			None => base,
-			Some(l) => Self::service_task_fetched(l as u32),
-		};
-		if named {
-			total.saturating_accrue(Self::service_task_named().saturating_sub(base));
-		}
-		if periodic {
-			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));
-		}
-		total
-	}
-}
-
-impl<T: WeightInfo> MarginalWeightInfo for T {}
-
-#[frame_support::pallet]
-pub mod pallet {
-	use super::*;
-	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};
-	use system::pallet_prelude::*;
-
-	/// The current storage version.
-	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);
-
-	#[pallet::pallet]
-	#[pallet::generate_store(pub(super) trait Store)]
-	#[pallet::storage_version(STORAGE_VERSION)]
-	pub struct Pallet<T>(_);
-
-	#[pallet::config]
-	pub trait Config: frame_system::Config {
-		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
-
-		/// The aggregated origin which the dispatch will take.
-		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
-			+ From<Self::PalletsOrigin>
-			+ IsType<<Self as system::Config>::RuntimeOrigin>
-			+ Clone;
-
-		/// The caller origin, overarching type of all pallets origins.
-		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>
-			+ Codec
-			+ Clone
-			+ Eq
-			+ TypeInfo
-			+ MaxEncodedLen;
-
-		/// The aggregated call type.
-		type RuntimeCall: Parameter
-			+ Dispatchable<
-				RuntimeOrigin = <Self as Config>::RuntimeOrigin,
-				PostInfo = PostDispatchInfo,
-			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>
-			+ GetDispatchInfo
-			+ From<system::Call<Self>>;
-
-		/// The maximum weight that may be scheduled per block for any dispatchables.
-		#[pallet::constant]
-		type MaximumWeight: Get<Weight>;
-
-		/// Required origin to schedule or cancel calls.
-		type ScheduleOrigin: EnsureOrigin<
-			<Self as system::Config>::RuntimeOrigin,
-			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,
-		>;
-
-		/// Compare the privileges of origins.
-		///
-		/// This will be used when canceling a task, to ensure that the origin that tries
-		/// to cancel has greater or equal privileges as the origin that created the scheduled task.
-		///
-		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can
-		/// be used. This will only check if two given origins are equal.
-		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;
-
-		/// The maximum number of scheduled calls in the queue for a single block.
-		#[pallet::constant]
-		type MaxScheduledPerBlock: Get<u32>;
-
-		/// Weight information for extrinsics in this pallet.
-		type WeightInfo: WeightInfo;
-
-		/// The preimage provider with which we look up call hashes to get the call.
-		type Preimages: SchedulerPreimages<Self>;
-
-		/// The helper type used for custom transaction fee logic.
-		type CallExecutor: DispatchCall<Self, H160>;
-
-		/// Required origin to set/change calls' priority.
-		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
-	}
-
-	#[pallet::storage]
-	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;
-
-	/// Items to be executed, indexed by the block number that they should be executed on.
-	#[pallet::storage]
-	pub type Agenda<T: Config> = StorageMap<
-		_,
-		Twox64Concat,
-		T::BlockNumber,
-		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,
-		ValueQuery,
-	>;
-
-	/// Lookup from a name to the block number and index of the task.
-	#[pallet::storage]
-	pub(crate) type Lookup<T: Config> =
-		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;
-
-	/// Events type.
-	#[pallet::event]
-	#[pallet::generate_deposit(pub(super) fn deposit_event)]
-	pub enum Event<T: Config> {
-		/// Scheduled some task.
-		Scheduled { when: T::BlockNumber, index: u32 },
-		/// Canceled some task.
-		Canceled { when: T::BlockNumber, index: u32 },
-		/// Dispatched some task.
-		Dispatched {
-			task: TaskAddress<T::BlockNumber>,
-			id: Option<[u8; 32]>,
-			result: DispatchResult,
-		},
-		/// Scheduled task's priority has changed
-		PriorityChanged {
-			when: T::BlockNumber,
-			index: u32,
-			priority: schedule::Priority,
-		},
-		/// The call for the provided hash was not found so the task has been aborted.
-		CallUnavailable {
-			task: TaskAddress<T::BlockNumber>,
-			id: Option<[u8; 32]>,
-		},
-		/// The given task was unable to be renewed since the agenda is full at that block.
-		PeriodicFailed {
-			task: TaskAddress<T::BlockNumber>,
-			id: Option<[u8; 32]>,
-		},
-		/// The given task can never be executed since it is overweight.
-		PermanentlyOverweight {
-			task: TaskAddress<T::BlockNumber>,
-			id: Option<[u8; 32]>,
-		},
-	}
-
-	#[pallet::error]
-	pub enum Error<T> {
-		/// Failed to schedule a call
-		FailedToSchedule,
-		/// There is no place for a new task in the agenda
-		AgendaIsExhausted,
-		/// Scheduled call is corrupted
-		ScheduledCallCorrupted,
-		/// Scheduled call preimage is not found
-		PreimageNotFound,
-		/// Scheduled call is too big
-		TooBigScheduledCall,
-		/// Cannot find the scheduled call.
-		NotFound,
-		/// Given target block number is in the past.
-		TargetBlockNumberInPast,
-		/// Attempt to use a non-named function on a named task.
-		Named,
-	}
-
-	#[pallet::hooks]
-	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		/// Execute the scheduled calls
-		fn on_initialize(now: T::BlockNumber) -> Weight {
-			let mut weight_counter = WeightCounter {
-				used: Weight::zero(),
-				limit: T::MaximumWeight::get(),
-			};
-			Self::service_agendas(&mut weight_counter, now, u32::max_value());
-			weight_counter.used
-		}
-	}
-
-	#[pallet::call]
-	impl<T: Config> Pallet<T> {
-		/// Anonymously schedule a task.
-		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule(
-			origin: OriginFor<T>,
-			when: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule(
-				DispatchTime::At(when),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Cancel an anonymously scheduled task.
-		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]
-		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
-			Ok(())
-		}
-
-		/// Schedule a named task.
-		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_named(
-			origin: OriginFor<T>,
-			id: TaskName,
-			when: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule_named(
-				id,
-				DispatchTime::At(when),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Cancel a named scheduled task.
-		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
-		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_cancel_named(Some(origin.caller().clone()), id)?;
-			Ok(())
-		}
-
-		/// Anonymously schedule a task after a delay.
-		///
-		/// # <weight>
-		/// Same as [`schedule`].
-		/// # </weight>
-		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_after(
-			origin: OriginFor<T>,
-			after: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule(
-				DispatchTime::After(after),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		/// Schedule a named task after a delay.
-		///
-		/// # <weight>
-		/// Same as [`schedule_named`](Self::schedule_named).
-		/// # </weight>
-		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
-		pub fn schedule_named_after(
-			origin: OriginFor<T>,
-			id: TaskName,
-			after: T::BlockNumber,
-			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-			priority: Option<schedule::Priority>,
-			call: Box<<T as Config>::RuntimeCall>,
-		) -> DispatchResult {
-			T::ScheduleOrigin::ensure_origin(origin.clone())?;
-
-			if priority.is_some() {
-				T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			}
-
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_schedule_named(
-				id,
-				DispatchTime::After(after),
-				maybe_periodic,
-				priority.unwrap_or(LOWEST_PRIORITY),
-				origin.caller().clone(),
-				<ScheduledCall<T>>::new(*call)?,
-			)?;
-			Ok(())
-		}
-
-		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]
-		pub fn change_named_priority(
-			origin: OriginFor<T>,
-			id: TaskName,
-			priority: schedule::Priority,
-		) -> DispatchResult {
-			T::PrioritySetOrigin::ensure_origin(origin.clone())?;
-			let origin = <T as Config>::RuntimeOrigin::from(origin);
-			Self::do_change_named_priority(origin.caller().clone(), id, priority)
-		}
-	}
-}
-
-impl<T: Config> Pallet<T> {
-	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
-		let now = frame_system::Pallet::<T>::block_number();
-
-		let when = match when {
-			DispatchTime::At(x) => x,
-			// The current block has already completed it's scheduled tasks, so
-			// Schedule the task at lest one block after this current block.
-			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
-		};
-
-		if when <= now {
-			return Err(Error::<T>::TargetBlockNumberInPast.into());
-		}
-
-		Ok(when)
-	}
-
-	fn place_task(
-		when: T::BlockNumber,
-		what: ScheduledOf<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {
-		let maybe_name = what.maybe_id;
-		let index = Self::push_to_agenda(when, what)?;
-		let address = (when, index);
-		if let Some(name) = maybe_name {
-			Lookup::<T>::insert(name, address)
-		}
-		Self::deposit_event(Event::Scheduled {
-			when: address.0,
-			index: address.1,
-		});
-		Ok(address)
-	}
-
-	fn push_to_agenda(
-		when: T::BlockNumber,
-		what: ScheduledOf<T>,
-	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {
-		let mut agenda = Agenda::<T>::get(when);
-		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
-			// will always succeed due to the above check.
-			let _ = agenda.try_push(Some(what));
-			agenda.len() as u32 - 1
-		} else {
-			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {
-				agenda[hole_index] = Some(what);
-				hole_index as u32
-			} else {
-				return Err((<Error<T>>::AgendaIsExhausted.into(), what));
-			}
-		};
-		Agenda::<T>::insert(when, agenda);
-		Ok(index)
-	}
-
-	fn do_schedule(
-		when: DispatchTime<T::BlockNumber>,
-		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-		priority: schedule::Priority,
-		origin: T::PalletsOrigin,
-		call: ScheduledCall<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		let when = Self::resolve_time(when)?;
-
-		// sanitize maybe_periodic
-		let maybe_periodic = maybe_periodic
-			.filter(|p| p.1 > 1 && !p.0.is_zero())
-			// Remove one from the number of repetitions since we will schedule one now.
-			.map(|(p, c)| (p, c - 1));
-		let task = Scheduled {
-			maybe_id: None,
-			priority,
-			call,
-			maybe_periodic,
-			origin,
-			_phantom: PhantomData,
-		};
-		Self::place_task(when, task).map_err(|x| x.0)
-	}
-
-	fn do_cancel(
-		origin: Option<T::PalletsOrigin>,
-		(when, index): TaskAddress<T::BlockNumber>,
-	) -> Result<(), DispatchError> {
-		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {
-			agenda.get_mut(index as usize).map_or(
-				Ok(None),
-				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
-					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
-						if matches!(
-							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
-							Some(Ordering::Less) | None
-						) {
-							return Err(BadOrigin.into());
-						}
-					};
-					Ok(s.take())
-				},
-			)
-		})?;
-		if let Some(s) = scheduled {
-			T::Preimages::drop(&s.call);
-
-			if let Some(id) = s.maybe_id {
-				Lookup::<T>::remove(id);
-			}
-			Self::deposit_event(Event::Canceled { when, index });
-			Ok(())
-		} else {
-			return Err(Error::<T>::NotFound.into());
-		}
-	}
-
-	fn do_schedule_named(
-		id: TaskName,
-		when: DispatchTime<T::BlockNumber>,
-		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
-		priority: schedule::Priority,
-		origin: T::PalletsOrigin,
-		call: ScheduledCall<T>,
-	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
-		// ensure id it is unique
-		if Lookup::<T>::contains_key(&id) {
-			return Err(Error::<T>::FailedToSchedule.into());
-		}
-
-		let when = Self::resolve_time(when)?;
-
-		// sanitize maybe_periodic
-		let maybe_periodic = maybe_periodic
-			.filter(|p| p.1 > 1 && !p.0.is_zero())
-			// Remove one from the number of repetitions since we will schedule one now.
-			.map(|(p, c)| (p, c - 1));
-
-		let task = Scheduled {
-			maybe_id: Some(id),
-			priority,
-			call,
-			maybe_periodic,
-			origin,
-			_phantom: Default::default(),
-		};
-		Self::place_task(when, task).map_err(|x| x.0)
-	}
-
-	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
-		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
-			if let Some((when, index)) = lookup.take() {
-				let i = index as usize;
-				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
-					if let Some(s) = agenda.get_mut(i) {
-						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
-							if matches!(
-								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
-								Some(Ordering::Less) | None
-							) {
-								return Err(BadOrigin.into());
-							}
-							T::Preimages::drop(&s.call);
-						}
-						*s = None;
-					}
-					Ok(())
-				})?;
-				Self::deposit_event(Event::Canceled { when, index });
-				Ok(())
-			} else {
-				return Err(Error::<T>::NotFound.into());
-			}
-		})
-	}
-
-	fn do_change_named_priority(
-		origin: T::PalletsOrigin,
-		id: TaskName,
-		priority: schedule::Priority,
-	) -> DispatchResult {
-		match Lookup::<T>::get(id) {
-			Some((when, index)) => {
-				let i = index as usize;
-				Agenda::<T>::try_mutate(when, |agenda| {
-					if let Some(Some(s)) = agenda.get_mut(i) {
-						if matches!(
-							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),
-							Some(Ordering::Less) | None
-						) {
-							return Err(BadOrigin.into());
-						}
-
-						s.priority = priority;
-						Self::deposit_event(Event::PriorityChanged {
-							when,
-							index,
-							priority,
-						});
-					}
-					Ok(())
-				})
-			}
-			None => Err(Error::<T>::NotFound.into()),
-		}
-	}
-}
-
-enum ServiceTaskError {
-	/// Could not be executed due to missing preimage.
-	Unavailable,
-	/// Could not be executed due to weight limitations.
-	Overweight,
-}
-use ServiceTaskError::*;
-
-/// A Scheduler-Runtime interface for finer payment handling.
-pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
-	/// Resolve the call dispatch, including any post-dispatch operations.
-	fn dispatch_call(
-		signer: Option<T::AccountId>,
-		function: <T as Config>::RuntimeCall,
-	) -> Result<
-		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
-		TransactionValidityError,
-	>;
-}
-
-impl<T: Config> Pallet<T> {
-	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.
-	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {
-		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {
-			return;
-		}
-
-		let mut incomplete_since = now + One::one();
-		let mut when = IncompleteSince::<T>::take().unwrap_or(now);
-		let mut executed = 0;
-
-		let max_items = T::MaxScheduledPerBlock::get();
-		let mut count_down = max;
-		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);
-		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {
-			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {
-				incomplete_since = incomplete_since.min(when);
-			}
-			when.saturating_inc();
-			count_down.saturating_dec();
-		}
-		incomplete_since = incomplete_since.min(when);
-		if incomplete_since <= now {
-			IncompleteSince::<T>::put(incomplete_since);
-		}
-	}
-
-	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a
-	/// later block.
-	fn service_agenda(
-		weight: &mut WeightCounter,
-		executed: &mut u32,
-		now: T::BlockNumber,
-		when: T::BlockNumber,
-		max: u32,
-	) -> bool {
-		let mut agenda = Agenda::<T>::get(when);
-		let mut ordered = agenda
-			.iter()
-			.enumerate()
-			.filter_map(|(index, maybe_item)| {
-				maybe_item
-					.as_ref()
-					.map(|item| (index as u32, item.priority))
-			})
-			.collect::<Vec<_>>();
-		ordered.sort_by_key(|k| k.1);
-		let within_limit =
-			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));
-		debug_assert!(
-			within_limit,
-			"weight limit should have been checked in advance"
-		);
-
-		// Items which we know can be executed and have postponed for execution in a later block.
-		let mut postponed = (ordered.len() as u32).saturating_sub(max);
-		// Items which we don't know can ever be executed.
-		let mut dropped = 0;
-
-		for (agenda_index, _) in ordered.into_iter().take(max as usize) {
-			let task = match agenda[agenda_index as usize].take() {
-				None => continue,
-				Some(t) => t,
-			};
-			let base_weight = T::WeightInfo::service_task(
-				task.call.lookup_len().map(|x| x as usize),
-				task.maybe_id.is_some(),
-				task.maybe_periodic.is_some(),
-			);
-			if !weight.can_accrue(base_weight) {
-				postponed += 1;
-				break;
-			}
-			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);
-			agenda[agenda_index as usize] = match result {
-				Err((Unavailable, slot)) => {
-					dropped += 1;
-					slot
-				}
-				Err((Overweight, slot)) => {
-					postponed += 1;
-					slot
-				}
-				Ok(()) => {
-					*executed += 1;
-					None
-				}
-			};
-		}
-		if postponed > 0 || dropped > 0 {
-			Agenda::<T>::insert(when, agenda);
-		} else {
-			Agenda::<T>::remove(when);
-		}
-		postponed == 0
-	}
-
-	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.
-	///
-	/// This involves:
-	/// - removing and potentially replacing the `Lookup` entry for the task.
-	/// - realizing the task's call which can include a preimage lookup.
-	/// - Rescheduling the task for execution in a later agenda if periodic.
-	fn service_task(
-		weight: &mut WeightCounter,
-		now: T::BlockNumber,
-		when: T::BlockNumber,
-		agenda_index: u32,
-		is_first: bool,
-		mut task: ScheduledOf<T>,
-	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {
-		let (call, lookup_len) = match T::Preimages::peek(&task.call) {
-			Ok(c) => c,
-			Err(_) => {
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				return Err((Unavailable, Some(task)));
-			}
-		};
-
-		weight.check_accrue(T::WeightInfo::service_task(
-			lookup_len.map(|x| x as usize),
-			task.maybe_id.is_some(),
-			task.maybe_periodic.is_some(),
-		));
-
-		match Self::execute_dispatch(weight, task.origin.clone(), call) {
-			Err(Unavailable) => {
-				debug_assert!(false, "Checked to exist with `peek`");
-
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				Self::deposit_event(Event::CallUnavailable {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-				});
-				Err((Unavailable, Some(task)))
-			}
-			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {
-				T::Preimages::drop(&task.call);
-
-				if let Some(ref id) = task.maybe_id {
-					Lookup::<T>::remove(id);
-				}
-
-				Self::deposit_event(Event::PermanentlyOverweight {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-				});
-				Err((Unavailable, Some(task)))
-			}
-			Err(Overweight) => {
-				// Preserve Lookup -- the task will be postponed.
-				Err((Overweight, Some(task)))
-			}
-			Ok(result) => {
-				Self::deposit_event(Event::Dispatched {
-					task: (when, agenda_index),
-					id: task.maybe_id,
-					result,
-				});
-
-				let is_canceled = task
-					.maybe_id
-					.as_ref()
-					.map(|id| !Lookup::<T>::contains_key(id))
-					.unwrap_or(false);
-
-				match &task.maybe_periodic {
-					&Some((period, count)) if !is_canceled => {
-						if count > 1 {
-							task.maybe_periodic = Some((period, count - 1));
-						} else {
-							task.maybe_periodic = None;
-						}
-						let wake = now.saturating_add(period);
-						match Self::place_task(wake, task) {
-							Ok(_) => {}
-							Err((_, task)) => {
-								// TODO: Leave task in storage somewhere for it to be rescheduled
-								// manually.
-								T::Preimages::drop(&task.call);
-								Self::deposit_event(Event::PeriodicFailed {
-									task: (when, agenda_index),
-									id: task.maybe_id,
-								});
-							}
-						}
-					}
-					_ => {
-						if let Some(ref id) = task.maybe_id {
-							Lookup::<T>::remove(id);
-						}
-
-						T::Preimages::drop(&task.call)
-					}
-				}
-				Ok(())
-			}
-		}
-	}
-
-	fn is_runtime_upgraded() -> bool {
-		let last = system::LastRuntimeUpgrade::<T>::get();
-		let current = T::Version::get();
-
-		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)
-	}
-
-	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`
-	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using
-	/// post info if available).
-	///
-	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the
-	/// call itself).
-	fn execute_dispatch(
-		weight: &mut WeightCounter,
-		origin: T::PalletsOrigin,
-		call: <T as Config>::RuntimeCall,
-	) -> Result<DispatchResult, ServiceTaskError> {
-		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();
-		let base_weight = match dispatch_origin.clone().as_signed() {
-			Some(_) => T::WeightInfo::execute_dispatch_signed(),
-			_ => T::WeightInfo::execute_dispatch_unsigned(),
-		};
-		let call_weight = call.get_dispatch_info().weight;
-		// We only allow a scheduled call if it cannot push the weight past the limit.
-		let max_weight = base_weight.saturating_add(call_weight);
-
-		if !weight.can_accrue(max_weight) {
-			return Err(Overweight);
-		}
-
-		// let scheduled_origin =
-		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());
-		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());
-
-		let r = match ensured_origin {
-			Ok(ScheduledEnsureOriginSuccess::Root) => {
-				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))
-			}
-			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {
-				// Execute transaction via chain default pipeline
-				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken
-				T::CallExecutor::dispatch_call(Some(sender), call.clone())
-			}
-			Err(e) => Ok(Err(e.into())),
-		};
-
-		let (maybe_actual_call_weight, result) = match r {
-			Ok(result) => match result {
-				Ok(post_info) => (post_info.actual_weight, Ok(())),
-				Err(error_and_info) => (
-					error_and_info.post_info.actual_weight,
-					Err(error_and_info.error),
-				),
-			},
-			Err(_) => {
-				log::error!(
-					target: "runtime::scheduler",
-					"Warning: Scheduler has failed to execute a post-dispatch transaction. \
-					This block might have become invalid.");
-				(None, Err(DispatchError::CannotLookup))
-			}
-		};
-		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);
-		weight.check_accrue(base_weight);
-		weight.check_accrue(call_weight);
-		Ok(result)
-	}
-}
deletedpallets/scheduler-v2/src/mock.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/mock.rs
+++ /dev/null
@@ -1,285 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license:
-// This file is part of Substrate.
-
-// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! # Scheduler test environment.
-
-use super::*;
-
-use crate as scheduler;
-use frame_support::{
-	ord_parameter_types, parameter_types,
-	traits::{ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize},
-	weights::constants::RocksDbWeight,
-};
-use frame_system::{EnsureRoot, RawOrigin};
-use sp_core::H256;
-use sp_runtime::{
-	testing::Header,
-	traits::{BlakeTwo256, IdentityLookup},
-	Perbill,
-};
-
-// Logger module to track execution.
-#[frame_support::pallet]
-pub mod logger {
-	use super::{OriginCaller, OriginTrait};
-	use frame_support::{pallet_prelude::*, parameter_types};
-	use frame_system::pallet_prelude::*;
-
-	parameter_types! {
-		static Log: Vec<(OriginCaller, u32)> = Vec::new();
-	}
-	pub fn log() -> Vec<(OriginCaller, u32)> {
-		Log::get().clone()
-	}
-
-	#[pallet::pallet]
-	#[pallet::generate_store(pub(super) trait Store)]
-	pub struct Pallet<T>(PhantomData<T>);
-
-	#[pallet::hooks]
-	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
-
-	#[pallet::config]
-	pub trait Config: frame_system::Config {
-		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
-	}
-
-	#[pallet::event]
-	#[pallet::generate_deposit(pub(super) fn deposit_event)]
-	pub enum Event<T: Config> {
-		Logged(u32, Weight),
-	}
-
-	#[pallet::call]
-	impl<T: Config> Pallet<T>
-	where
-		<T as frame_system::Config>::RuntimeOrigin: OriginTrait<PalletsOrigin = OriginCaller>,
-	{
-		#[pallet::weight(*weight)]
-		pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
-			Self::deposit_event(Event::Logged(i, weight));
-			Log::mutate(|log| {
-				log.push((origin.caller().clone(), i));
-			});
-			Ok(())
-		}
-
-		#[pallet::weight(*weight)]
-		pub fn log_without_filter(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
-			Self::deposit_event(Event::Logged(i, weight));
-			Log::mutate(|log| {
-				log.push((origin.caller().clone(), i));
-			});
-			Ok(())
-		}
-	}
-}
-
-type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
-type Block = frame_system::mocking::MockBlock<Test>;
-
-frame_support::construct_runtime!(
-	pub enum Test where
-		Block = Block,
-		NodeBlock = Block,
-		UncheckedExtrinsic = UncheckedExtrinsic,
-	{
-		System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
-		Logger: logger::{Pallet, Call, Event<T>},
-		Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},
-	}
-);
-
-// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
-pub struct BaseFilter;
-impl Contains<RuntimeCall> for BaseFilter {
-	fn contains(call: &RuntimeCall) -> bool {
-		!matches!(call, RuntimeCall::Logger(LoggerCall::log { .. }))
-	}
-}
-
-parameter_types! {
-	pub BlockWeights: frame_system::limits::BlockWeights =
-		frame_system::limits::BlockWeights::simple_max(
-			Weight::from_ref_time(2_000_000_000_000)
-			// .set_proof_size(u64::MAX),
-		);
-}
-impl system::Config for Test {
-	type BaseCallFilter = BaseFilter;
-	type BlockWeights = BlockWeights;
-	type BlockLength = ();
-	type DbWeight = RocksDbWeight;
-	type RuntimeOrigin = RuntimeOrigin;
-	type RuntimeCall = RuntimeCall;
-	type Index = u64;
-	type BlockNumber = u64;
-	type Hash = H256;
-	type Hashing = BlakeTwo256;
-	type AccountId = u64;
-	type Lookup = IdentityLookup<Self::AccountId>;
-	type Header = Header;
-	type RuntimeEvent = RuntimeEvent;
-	type BlockHashCount = ConstU64<250>;
-	type Version = ();
-	type PalletInfo = PalletInfo;
-	type AccountData = ();
-	type OnNewAccount = ();
-	type OnKilledAccount = ();
-	type SystemWeightInfo = ();
-	type SS58Prefix = ();
-	type OnSetCode = ();
-	type MaxConsumers = ConstU32<16>;
-}
-impl logger::Config for Test {
-	type RuntimeEvent = RuntimeEvent;
-}
-ord_parameter_types! {
-	pub const One: u64 = 1;
-}
-
-pub struct TestWeightInfo;
-impl WeightInfo for TestWeightInfo {
-	fn service_agendas_base() -> Weight {
-		Weight::from_ref_time(0b0000_0001)
-	}
-	fn service_agenda_base(i: u32) -> Weight {
-		Weight::from_ref_time((i << 8) as u64 + 0b0000_0010)
-	}
-	fn service_task_base() -> Weight {
-		Weight::from_ref_time(0b0000_0100)
-	}
-	fn service_task_periodic() -> Weight {
-		Weight::from_ref_time(0b0000_1100)
-	}
-	fn service_task_named() -> Weight {
-		Weight::from_ref_time(0b0001_0100)
-	}
-	fn service_task_fetched(s: u32) -> Weight {
-		Weight::from_ref_time((s << 8) as u64 + 0b0010_0100)
-	}
-	fn execute_dispatch_signed() -> Weight {
-		Weight::from_ref_time(0b0100_0000)
-	}
-	fn execute_dispatch_unsigned() -> Weight {
-		Weight::from_ref_time(0b1000_0000)
-	}
-	fn schedule(_s: u32) -> Weight {
-		Weight::from_ref_time(50)
-	}
-	fn cancel(_s: u32) -> Weight {
-		Weight::from_ref_time(50)
-	}
-	fn schedule_named(_s: u32) -> Weight {
-		Weight::from_ref_time(50)
-	}
-	fn cancel_named(_s: u32) -> Weight {
-		Weight::from_ref_time(50)
-	}
-	fn change_named_priority(_s: u32) -> Weight {
-		Weight::from_ref_time(50)
-	}
-}
-parameter_types! {
-	pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
-		BlockWeights::get().max_block;
-}
-
-pub struct EnsureSignedOneOrRoot;
-impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>> EnsureOrigin<O>
-	for EnsureSignedOneOrRoot
-{
-	type Success = ScheduledEnsureOriginSuccess<u64>;
-	fn try_origin(o: O) -> Result<Self::Success, O> {
-		o.into().and_then(|o| match o {
-			RawOrigin::Root => Ok(ScheduledEnsureOriginSuccess::Root),
-			RawOrigin::Signed(1) => Ok(ScheduledEnsureOriginSuccess::Signed(1)),
-			r => Err(O::from(r)),
-		})
-	}
-}
-
-pub struct Executor;
-impl DispatchCall<Test, sp_core::H160> for Executor {
-	fn dispatch_call(
-		signer: Option<u64>,
-		function: RuntimeCall,
-	) -> Result<
-		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
-		TransactionValidityError,
-	> {
-		let origin = match signer {
-			Some(who) => RuntimeOrigin::signed(who),
-			None => RuntimeOrigin::none(),
-		};
-		Ok(function.dispatch(origin))
-	}
-}
-
-impl Config for Test {
-	type RuntimeEvent = RuntimeEvent;
-	type RuntimeOrigin = RuntimeOrigin;
-	type PalletsOrigin = OriginCaller;
-	type RuntimeCall = RuntimeCall;
-	type MaximumWeight = MaximumSchedulerWeight;
-	type ScheduleOrigin = EnsureSignedOneOrRoot;
-	type MaxScheduledPerBlock = ConstU32<10>;
-	type WeightInfo = TestWeightInfo;
-	type OriginPrivilegeCmp = EqualPrivilegeOnly;
-	type Preimages = ();
-	type PrioritySetOrigin = EnsureRoot<u64>;
-	type CallExecutor = Executor;
-}
-
-pub type LoggerCall = logger::Call<Test>;
-
-pub fn new_test_ext() -> sp_io::TestExternalities {
-	let t = system::GenesisConfig::default()
-		.build_storage::<Test>()
-		.unwrap();
-	t.into()
-}
-
-pub fn run_to_block(n: u64) {
-	while System::block_number() < n {
-		Scheduler::on_finalize(System::block_number());
-		System::set_block_number(System::block_number() + 1);
-		Scheduler::on_initialize(System::block_number());
-	}
-}
-
-pub fn root() -> OriginCaller {
-	system::RawOrigin::Root.into()
-}
deletedpallets/scheduler-v2/src/tests.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/tests.rs
+++ /dev/null
@@ -1,874 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license:
-// This file is part of Substrate.
-
-// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
-// SPDX-License-Identifier: Apache-2.0
-
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// 	http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-//! # Scheduler tests.
-
-use super::*;
-use crate::mock::{
-	logger, new_test_ext, root, run_to_block, LoggerCall, RuntimeCall, Scheduler, Test, *,
-};
-use frame_support::{
-	assert_noop, assert_ok,
-	traits::{Contains, OnInitialize},
-};
-
-#[test]
-fn basic_scheduling_works() {
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
-			&call
-		));
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		run_to_block(3);
-		assert!(logger::log().is_empty());
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(100);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-	});
-}
-
-#[test]
-fn schedule_after_works() {
-	new_test_ext().execute_with(|| {
-		run_to_block(2);
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
-			&call
-		));
-		// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::After(3),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		run_to_block(5);
-		assert!(logger::log().is_empty());
-		run_to_block(6);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(100);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-	});
-}
-
-#[test]
-fn schedule_after_zero_works() {
-	new_test_ext().execute_with(|| {
-		run_to_block(2);
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-		assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
-			&call
-		));
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::After(0),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		// Will trigger on the next block.
-		run_to_block(3);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(100);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-	});
-}
-
-#[test]
-fn periodic_scheduling_works() {
-	new_test_ext().execute_with(|| {
-		// at #4, every 3 blocks, 3 times.
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			Some((3, 3)),
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {
-				i: 42,
-				weight: Weight::from_ref_time(10)
-			}))
-			.unwrap()
-		));
-		run_to_block(3);
-		assert!(logger::log().is_empty());
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(6);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(7);
-		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
-		run_to_block(9);
-		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
-		run_to_block(10);
-		assert_eq!(
-			logger::log(),
-			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
-		);
-		run_to_block(100);
-		assert_eq!(
-			logger::log(),
-			vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
-		);
-	});
-}
-
-#[test]
-fn cancel_named_scheduling_works_with_normal_cancel() {
-	new_test_ext().execute_with(|| {
-		// at #4.
-		Scheduler::do_schedule_named(
-			[1u8; 32],
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
-				i: 69,
-				weight: Weight::from_ref_time(10),
-			}))
-			.unwrap(),
-		)
-		.unwrap();
-		let i = Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
-				i: 42,
-				weight: Weight::from_ref_time(10),
-			}))
-			.unwrap(),
-		)
-		.unwrap();
-		run_to_block(3);
-		assert!(logger::log().is_empty());
-		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
-		assert_ok!(Scheduler::do_cancel(None, i));
-		run_to_block(100);
-		assert!(logger::log().is_empty());
-	});
-}
-
-#[test]
-fn cancel_named_periodic_scheduling_works() {
-	new_test_ext().execute_with(|| {
-		// at #4, every 3 blocks, 3 times.
-		Scheduler::do_schedule_named(
-			[1u8; 32],
-			DispatchTime::At(4),
-			Some((3, 3)),
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
-				i: 42,
-				weight: Weight::from_ref_time(10),
-			}))
-			.unwrap(),
-		)
-		.unwrap();
-		// same id results in error.
-		assert!(Scheduler::do_schedule_named(
-			[1u8; 32],
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
-				i: 69,
-				weight: Weight::from_ref_time(10)
-			}))
-			.unwrap(),
-		)
-		.is_err());
-		// different id is ok.
-		Scheduler::do_schedule_named(
-			[2u8; 32],
-			DispatchTime::At(8),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(RuntimeCall::Logger(LoggerCall::log {
-				i: 69,
-				weight: Weight::from_ref_time(10),
-			}))
-			.unwrap(),
-		)
-		.unwrap();
-		run_to_block(3);
-		assert!(logger::log().is_empty());
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(6);
-		assert_ok!(Scheduler::do_cancel_named(None, [1u8; 32]));
-		run_to_block(100);
-		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
-	});
-}
-
-#[test]
-fn scheduler_respects_weight_limits() {
-	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: max_weight / 3 * 2,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: max_weight / 3 * 2,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		// 69 and 42 do not fit together
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 42u32)]);
-		run_to_block(5);
-		assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
-	});
-}
-
-/// Permanently overweight calls are not deleted but also not executed.
-#[test]
-fn scheduler_does_not_delete_permanently_overweight_call() {
-	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: max_weight,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		// Never executes.
-		run_to_block(100);
-		assert_eq!(logger::log(), vec![]);
-
-		// Assert the `PermanentlyOverweight` event.
-		assert_eq!(
-			System::events().last().unwrap().event,
-			crate::Event::PermanentlyOverweight {
-				task: (4, 0),
-				id: None
-			}
-			.into(),
-		);
-		// The call is still in the agenda.
-		assert!(Agenda::<Test>::get(4)[0].is_some());
-	});
-}
-
-#[test]
-fn scheduler_handles_periodic_failure() {
-	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
-	let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();
-
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: (max_weight / 3) * 2,
-		});
-		let call = <ScheduledCall<Test>>::new(call).unwrap();
-
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			Some((4, u32::MAX)),
-			127,
-			root(),
-			call.clone(),
-		));
-		// Executes 5 times till block 20.
-		run_to_block(20);
-		assert_eq!(logger::log().len(), 5);
-
-		// Block 28 will already be full.
-		for _ in 0..max_per_block {
-			assert_ok!(Scheduler::do_schedule(
-				DispatchTime::At(28),
-				None,
-				120,
-				root(),
-				call.clone(),
-			));
-		}
-
-		// Going to block 24 will emit a `PeriodicFailed` event.
-		run_to_block(24);
-		assert_eq!(logger::log().len(), 6);
-
-		assert_eq!(
-			System::events().last().unwrap().event,
-			crate::Event::PeriodicFailed {
-				task: (24, 0),
-				id: None
-			}
-			.into(),
-		);
-	});
-}
-
-#[test]
-fn scheduler_respects_priority_ordering() {
-	let max_weight: Weight = <Test as Config>::MaximumWeight::get();
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: max_weight / 3,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			1,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: max_weight / 3,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			0,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
-	});
-}
-
-#[test]
-fn scheduler_respects_priority_ordering_with_soft_deadlines() {
-	new_test_ext().execute_with(|| {
-		let max_weight: Weight = <Test as Config>::MaximumWeight::get();
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: max_weight / 5 * 2,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			255,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: max_weight / 5 * 2,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 2600,
-			weight: max_weight / 5 * 4,
-		});
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			126,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-
-		// 2600 does not fit with 69 or 42, but has higher priority, so will go through
-		run_to_block(4);
-		assert_eq!(logger::log(), vec![(root(), 2600u32)]);
-		// 69 and 42 fit together
-		run_to_block(5);
-		assert_eq!(
-			logger::log(),
-			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
-		);
-	});
-}
-
-#[test]
-fn on_initialize_weight_is_correct() {
-	new_test_ext().execute_with(|| {
-		let call_weight = Weight::from_ref_time(25);
-
-		// Named
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 3,
-			weight: call_weight + Weight::from_ref_time(1),
-		});
-		assert_ok!(Scheduler::do_schedule_named(
-			[1u8; 32],
-			DispatchTime::At(3),
-			None,
-			255,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: call_weight + Weight::from_ref_time(2),
-		});
-		// Anon Periodic
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(2),
-			Some((1000, 3)),
-			128,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: call_weight + Weight::from_ref_time(3),
-		});
-		// Anon
-		assert_ok!(Scheduler::do_schedule(
-			DispatchTime::At(2),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-		// Named Periodic
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 2600,
-			weight: call_weight + Weight::from_ref_time(4),
-		});
-		assert_ok!(Scheduler::do_schedule_named(
-			[2u8; 32],
-			DispatchTime::At(1),
-			Some((1000, 3)),
-			126,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		));
-
-		// Will include the named periodic only
-		assert_eq!(
-			Scheduler::on_initialize(1),
-			TestWeightInfo::service_agendas_base()
-				+ TestWeightInfo::service_agenda_base(1)
-				+ <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, true)
-				+ TestWeightInfo::execute_dispatch_unsigned()
-				+ call_weight + Weight::from_ref_time(4)
-		);
-		assert_eq!(IncompleteSince::<Test>::get(), None);
-		assert_eq!(logger::log(), vec![(root(), 2600u32)]);
-
-		// Will include anon and anon periodic
-		assert_eq!(
-			Scheduler::on_initialize(2),
-			TestWeightInfo::service_agendas_base()
-				+ TestWeightInfo::service_agenda_base(2)
-				+ <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, true)
-				+ TestWeightInfo::execute_dispatch_unsigned()
-				+ call_weight + Weight::from_ref_time(3)
-				+ <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, false)
-				+ TestWeightInfo::execute_dispatch_unsigned()
-				+ call_weight + Weight::from_ref_time(2)
-		);
-		assert_eq!(IncompleteSince::<Test>::get(), None);
-		assert_eq!(
-			logger::log(),
-			vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
-		);
-
-		// Will include named only
-		assert_eq!(
-			Scheduler::on_initialize(3),
-			TestWeightInfo::service_agendas_base()
-				+ TestWeightInfo::service_agenda_base(1)
-				+ <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, false)
-				+ TestWeightInfo::execute_dispatch_unsigned()
-				+ call_weight + Weight::from_ref_time(1)
-		);
-		assert_eq!(IncompleteSince::<Test>::get(), None);
-		assert_eq!(
-			logger::log(),
-			vec![
-				(root(), 2600u32),
-				(root(), 69u32),
-				(root(), 42u32),
-				(root(), 3u32)
-			]
-		);
-
-		// Will contain none
-		let actual_weight = Scheduler::on_initialize(4);
-		assert_eq!(
-			actual_weight,
-			TestWeightInfo::service_agendas_base() + TestWeightInfo::service_agenda_base(0)
-		);
-	});
-}
-
-#[test]
-fn root_calls_works() {
-	new_test_ext().execute_with(|| {
-		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-		assert_ok!(Scheduler::schedule_named(
-			RuntimeOrigin::root(),
-			[1u8; 32],
-			4,
-			None,
-			Some(127),
-			call,
-		));
-		assert_ok!(Scheduler::schedule(
-			RuntimeOrigin::root(),
-			4,
-			None,
-			Some(127),
-			call2
-		));
-		run_to_block(3);
-		// Scheduled calls are in the agenda.
-		assert_eq!(Agenda::<Test>::get(4).len(), 2);
-		assert!(logger::log().is_empty());
-		assert_ok!(Scheduler::cancel_named(RuntimeOrigin::root(), [1u8; 32]));
-		assert_ok!(Scheduler::cancel(RuntimeOrigin::root(), 4, 1));
-		// Scheduled calls are made NONE, so should not effect state
-		run_to_block(100);
-		assert!(logger::log().is_empty());
-	});
-}
-
-#[test]
-fn fails_to_schedule_task_in_the_past() {
-	new_test_ext().execute_with(|| {
-		run_to_block(3);
-
-		let call1 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call3 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-
-		assert_noop!(
-			Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 2, None, Some(127), call1),
-			Error::<Test>::TargetBlockNumberInPast,
-		);
-
-		assert_noop!(
-			Scheduler::schedule(RuntimeOrigin::root(), 2, None, Some(127), call2),
-			Error::<Test>::TargetBlockNumberInPast,
-		);
-
-		assert_noop!(
-			Scheduler::schedule(RuntimeOrigin::root(), 3, None, Some(127), call3),
-			Error::<Test>::TargetBlockNumberInPast,
-		);
-	});
-}
-
-#[test]
-fn should_use_origin() {
-	new_test_ext().execute_with(|| {
-		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-		assert_ok!(Scheduler::schedule_named(
-			system::RawOrigin::Signed(1).into(),
-			[1u8; 32],
-			4,
-			None,
-			None,
-			call,
-		));
-		assert_ok!(Scheduler::schedule(
-			system::RawOrigin::Signed(1).into(),
-			4,
-			None,
-			None,
-			call2,
-		));
-		run_to_block(3);
-		// Scheduled calls are in the agenda.
-		assert_eq!(Agenda::<Test>::get(4).len(), 2);
-		assert!(logger::log().is_empty());
-		assert_ok!(Scheduler::cancel_named(
-			system::RawOrigin::Signed(1).into(),
-			[1u8; 32]
-		));
-		assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
-		// Scheduled calls are made NONE, so should not effect state
-		run_to_block(100);
-		assert!(logger::log().is_empty());
-	});
-}
-
-#[test]
-fn should_check_origin() {
-	new_test_ext().execute_with(|| {
-		let call = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 69,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-		assert_noop!(
-			Scheduler::schedule_named(
-				system::RawOrigin::Signed(2).into(),
-				[1u8; 32],
-				4,
-				None,
-				None,
-				call
-			),
-			BadOrigin
-		);
-		assert_noop!(
-			Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, None, call2),
-			BadOrigin
-		);
-	});
-}
-
-#[test]
-fn should_check_origin_for_cancel() {
-	new_test_ext().execute_with(|| {
-		let call = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
-			i: 69,
-			weight: Weight::from_ref_time(10),
-		}));
-		let call2 = Box::new(RuntimeCall::Logger(LoggerCall::log_without_filter {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		}));
-		assert_ok!(Scheduler::schedule_named(
-			system::RawOrigin::Signed(1).into(),
-			[1u8; 32],
-			4,
-			None,
-			None,
-			call,
-		));
-		assert_ok!(Scheduler::schedule(
-			system::RawOrigin::Signed(1).into(),
-			4,
-			None,
-			None,
-			call2,
-		));
-		run_to_block(3);
-		// Scheduled calls are in the agenda.
-		assert_eq!(Agenda::<Test>::get(4).len(), 2);
-		assert!(logger::log().is_empty());
-		assert_noop!(
-			Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),
-			BadOrigin
-		);
-		assert_noop!(
-			Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
-			BadOrigin
-		);
-		assert_noop!(
-			Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),
-			BadOrigin
-		);
-		assert_noop!(
-			Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
-			BadOrigin
-		);
-		run_to_block(5);
-		assert_eq!(
-			logger::log(),
-			vec![
-				(system::RawOrigin::Signed(1).into(), 69u32),
-				(system::RawOrigin::Signed(1).into(), 42u32)
-			]
-		);
-	});
-}
-
-/// Cancelling a call and then scheduling a second call for the same
-/// block results in different addresses.
-#[test]
-fn schedule_does_not_resuse_addr() {
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-
-		// Schedule both calls.
-		let addr_1 = Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call.clone()).unwrap(),
-		)
-		.unwrap();
-		// Cancel the call.
-		assert_ok!(Scheduler::do_cancel(None, addr_1));
-		let addr_2 = Scheduler::do_schedule(
-			DispatchTime::At(4),
-			None,
-			127,
-			root(),
-			<ScheduledCall<Test>>::new(call).unwrap(),
-		)
-		.unwrap();
-
-		// Should not re-use the address.
-		assert!(addr_1 != addr_2);
-	});
-}
-
-#[test]
-fn schedule_agenda_overflows() {
-	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
-
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-		let call = <ScheduledCall<Test>>::new(call).unwrap();
-
-		// Schedule the maximal number allowed per block.
-		for _ in 0..max {
-			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();
-		}
-
-		// One more time and it errors.
-		assert_noop!(
-			Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call,),
-			<Error<Test>>::AgendaIsExhausted,
-		);
-
-		run_to_block(4);
-		// All scheduled calls are executed.
-		assert_eq!(logger::log().len() as u32, max);
-	});
-}
-
-/// Cancelling and scheduling does not overflow the agenda but fills holes.
-#[test]
-fn cancel_and_schedule_fills_holes() {
-	let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
-	assert!(
-		max > 3,
-		"This test only makes sense for MaxScheduledPerBlock > 3"
-	);
-
-	new_test_ext().execute_with(|| {
-		let call = RuntimeCall::Logger(LoggerCall::log {
-			i: 42,
-			weight: Weight::from_ref_time(10),
-		});
-		let call = <ScheduledCall<Test>>::new(call).unwrap();
-		let mut addrs = Vec::<_>::default();
-
-		// Schedule the maximal number allowed per block.
-		for _ in 0..max {
-			addrs.push(
-				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
-					.unwrap(),
-			);
-		}
-		// Cancel three of them.
-		for addr in addrs.into_iter().take(3) {
-			Scheduler::do_cancel(None, addr).unwrap();
-		}
-		// Schedule three new ones.
-		for i in 0..3 {
-			let (_block, index) =
-				Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
-					.unwrap();
-			assert_eq!(i, index);
-		}
-
-		run_to_block(4);
-		// Maximum number of calls are executed.
-		assert_eq!(logger::log().len() as u32, max);
-	});
-}
deletedpallets/scheduler-v2/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/weights.rs
+++ /dev/null
@@ -1,270 +0,0 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license:
-// This file is part of Substrate.
-
-// Copyright (C) 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.
-
-//! Autogenerated weights for pallet_scheduler
-//!
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-10-03, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
-//! HOSTNAME: `bm3`, CPU: `Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz`
-//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
-
-// Executed Command:
-// /home/benchbot/cargo_target_dir/production/substrate
-// benchmark
-// pallet
-// --steps=50
-// --repeat=20
-// --extrinsic=*
-// --execution=wasm
-// --wasm-execution=compiled
-// --heap-pages=4096
-// --pallet=pallet_scheduler
-// --chain=dev
-// --output=./frame/scheduler/src/weights.rs
-// --template=./.maintain/frame-weight-template.hbs
-
-#![cfg_attr(rustfmt, rustfmt_skip)]
-#![allow(unused_parens)]
-#![allow(unused_imports)]
-
-use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
-use sp_std::marker::PhantomData;
-
-/// Weight functions needed for pallet_scheduler.
-pub trait WeightInfo {
-	fn service_agendas_base() -> Weight;
-	fn service_agenda_base(s: u32, ) -> Weight;
-	fn service_task_base() -> Weight;
-	fn service_task_fetched(s: u32, ) -> Weight;
-	fn service_task_named() -> Weight;
-	fn service_task_periodic() -> Weight;
-	fn execute_dispatch_signed() -> Weight;
-	fn execute_dispatch_unsigned() -> Weight;
-	fn schedule(s: u32, ) -> Weight;
-	fn cancel(s: u32, ) -> Weight;
-	fn schedule_named(s: u32, ) -> Weight;
-	fn cancel_named(s: u32, ) -> Weight;
-	fn change_named_priority(s: u32, ) -> Weight;
-}
-
-/// Weights for pallet_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 IncompleteSince (r:1 w:1)
-	fn service_agendas_base() -> Weight {
-		Weight::from_ref_time(4_992_000 as u64)
-			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().writes(1 as u64))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 512]`.
-	fn service_agenda_base(s: u32, ) -> Weight {
-		Weight::from_ref_time(4_320_000 as u64)
-			// Standard Error: 619
-			.saturating_add(Weight::from_ref_time(336_713 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().writes(1 as u64))
-	}
-	fn service_task_base() -> Weight {
-		Weight::from_ref_time(10_864_000 as u64)
-	}
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	/// The range of component `s` is `[128, 4194304]`.
-	fn service_task_fetched(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_586_000 as u64)
-			// Standard Error: 1
-			.saturating_add(Weight::from_ref_time(1_138 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn service_task_named() -> Weight {
-		Weight::from_ref_time(13_127_000 as u64)
-			.saturating_add(T::DbWeight::get().writes(1 as u64))
-	}
-	fn service_task_periodic() -> Weight {
-		Weight::from_ref_time(11_053_000 as u64)
-	}
-	fn execute_dispatch_signed() -> Weight {
-		Weight::from_ref_time(4_158_000 as u64)
-	}
-	fn execute_dispatch_unsigned() -> Weight {
-		Weight::from_ref_time(4_104_000 as u64)
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 511]`.
-	fn schedule(s: u32, ) -> Weight {
-		Weight::from_ref_time(20_074_000 as u64)
-			// Standard Error: 765
-			.saturating_add(Weight::from_ref_time(343_285 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().writes(1 as u64))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	/// The range of component `s` is `[1, 512]`.
-	fn cancel(s: u32, ) -> Weight {
-		Weight::from_ref_time(21_509_000 as u64)
-			// Standard Error: 708
-			.saturating_add(Weight::from_ref_time(323_013 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(1 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 511]`.
-	fn schedule_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(22_427_000 as u64)
-			// Standard Error: 850
-			.saturating_add(Weight::from_ref_time(357_265 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[1, 512]`.
-	fn cancel_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(22_875_000 as u64)
-			// Standard Error: 693
-			.saturating_add(Weight::from_ref_time(336_643 as u64).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn change_named_priority(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_642_000)
-			// Standard Error: 0
-			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
-			.saturating_add(T::DbWeight::get().reads(2 as u64))
-			.saturating_add(T::DbWeight::get().writes(2 as u64))
-	}
-}
-
-// For backwards compatibility and tests
-impl WeightInfo for () {
-	// Storage: Scheduler IncompleteSince (r:1 w:1)
-	fn service_agendas_base() -> Weight {
-		Weight::from_ref_time(4_992_000 as u64)
-			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().writes(1 as u64))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 512]`.
-	fn service_agenda_base(s: u32, ) -> Weight {
-		Weight::from_ref_time(4_320_000 as u64)
-			// Standard Error: 619
-			.saturating_add(Weight::from_ref_time(336_713 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().writes(1 as u64))
-	}
-	fn service_task_base() -> Weight {
-		Weight::from_ref_time(10_864_000 as u64)
-	}
-	// Storage: Preimage PreimageFor (r:1 w:1)
-	// Storage: Preimage StatusFor (r:1 w:1)
-	/// The range of component `s` is `[128, 4194304]`.
-	fn service_task_fetched(s: u32, ) -> Weight {
-		Weight::from_ref_time(24_586_000 as u64)
-			// Standard Error: 1
-			.saturating_add(Weight::from_ref_time(1_138 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:0 w:1)
-	fn service_task_named() -> Weight {
-		Weight::from_ref_time(13_127_000 as u64)
-			.saturating_add(RocksDbWeight::get().writes(1 as u64))
-	}
-	fn service_task_periodic() -> Weight {
-		Weight::from_ref_time(11_053_000 as u64)
-	}
-	fn execute_dispatch_signed() -> Weight {
-		Weight::from_ref_time(4_158_000 as u64)
-	}
-	fn execute_dispatch_unsigned() -> Weight {
-		Weight::from_ref_time(4_104_000 as u64)
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 511]`.
-	fn schedule(s: u32, ) -> Weight {
-		Weight::from_ref_time(20_074_000 as u64)
-			// Standard Error: 765
-			.saturating_add(Weight::from_ref_time(343_285 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().writes(1 as u64))
-	}
-	// Storage: Scheduler Agenda (r:1 w:1)
-	// Storage: Scheduler Lookup (r:0 w:1)
-	/// The range of component `s` is `[1, 512]`.
-	fn cancel(s: u32, ) -> Weight {
-		Weight::from_ref_time(21_509_000 as u64)
-			// Standard Error: 708
-			.saturating_add(Weight::from_ref_time(323_013 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(1 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[0, 511]`.
-	fn schedule_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(22_427_000 as u64)
-			// Standard Error: 850
-			.saturating_add(Weight::from_ref_time(357_265 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	/// The range of component `s` is `[1, 512]`.
-	fn cancel_named(s: u32, ) -> Weight {
-		Weight::from_ref_time(22_875_000 as u64)
-			// Standard Error: 693
-			.saturating_add(Weight::from_ref_time(336_643 as u64).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-
-	// Storage: Scheduler Lookup (r:1 w:1)
-	// Storage: Scheduler Agenda (r:1 w:1)
-	fn change_named_priority(s: u32, ) -> Weight {
-		Weight::from_ref_time(8_642_000)
-			// Standard Error: 0
-			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
-			.saturating_add(RocksDbWeight::get().reads(2 as u64))
-			.saturating_add(RocksDbWeight::get().writes(2 as u64))
-	}
-}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
before · primitives/data-structs/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//! # Primitives crate.18//!19//! This crate contains types, traits and constants.2021#![cfg_attr(not(feature = "std"), no_std)]2223use core::{24	convert::{TryFrom, TryInto},25	fmt,26};27use frame_support::{28	storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},29	traits::Get,30	parameter_types,31};3233#[cfg(feature = "serde")]34use serde::{Serialize, Deserialize};3536use sp_core::U256;37use sp_runtime::{ArithmeticError, sp_std::prelude::Vec, Permill};38use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};39use bondrewd::Bitfields;40use frame_support::{BoundedVec, traits::ConstU32};41use derivative::Derivative;42use scale_info::TypeInfo;4344// RMRK45use rmrk_traits::{46	CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme, ThemeProperty,47	ResourceTypes, BasicResource, ComposableResource, SlotResource, EquippableList,48};49pub use rmrk_traits::{50	primitives::{51		CollectionId as RmrkCollectionId, NftId as RmrkNftId, BaseId as RmrkBaseId,52		SlotId as RmrkSlotId, PartId as RmrkPartId, ResourceId as RmrkResourceId,53	},54	NftChild as RmrkNftChild, AccountIdOrCollectionNftTuple as RmrkAccountIdOrCollectionNftTuple,55	FixedPart as RmrkFixedPart, SlotPart as RmrkSlotPart,56};5758mod bondrewd_codec;59mod bounded;60pub mod budget;61pub mod mapping;62mod migration;6364/// Maximum of decimal points.65pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;6667/// Maximum pieces for refungible token.68pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;69pub const MAX_SPONSOR_TIMEOUT: u32 = 10_368_000;7071/// Maximum tokens for user.72pub const MAX_TOKEN_OWNERSHIP: u32 = if cfg!(not(feature = "limit-testing")) {73	100_00074} else {75	1076};7778/// Maximum for collections can be created.79pub const COLLECTION_NUMBER_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {80	100_00081} else {82	1083};8485/// Maximum for various custom data of token.86pub const CUSTOM_DATA_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {87	204888} else {89	1090};9192/// Maximum admins per collection.93pub const COLLECTION_ADMINS_LIMIT: u32 = 5;9495/// Maximum tokens per collection.96pub const COLLECTION_TOKEN_LIMIT: u32 = u32::MAX;9798/// Maximum tokens per account.99pub const ACCOUNT_TOKEN_OWNERSHIP_LIMIT: u32 = if cfg!(not(feature = "limit-testing")) {100	1_000_000101} else {102	10103};104105/// Default timeout for transfer sponsoring NFT item.106pub const NFT_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;107/// Default timeout for transfer sponsoring fungible item.108pub const FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;109/// Default timeout for transfer sponsoring refungible item.110pub const REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT: u32 = 5;111112/// Default timeout for sponsored approving.113pub const SPONSOR_APPROVE_TIMEOUT: u32 = 5;114115// Schema limits116pub const OFFCHAIN_SCHEMA_LIMIT: u32 = 8192;117pub const VARIABLE_ON_CHAIN_SCHEMA_LIMIT: u32 = 8192;118pub const CONST_ON_CHAIN_SCHEMA_LIMIT: u32 = 32768;119120// TODO: not used. Delete?121pub const COLLECTION_FIELD_LIMIT: u32 = CONST_ON_CHAIN_SCHEMA_LIMIT;122123/// Maximum length for collection name.124pub const MAX_COLLECTION_NAME_LENGTH: u32 = 64;125126/// Maximum length for collection description.127pub const MAX_COLLECTION_DESCRIPTION_LENGTH: u32 = 256;128129/// Maximal token prefix length.130pub const MAX_TOKEN_PREFIX_LENGTH: u32 = 16;131132/// Maximal lenght of property key.133pub const MAX_PROPERTY_KEY_LENGTH: u32 = 256;134135/// Maximal lenght of property value.136pub const MAX_PROPERTY_VALUE_LENGTH: u32 = 32768;137138/// Maximum properties that can be assigned to token.139pub const MAX_PROPERTIES_PER_ITEM: u32 = 64;140141/// Maximal lenght of extended property value.142pub const MAX_AUX_PROPERTY_VALUE_LENGTH: u32 = 2048;143144/// Maximum size for all collection properties.145pub const MAX_COLLECTION_PROPERTIES_SIZE: u32 = 40960;146147/// Maximum size for all token properties.148pub const MAX_TOKEN_PROPERTIES_SIZE: u32 = 32768;149150/// How much items can be created per single151/// create_many call.152pub const MAX_ITEMS_PER_BATCH: u32 = 200;153154/// Used for limit bounded types of token custom data.155pub type CustomDataLimit = ConstU32<CUSTOM_DATA_LIMIT>;156157/// Collection id.158#[derive(159	Encode,160	Decode,161	PartialEq,162	Eq,163	PartialOrd,164	Ord,165	Clone,166	Copy,167	Debug,168	Default,169	TypeInfo,170	MaxEncodedLen,171)]172#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]173pub struct CollectionId(pub u32);174impl EncodeLike<u32> for CollectionId {}175impl EncodeLike<CollectionId> for u32 {}176177/// Token id.178#[derive(179	Encode,180	Decode,181	PartialEq,182	Eq,183	PartialOrd,184	Ord,185	Clone,186	Copy,187	Debug,188	Default,189	TypeInfo,190	MaxEncodedLen,191)]192#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]193pub struct TokenId(pub u32);194impl EncodeLike<u32> for TokenId {}195impl EncodeLike<TokenId> for u32 {}196197impl TokenId {198	/// Try to get next token id.199	///200	/// If next id cause overflow, then [`ArithmeticError::Overflow`] returned.201	pub fn try_next(self) -> Result<TokenId, ArithmeticError> {202		self.0203			.checked_add(1)204			.ok_or(ArithmeticError::Overflow)205			.map(Self)206	}207}208209impl From<TokenId> for U256 {210	fn from(t: TokenId) -> Self {211		t.0.into()212	}213}214215impl TryFrom<U256> for TokenId {216	type Error = &'static str;217218	fn try_from(value: U256) -> Result<Self, Self::Error> {219		Ok(TokenId(value.try_into().map_err(|_| "too large token id")?))220	}221}222223/// Token data.224#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]225#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]226pub struct TokenData<CrossAccountId> {227	/// Properties of token.228	pub properties: Vec<Property>,229230	/// Token owner.231	pub owner: Option<CrossAccountId>,232233	/// Token pieces.234	pub pieces: u128,235}236237// TODO: unused type238pub struct OverflowError;239impl From<OverflowError> for &'static str {240	fn from(_: OverflowError) -> Self {241		"overflow occured"242	}243}244245/// Alias for decimal points type.246pub type DecimalPoints = u8;247248/// Collection mode.249///250/// Collection can represent various types of tokens.251/// Each collection can contain only one type of tokens at a time.252/// This type helps to understand which tokens the collection contains.253#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]254#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]255pub enum CollectionMode {256	/// Non fungible tokens.257	NFT,258	/// Fungible tokens.259	Fungible(DecimalPoints),260	/// Refungible tokens.261	ReFungible,262}263264impl CollectionMode {265	/// Get collection mod as number.266	pub fn id(&self) -> u8 {267		match self {268			CollectionMode::NFT => 1,269			CollectionMode::Fungible(_) => 2,270			CollectionMode::ReFungible => 3,271		}272	}273}274275// TODO: unused trait276pub trait SponsoringResolve<AccountId, Call> {277	fn resolve(who: &AccountId, call: &Call) -> Option<AccountId>;278}279280/// Access mode for some token operations.281#[derive(Encode, Decode, Eq, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]282#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]283pub enum AccessMode {284	/// Access grant for owner and admins. Used as default.285	Normal,286	/// Like a [`Normal`](AccessMode::Normal) but also users in allow list.287	AllowList,288}289impl Default for AccessMode {290	fn default() -> Self {291		Self::Normal292	}293}294295// TODO: remove in future.296#[derive(Encode, Decode, Eq, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]297#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]298pub enum SchemaVersion {299	ImageURL,300	Unique,301}302impl Default for SchemaVersion {303	fn default() -> Self {304		Self::ImageURL305	}306}307308// TODO: unused type309#[derive(Encode, Decode, Default, Debug, Clone, PartialEq, TypeInfo)]310#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]311pub struct Ownership<AccountId> {312	pub owner: AccountId,313	pub fraction: u128,314}315316/// The state of collection sponsorship.317#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]318#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]319pub enum SponsorshipState<AccountId> {320	/// The fees are applied to the transaction sender.321	Disabled,322	/// The sponsor is under consideration. Until the sponsor gives his consent,323	/// the fee will still be charged to sender.324	Unconfirmed(AccountId),325	/// Transactions are sponsored by specified account.326	Confirmed(AccountId),327}328329impl<AccountId> SponsorshipState<AccountId> {330	/// Get a sponsor of the collection who has confirmed his status.331	pub fn sponsor(&self) -> Option<&AccountId> {332		match self {333			Self::Confirmed(sponsor) => Some(sponsor),334			_ => None,335		}336	}337338	/// Get a sponsor of the collection who has pending or confirmed status.339	pub fn pending_sponsor(&self) -> Option<&AccountId> {340		match self {341			Self::Unconfirmed(sponsor) | Self::Confirmed(sponsor) => Some(sponsor),342			_ => None,343		}344	}345346	/// Whether the sponsorship is confirmed.347	pub fn confirmed(&self) -> bool {348		matches!(self, Self::Confirmed(_))349	}350}351352impl<T> Default for SponsorshipState<T> {353	fn default() -> Self {354		Self::Disabled355	}356}357358pub type CollectionName = BoundedVec<u16, ConstU32<MAX_COLLECTION_NAME_LENGTH>>;359pub type CollectionDescription = BoundedVec<u16, ConstU32<MAX_COLLECTION_DESCRIPTION_LENGTH>>;360pub type CollectionTokenPrefix = BoundedVec<u8, ConstU32<MAX_TOKEN_PREFIX_LENGTH>>;361362#[derive(Bitfields, Clone, Copy, PartialEq, Eq, Debug, Default)]363#[bondrewd(enforce_bytes = 1)]364pub struct CollectionFlags {365	/// Tokens in foreign collections can be transferred, but not burnt366	#[bondrewd(bits = "0..1")]367	pub foreign: bool,368	/// Supports ERC721Metadata369	#[bondrewd(bits = "1..2")]370	pub erc721metadata: bool,371	/// External collections can't be managed using `unique` api372	#[bondrewd(bits = "7..8")]373	pub external: bool,374375	#[bondrewd(reserve, bits = "2..7")]376	pub reserved: u8,377}378bondrewd_codec!(CollectionFlags);379380/// Base structure for represent collection.381///382/// Used to provide basic functionality for all types of collections.383///384/// #### Note385/// Collection parameters, used in storage (see [`RpcCollection`] for the RPC version).386#[struct_versioning::versioned(version = 2, upper)]387#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen)]388pub struct Collection<AccountId> {389	/// Collection owner account.390	pub owner: AccountId,391392	/// Collection mode.393	pub mode: CollectionMode,394395	/// Access mode.396	#[version(..2)]397	pub access: AccessMode,398399	/// Collection name.400	pub name: CollectionName,401402	/// Collection description.403	pub description: CollectionDescription,404405	/// Token prefix.406	pub token_prefix: CollectionTokenPrefix,407408	#[version(..2)]409	pub mint_mode: bool,410411	#[version(..2)]412	pub offchain_schema: BoundedVec<u8, ConstU32<OFFCHAIN_SCHEMA_LIMIT>>,413414	#[version(..2)]415	pub schema_version: SchemaVersion,416417	/// The state of sponsorship of the collection.418	pub sponsorship: SponsorshipState<AccountId>,419420	/// Collection limits.421	pub limits: CollectionLimits,422423	/// Collection permissions.424	#[version(2.., upper(Default::default()))]425	pub permissions: CollectionPermissions,426427	#[version(2.., upper(Default::default()))]428	pub flags: CollectionFlags,429430	#[version(..2)]431	pub variable_on_chain_schema: BoundedVec<u8, ConstU32<VARIABLE_ON_CHAIN_SCHEMA_LIMIT>>,432433	#[version(..2)]434	pub const_on_chain_schema: BoundedVec<u8, ConstU32<CONST_ON_CHAIN_SCHEMA_LIMIT>>,435436	#[version(..2)]437	pub meta_update_permission: MetaUpdatePermission,438}439440#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]441#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]442pub struct RpcCollectionFlags {443	/// Is collection is foreign.444	pub foreign: bool,445	/// Collection supports ERC721Metadata.446	pub erc721metadata: bool,447}448449/// Collection parameters, used in RPC calls (see [`Collection`] for the storage version).450#[struct_versioning::versioned(version = 2, upper)]451#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]452#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]453pub struct RpcCollection<AccountId> {454	/// Collection owner account.455	pub owner: AccountId,456457	/// Collection mode.458	pub mode: CollectionMode,459460	/// Collection name.461	pub name: Vec<u16>,462463	/// Collection description.464	pub description: Vec<u16>,465466	/// Token prefix.467	pub token_prefix: Vec<u8>,468469	/// The state of sponsorship of the collection.470	pub sponsorship: SponsorshipState<AccountId>,471472	/// Collection limits.473	pub limits: CollectionLimits,474475	/// Collection permissions.476	pub permissions: CollectionPermissions,477478	/// Token property permissions.479	pub token_property_permissions: Vec<PropertyKeyPermission>,480481	/// Collection properties.482	pub properties: Vec<Property>,483484	/// Is collection read only.485	pub read_only: bool,486487	/// Extra collection flags488	#[version(2.., upper(RpcCollectionFlags {foreign: false, erc721metadata: false}))]489	pub flags: RpcCollectionFlags,490}491492/// Data used for create collection.493///494/// All fields are wrapped in [`Option`], where `None` means chain default.495#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, Derivative, MaxEncodedLen)]496#[derivative(Debug, Default(bound = ""))]497pub struct CreateCollectionData<AccountId> {498	/// Collection mode.499	#[derivative(Default(value = "CollectionMode::NFT"))]500	pub mode: CollectionMode,501502	/// Access mode.503	pub access: Option<AccessMode>,504505	/// Collection name.506	pub name: CollectionName,507508	/// Collection description.509	pub description: CollectionDescription,510511	/// Token prefix.512	pub token_prefix: CollectionTokenPrefix,513514	/// Pending collection sponsor.515	pub pending_sponsor: Option<AccountId>,516517	/// Collection limits.518	pub limits: Option<CollectionLimits>,519520	/// Collection permissions.521	pub permissions: Option<CollectionPermissions>,522523	/// Token property permissions.524	pub token_property_permissions: CollectionPropertiesPermissionsVec,525526	/// Collection properties.527	pub properties: CollectionPropertiesVec,528}529530/// Bounded vector of properties permissions. Max length is [`MAX_PROPERTIES_PER_ITEM`].531// TODO: maybe rename to PropertiesPermissionsVec532pub type CollectionPropertiesPermissionsVec =533	BoundedVec<PropertyKeyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;534535/// Bounded vector of properties. Max length is [`MAX_PROPERTIES_PER_ITEM`].536pub type CollectionPropertiesVec = BoundedVec<Property, ConstU32<MAX_PROPERTIES_PER_ITEM>>;537538/// Limits and restrictions of a collection.539///540/// All fields are wrapped in [`Option`], where `None` means chain default.541///542/// Update with `pallet_common::Pallet::clamp_limits`.543// IMPORTANT: When adding/removing fields from this struct - don't forget to also544#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]545#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]546// When adding/removing fields from this struct - don't forget to also update with `pallet_common::Pallet::clamp_limits`.547// TODO: move `pallet_common::Pallet::clamp_limits` into `impl CollectionLimits`.548// TODO: may be remove [`Option`] and **pub** from fields and create struct with default values.549pub struct CollectionLimits {550	/// How many tokens can a user have on one account.551	/// * Default - [`ACCOUNT_TOKEN_OWNERSHIP_LIMIT`].552	/// * Limit - [`MAX_TOKEN_OWNERSHIP`].553	pub account_token_ownership_limit: Option<u32>,554555	/// How many bytes of data are available for sponsorship.556	/// * Default - [`CUSTOM_DATA_LIMIT`].557	/// * Limit - [`CUSTOM_DATA_LIMIT`].558	pub sponsored_data_size: Option<u32>,559560	// FIXME should we delete this or repurpose it?561	/// Times in how many blocks we sponsor data.562	///563	/// If is `Some(v)` then **setVariableMetadata** is sponsored if there is `v` block between transactions.564	///565	/// * Default - [`SponsoringDisabled`](SponsoringRateLimit::SponsoringDisabled).566	/// * Limit - [`MAX_SPONSOR_TIMEOUT`].567	///568	/// In any case, chain default: [`SponsoringRateLimit::SponsoringDisabled`]569	pub sponsored_data_rate_limit: Option<SponsoringRateLimit>,570	/// Maximum amount of tokens inside the collection. Chain default: [`COLLECTION_TOKEN_LIMIT`]571572	/// How many tokens can be mined into this collection.573	///574	/// * Default - [`COLLECTION_TOKEN_LIMIT`].575	/// * Limit - [`COLLECTION_TOKEN_LIMIT`].576	pub token_limit: Option<u32>,577578	/// Timeouts for transfer sponsoring.579	///580	/// * Default581	///   - **Fungible** - [`FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]582	///   - **NFT** - [`NFT_SPONSOR_TRANSFER_TIMEOUT`]583	///   - **Refungible** - [`REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT`]584	/// * Limit - [`MAX_SPONSOR_TIMEOUT`].585	pub sponsor_transfer_timeout: Option<u32>,586587	/// Timeout for sponsoring an approval in passed blocks.588	///589	/// * Default - [`SPONSOR_APPROVE_TIMEOUT`].590	/// * Limit - [`MAX_SPONSOR_TIMEOUT`].591	pub sponsor_approve_timeout: Option<u32>,592593	/// Whether the collection owner of the collection can send tokens (which belong to other users).594	///595	/// * Default - **false**.596	pub owner_can_transfer: Option<bool>,597598	/// Can the collection owner burn other people's tokens.599	///600	/// * Default - **true**.601	pub owner_can_destroy: Option<bool>,602603	/// Is it possible to send tokens from this collection between users.604	///605	/// * Default - **true**.606	pub transfers_enabled: Option<bool>,607}608609impl CollectionLimits {610	/// Get effective value for [`account_token_ownership_limit`](self.account_token_ownership_limit).611	pub fn account_token_ownership_limit(&self) -> u32 {612		self.account_token_ownership_limit613			.unwrap_or(ACCOUNT_TOKEN_OWNERSHIP_LIMIT)614			.min(MAX_TOKEN_OWNERSHIP)615	}616617	/// Get effective value for [`sponsored_data_size`](self.sponsored_data_size).618	pub fn sponsored_data_size(&self) -> u32 {619		self.sponsored_data_size620			.unwrap_or(CUSTOM_DATA_LIMIT)621			.min(CUSTOM_DATA_LIMIT)622	}623624	/// Get effective value for [`token_limit`](self.token_limit).625	pub fn token_limit(&self) -> u32 {626		self.token_limit627			.unwrap_or(COLLECTION_TOKEN_LIMIT)628			.min(COLLECTION_TOKEN_LIMIT)629	}630631	// TODO: may be replace u32 to mode?632	/// Get effective value for [`sponsor_transfer_timeout`](self.sponsor_transfer_timeout).633	pub fn sponsor_transfer_timeout(&self, default: u32) -> u32 {634		self.sponsor_transfer_timeout635			.unwrap_or(default)636			.min(MAX_SPONSOR_TIMEOUT)637	}638639	/// Get effective value for [`sponsor_approve_timeout`](self.sponsor_approve_timeout).640	pub fn sponsor_approve_timeout(&self) -> u32 {641		self.sponsor_approve_timeout642			.unwrap_or(SPONSOR_APPROVE_TIMEOUT)643			.min(MAX_SPONSOR_TIMEOUT)644	}645646	/// Get effective value for [`owner_can_transfer`](self.owner_can_transfer).647	pub fn owner_can_transfer(&self) -> bool {648		self.owner_can_transfer.unwrap_or(false)649	}650651	/// Get effective value for [`owner_can_transfer_instaled`](self.owner_can_transfer_instaled).652	pub fn owner_can_transfer_instaled(&self) -> bool {653		self.owner_can_transfer.is_some()654	}655656	/// Get effective value for [`owner_can_destroy`](self.owner_can_destroy).657	pub fn owner_can_destroy(&self) -> bool {658		self.owner_can_destroy.unwrap_or(true)659	}660661	/// Get effective value for [`transfers_enabled`](self.transfers_enabled).662	pub fn transfers_enabled(&self) -> bool {663		self.transfers_enabled.unwrap_or(true)664	}665666	/// Get effective value for [`sponsored_data_rate_limit`](self.sponsored_data_rate_limit).667	pub fn sponsored_data_rate_limit(&self) -> Option<u32> {668		match self669			.sponsored_data_rate_limit670			.unwrap_or(SponsoringRateLimit::SponsoringDisabled)671		{672			SponsoringRateLimit::SponsoringDisabled => None,673			SponsoringRateLimit::Blocks(v) => Some(v.min(MAX_SPONSOR_TIMEOUT)),674		}675	}676}677678/// Permissions on certain operations within a collection.679///680/// Some fields are wrapped in [`Option`], where `None` means chain default.681///682/// Update with `pallet_common::Pallet::clamp_permissions`.683#[derive(Encode, Decode, Debug, Default, Clone, PartialEq, TypeInfo, MaxEncodedLen)]684#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]685// When adding/removing fields from this struct - don't forget to also update `pallet_common::Pallet::clamp_permissions`.686// TODO: move `pallet_common::Pallet::clamp_permissions` into `impl CollectionPermissions`.687pub struct CollectionPermissions {688	/// Access mode.689	///690	/// * Default - [`AccessMode::Normal`].691	pub access: Option<AccessMode>,692693	/// Minting allowance.694	///695	/// * Default - **false**.696	pub mint_mode: Option<bool>,697698	/// Permissions for nesting.699	///700	/// * Default701	///   - `token_owner` - **false**702	///   - `collection_admin` - **false**703	///   - `restricted` - **None**704	pub nesting: Option<NestingPermissions>,705}706707impl CollectionPermissions {708	/// Get effective value for [`access`](self.access).709	pub fn access(&self) -> AccessMode {710		self.access.unwrap_or(AccessMode::Normal)711	}712713	/// Get effective value for [`mint_mode`](self.mint_mode).714	pub fn mint_mode(&self) -> bool {715		self.mint_mode.unwrap_or(false)716	}717718	/// Get effective value for [`nesting`](self.nesting).719	pub fn nesting(&self) -> &NestingPermissions {720		static DEFAULT: NestingPermissions = NestingPermissions {721			token_owner: false,722			collection_admin: false,723			restricted: None,724			#[cfg(feature = "runtime-benchmarks")]725			permissive: false,726		};727		self.nesting.as_ref().unwrap_or(&DEFAULT)728	}729}730731/// Inner set for collections allowed to nest.732type OwnerRestrictedSetInner = BoundedBTreeSet<CollectionId, ConstU32<16>>;733734/// Wraper for collections set allowing nest.735#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]736#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]737#[derivative(Debug)]738pub struct OwnerRestrictedSet(739	#[cfg_attr(feature = "serde1", serde(with = "bounded::set_serde"))]740	#[derivative(Debug(format_with = "bounded::set_debug"))]741	pub OwnerRestrictedSetInner,742);743744impl OwnerRestrictedSet {745	/// Create new set.746	pub fn new() -> Self {747		Self(Default::default())748	}749}750impl core::ops::Deref for OwnerRestrictedSet {751	type Target = OwnerRestrictedSetInner;752	fn deref(&self) -> &Self::Target {753		&self.0754	}755}756impl core::ops::DerefMut for OwnerRestrictedSet {757	fn deref_mut(&mut self) -> &mut Self::Target {758		&mut self.0759	}760}761762/// Part of collection permissions, if set, defines who is able to nest tokens into other tokens.763#[derive(Encode, Decode, Clone, PartialEq, TypeInfo, MaxEncodedLen, Derivative)]764#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]765#[derivative(Debug)]766pub struct NestingPermissions {767	/// Owner of token can nest tokens under it.768	pub token_owner: bool,769	/// Admin of token collection can nest tokens under token.770	pub collection_admin: bool,771	/// If set - only tokens from specified collections can be nested.772	pub restricted: Option<OwnerRestrictedSet>,773774	#[cfg(feature = "runtime-benchmarks")]775	/// Anyone can nest tokens, mutually exclusive with `token_owner`, `admin`.776	pub permissive: bool,777}778779/// Enum denominating how often can sponsoring occur if it is enabled.780///781/// Used for [`collection limits`](CollectionLimits).782#[derive(Encode, Decode, Debug, Clone, Copy, PartialEq, TypeInfo, MaxEncodedLen)]783#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]784pub enum SponsoringRateLimit {785	/// Sponsoring is disabled, and the collection sponsor will not pay for transactions786	SponsoringDisabled,787	/// Once per how many blocks can sponsorship of a transaction type occur788	Blocks(u32),789}790791/// Data used to describe an NFT at creation.792#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]793#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]794#[derivative(Debug)]795pub struct CreateNftData {796	/// Key-value pairs used to describe the token as metadata797	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]798	#[derivative(Debug(format_with = "bounded::vec_debug"))]799	/// Properties that wil be assignet to created item.800	pub properties: CollectionPropertiesVec,801}802803/// Data used to describe a Fungible token at creation.804#[derive(Encode, Decode, MaxEncodedLen, Default, Debug, Clone, PartialEq, TypeInfo)]805#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]806pub struct CreateFungibleData {807	/// Number of fungible coins minted808	pub value: u128,809}810811/// Data used to describe a Refungible token at creation.812#[derive(Encode, Decode, MaxEncodedLen, Default, PartialEq, Clone, Derivative, TypeInfo)]813#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]814#[derivative(Debug)]815pub struct CreateReFungibleData {816	/// Number of pieces the RFT is split into817	pub pieces: u128,818819	/// Key-value pairs used to describe the token as metadata820	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]821	#[derivative(Debug(format_with = "bounded::vec_debug"))]822	pub properties: CollectionPropertiesVec,823}824825// TODO: remove this.826#[derive(Encode, Decode, Debug, Clone, PartialEq, TypeInfo, MaxEncodedLen)]827#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]828pub enum MetaUpdatePermission {829	ItemOwner,830	Admin,831	None,832}833834/// Enum holding data used for creation of all three item types.835/// Unified data for create item.836#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]837#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]838pub enum CreateItemData {839	/// Data for create NFT.840	NFT(CreateNftData),841	/// Data for create Fungible item.842	Fungible(CreateFungibleData),843	/// Data for create ReFungible item.844	ReFungible(CreateReFungibleData),845}846847/// Extended data for create NFT.848#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]849#[derivative(Debug)]850pub struct CreateNftExData<CrossAccountId> {851	/// Properties that wil be assignet to created item.852	#[derivative(Debug(format_with = "bounded::vec_debug"))]853	pub properties: CollectionPropertiesVec,854855	/// Owner of creating item.856	pub owner: CrossAccountId,857}858859/// Extended data for create ReFungible item.860#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]861#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]862pub struct CreateRefungibleExMultipleOwners<CrossAccountId> {863	#[derivative(Debug(format_with = "bounded::map_debug"))]864	pub users: BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,865	#[derivative(Debug(format_with = "bounded::vec_debug"))]866	pub properties: CollectionPropertiesVec,867}868869/// Extended data for create ReFungible item.870#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]871#[derivative(Debug(bound = "CrossAccountId: fmt::Debug"))]872pub struct CreateRefungibleExSingleOwner<CrossAccountId> {873	pub user: CrossAccountId,874	pub pieces: u128,875	#[derivative(Debug(format_with = "bounded::vec_debug"))]876	pub properties: CollectionPropertiesVec,877}878879/// Unified extended data for creating item.880#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, TypeInfo, Derivative)]881#[derivative(Debug(bound = "CrossAccountId: fmt::Debug + Ord"))]882pub enum CreateItemExData<CrossAccountId> {883	/// Extended data for create NFT.884	NFT(885		#[derivative(Debug(format_with = "bounded::vec_debug"))]886		BoundedVec<CreateNftExData<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,887	),888889	/// Extended data for create Fungible item.890	Fungible(891		#[derivative(Debug(format_with = "bounded::map_debug"))]892		BoundedBTreeMap<CrossAccountId, u128, ConstU32<MAX_ITEMS_PER_BATCH>>,893	),894895	/// Extended data for create ReFungible item in case of896	/// many tokens, each may have only one owner897	RefungibleMultipleItems(898		#[derivative(Debug(format_with = "bounded::vec_debug"))]899		BoundedVec<CreateRefungibleExSingleOwner<CrossAccountId>, ConstU32<MAX_ITEMS_PER_BATCH>>,900	),901902	/// Extended data for create ReFungible item in case of903	/// single token, which may have many owners904	RefungibleMultipleOwners(CreateRefungibleExMultipleOwners<CrossAccountId>),905}906907impl From<CreateNftData> for CreateItemData {908	fn from(item: CreateNftData) -> Self {909		CreateItemData::NFT(item)910	}911}912913impl From<CreateReFungibleData> for CreateItemData {914	fn from(item: CreateReFungibleData) -> Self {915		CreateItemData::ReFungible(item)916	}917}918919impl From<CreateFungibleData> for CreateItemData {920	fn from(item: CreateFungibleData) -> Self {921		CreateItemData::Fungible(item)922	}923}924925/// Token's address, dictated by its collection and token IDs.926#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]927#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]928// todo possibly rename to be used generally as an address pair929pub struct TokenChild {930	/// Token id.931	pub token: TokenId,932933	/// Collection id.934	pub collection: CollectionId,935}936937/// Collection statistics.938#[derive(Encode, Decode, MaxEncodedLen, PartialEq, Clone, Debug, TypeInfo)]939#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]940pub struct CollectionStats {941	/// Number of created items.942	pub created: u32,943944	/// Number of burned items.945	pub destroyed: u32,946947	/// Number of current items.948	pub alive: u32,949}950951/// This type works like [`PhantomData`] but supports generating _scale-info_ descriptions to generate node metadata.952#[derive(Encode, Decode, Clone, Debug)]953#[cfg_attr(feature = "std", derive(PartialEq))]954pub struct PhantomType<T>(core::marker::PhantomData<T>);955956impl<T: TypeInfo + 'static> TypeInfo for PhantomType<T> {957	type Identity = PhantomType<T>;958959	fn type_info() -> scale_info::Type {960		use scale_info::{961			Type, Path,962			build::{FieldsBuilder, UnnamedFields},963			type_params,964		};965		Type::builder()966			.path(Path::new("up_data_structs", "PhantomType"))967			.type_params(type_params!(T))968			.composite(<FieldsBuilder<UnnamedFields>>::default().field(|b| b.ty::<[T; 0]>()))969	}970}971impl<T> MaxEncodedLen for PhantomType<T> {972	fn max_encoded_len() -> usize {973		0974	}975}976977/// Bounded vector of bytes.978pub type BoundedBytes<S> = BoundedVec<u8, S>;979980/// Extra properties for external collections.981pub type AuxPropertyValue = BoundedBytes<ConstU32<MAX_AUX_PROPERTY_VALUE_LENGTH>>;982983/// Property key.984pub type PropertyKey = BoundedBytes<ConstU32<MAX_PROPERTY_KEY_LENGTH>>;985986/// Property value.987pub type PropertyValue = BoundedBytes<ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;988989/// Property permission.990#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]991#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]992pub struct PropertyPermission {993	/// Permission to change the property and property permission.994	///995	/// If it **false** then you can not change corresponding property even if [`collection_admin`] and [`token_owner`] are **true**.996	pub mutable: bool,997998	/// Change permission for the collection administrator.999	pub collection_admin: bool,10001001	/// Permission to change the property for the owner of the token.1002	pub token_owner: bool,1003}10041005impl PropertyPermission {1006	/// Creates mutable property permission but changes restricted for collection admin and token owner.1007	pub fn none() -> Self {1008		Self {1009			mutable: true,1010			collection_admin: false,1011			token_owner: false,1012		}1013	}1014}10151016/// Property is simpl key-value record.1017#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1018#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1019pub struct Property {1020	/// Property key.1021	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1022	pub key: PropertyKey,10231024	/// Property value.1025	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1026	pub value: PropertyValue,1027}10281029impl Into<(PropertyKey, PropertyValue)> for Property {1030	fn into(self) -> (PropertyKey, PropertyValue) {1031		(self.key, self.value)1032	}1033}10341035/// Record for proprty key permission.1036#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]1037#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]1038pub struct PropertyKeyPermission {1039	/// Key.1040	#[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]1041	pub key: PropertyKey,10421043	/// Permission.1044	pub permission: PropertyPermission,1045}10461047impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {1048	fn into(self) -> (PropertyKey, PropertyPermission) {1049		(self.key, self.permission)1050	}1051}10521053/// Errors for properties actions.1054#[derive(Debug)]1055pub enum PropertiesError {1056	/// The space allocated for properties has run out.1057	///1058	/// * Limit for colection - [`MAX_COLLECTION_PROPERTIES_SIZE`].1059	/// * Limit for token - [`MAX_TOKEN_PROPERTIES_SIZE`].1060	NoSpaceForProperty,10611062	/// The property limit has been reached.1063	///1064	/// * Limit - [`MAX_PROPERTIES_PER_ITEM`].1065	PropertyLimitReached,10661067	/// Property key contains not allowed character.1068	InvalidCharacterInPropertyKey,10691070	/// Property key length is too long.1071	///1072	/// * Limit - [`MAX_PROPERTY_KEY_LENGTH`].1073	PropertyKeyIsTooLong,10741075	/// Property key is empty.1076	EmptyPropertyKey,1077}10781079/// Marker for scope of property.1080///1081/// Scoped property can't be changed by user. Used for external collections.1082#[derive(Encode, Decode, MaxEncodedLen, TypeInfo, PartialEq, Clone, Copy)]1083pub enum PropertyScope {1084	None,1085	Rmrk,1086}10871088impl PropertyScope {1089	/// Apply scope to property key.1090	pub fn apply(self, key: PropertyKey) -> Result<PropertyKey, PropertiesError> {1091		let scope_str: &[u8] = match self {1092			Self::None => return Ok(key),1093			Self::Rmrk => b"rmrk",1094		};10951096		[scope_str, b":", key.as_slice()]1097			.concat()1098			.try_into()1099			.map_err(|_| PropertiesError::PropertyKeyIsTooLong)1100	}1101}11021103/// Trait for operate with properties.1104pub trait TrySetProperty: Sized {1105	type Value;11061107	/// Try to set property with scope.1108	fn try_scoped_set(1109		&mut self,1110		scope: PropertyScope,1111		key: PropertyKey,1112		value: Self::Value,1113	) -> Result<(), PropertiesError>;11141115	/// Try to set property with scope from iterator.1116	fn try_scoped_set_from_iter<I, KV>(1117		&mut self,1118		scope: PropertyScope,1119		iter: I,1120	) -> Result<(), PropertiesError>1121	where1122		I: Iterator<Item = KV>,1123		KV: Into<(PropertyKey, Self::Value)>,1124	{1125		for kv in iter {1126			let (key, value) = kv.into();1127			self.try_scoped_set(scope, key, value)?;1128		}11291130		Ok(())1131	}11321133	/// Try to set property.1134	fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {1135		self.try_scoped_set(PropertyScope::None, key, value)1136	}11371138	/// Try to set property from iterator.1139	fn try_set_from_iter<I, KV>(&mut self, iter: I) -> Result<(), PropertiesError>1140	where1141		I: Iterator<Item = KV>,1142		KV: Into<(PropertyKey, Self::Value)>,1143	{1144		self.try_scoped_set_from_iter(PropertyScope::None, iter)1145	}1146}11471148/// Wrapped map for storing properties.1149#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]1150#[derivative(Default(bound = ""))]1151pub struct PropertiesMap<Value>(1152	BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>,1153);11541155impl<Value> PropertiesMap<Value> {1156	/// Create new property map.1157	pub fn new() -> Self {1158		Self(BoundedBTreeMap::new())1159	}11601161	/// Remove property from map.1162	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {1163		Self::check_property_key(key)?;11641165		Ok(self.0.remove(key))1166	}11671168	/// Get property with appropriate key from map.1169	pub fn get(&self, key: &PropertyKey) -> Option<&Value> {1170		self.0.get(key)1171	}11721173	/// Check if map contains key.1174	pub fn contains_key(&self, key: &PropertyKey) -> bool {1175		self.0.contains_key(key)1176	}11771178	/// Check if map contains key with key validation.1179	fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {1180		if key.is_empty() {1181			return Err(PropertiesError::EmptyPropertyKey);1182		}11831184		for byte in key.as_slice().iter() {1185			let byte = *byte;11861187			if !byte.is_ascii_alphanumeric() && byte != b'_' && byte != b'-' && byte != b'.' {1188				return Err(PropertiesError::InvalidCharacterInPropertyKey);1189			}1190		}11911192		Ok(())1193	}1194}11951196impl<Value> IntoIterator for PropertiesMap<Value> {1197	type Item = (PropertyKey, Value);1198	type IntoIter = <1199		BoundedBTreeMap<1200			PropertyKey,1201			Value,1202			ConstU32<MAX_PROPERTIES_PER_ITEM>1203		> as IntoIterator1204	>::IntoIter;12051206	fn into_iter(self) -> Self::IntoIter {1207		self.0.into_iter()1208	}1209}12101211impl<Value> TrySetProperty for PropertiesMap<Value> {1212	type Value = Value;12131214	fn try_scoped_set(1215		&mut self,1216		scope: PropertyScope,1217		key: PropertyKey,1218		value: Self::Value,1219	) -> Result<(), PropertiesError> {1220		Self::check_property_key(&key)?;12211222		let key = scope.apply(key)?;1223		self.01224			.try_insert(key, value)1225			.map_err(|_| PropertiesError::PropertyLimitReached)?;12261227		Ok(())1228	}1229}12301231/// Alias for property permissions map.1232pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;12331234/// Wrapper for properties map with consumed space control.1235#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]1236pub struct Properties {1237	map: PropertiesMap<PropertyValue>,1238	consumed_space: u32,1239	space_limit: u32,1240}12411242impl Properties {1243	/// Create new properies container.1244	pub fn new(space_limit: u32) -> Self {1245		Self {1246			map: PropertiesMap::new(),1247			consumed_space: 0,1248			space_limit,1249		}1250	}12511252	/// Remove propery with appropiate key.1253	pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {1254		let value = self.map.remove(key)?;12551256		if let Some(ref value) = value {1257			let value_len = value.len() as u32;1258			self.consumed_space -= value_len;1259		}12601261		Ok(value)1262	}12631264	/// Get property with appropriate key.1265	pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {1266		self.map.get(key)1267	}1268}12691270impl IntoIterator for Properties {1271	type Item = (PropertyKey, PropertyValue);1272	type IntoIter = <PropertiesMap<PropertyValue> as IntoIterator>::IntoIter;12731274	fn into_iter(self) -> Self::IntoIter {1275		self.map.into_iter()1276	}1277}12781279impl TrySetProperty for Properties {1280	type Value = PropertyValue;12811282	fn try_scoped_set(1283		&mut self,1284		scope: PropertyScope,1285		key: PropertyKey,1286		value: Self::Value,1287	) -> Result<(), PropertiesError> {1288		let value_len = value.len();12891290		if self.consumed_space as usize + value_len > self.space_limit as usize1291			&& !cfg!(feature = "runtime-benchmarks")1292		{1293			return Err(PropertiesError::NoSpaceForProperty);1294		}12951296		self.map.try_scoped_set(scope, key, value)?;12971298		self.consumed_space += value_len as u32;12991300		Ok(())1301	}1302}13031304/// Utility struct for using in `StorageMap`.1305pub struct CollectionProperties;13061307impl Get<Properties> for CollectionProperties {1308	fn get() -> Properties {1309		Properties::new(MAX_COLLECTION_PROPERTIES_SIZE)1310	}1311}13121313/// Utility struct for using in `StorageMap`.1314pub struct TokenProperties;13151316impl Get<Properties> for TokenProperties {1317	fn get() -> Properties {1318		Properties::new(MAX_TOKEN_PROPERTIES_SIZE)1319	}1320}13211322// RMRK1323// todo document?1324parameter_types! {1325	#[derive(PartialEq, TypeInfo)]1326	pub const RmrkStringLimit: u32 = 128;1327	#[derive(PartialEq)]1328	pub const RmrkCollectionSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1329	#[derive(PartialEq)]1330	pub const RmrkResourceSymbolLimit: u32 = 10;1331	#[derive(PartialEq)]1332	pub const RmrkBaseSymbolLimit: u32 = MAX_TOKEN_PREFIX_LENGTH;1333	#[derive(PartialEq)]1334	pub const RmrkKeyLimit: u32 = 32;1335	#[derive(PartialEq)]1336	pub const RmrkValueLimit: u32 = 256;1337	#[derive(PartialEq)]1338	pub const RmrkMaxCollectionsEquippablePerPart: u32 = 100;1339	#[derive(PartialEq)]1340	pub const MaxPropertiesPerTheme: u32 = 5;1341	#[derive(PartialEq)]1342	pub const RmrkPartsLimit: u32 = 25;1343	#[derive(PartialEq)]1344	pub const RmrkMaxPriorities: u32 = 25;1345	#[derive(PartialEq)]1346	pub const MaxResourcesOnMint: u32 = 100;1347}13481349impl From<RmrkCollectionId> for CollectionId {1350	fn from(id: RmrkCollectionId) -> Self {1351		Self(id)1352	}1353}13541355impl From<RmrkNftId> for TokenId {1356	fn from(id: RmrkNftId) -> Self {1357		Self(id)1358	}1359}13601361pub type RmrkCollectionInfo<AccountId> =1362	CollectionInfo<RmrkString, RmrkCollectionSymbol, AccountId>;1363pub type RmrkInstanceInfo<AccountId> = NftInfo<AccountId, Permill, RmrkString>;1364pub type RmrkResourceInfo = ResourceInfo<RmrkString, RmrkBoundedParts>;1365pub type RmrkPropertyInfo = PropertyInfo<RmrkKeyString, RmrkValueString>;1366pub type RmrkBaseInfo<AccountId> = BaseInfo<AccountId, RmrkString>;1367pub type BoundedEquippableCollectionIds =1368	BoundedVec<RmrkCollectionId, RmrkMaxCollectionsEquippablePerPart>;1369pub type RmrkPartType = PartType<RmrkString, BoundedEquippableCollectionIds>;1370pub type RmrkEquippableList = EquippableList<BoundedEquippableCollectionIds>;1371pub type RmrkThemeProperty = ThemeProperty<RmrkString>;1372pub type RmrkTheme = Theme<RmrkString, Vec<RmrkThemeProperty>>;1373pub type RmrkBoundedTheme = Theme<RmrkString, BoundedVec<RmrkThemeProperty, MaxPropertiesPerTheme>>;1374pub type RmrkResourceTypes = ResourceTypes<RmrkString, RmrkBoundedParts>;13751376pub type RmrkBasicResource = BasicResource<RmrkString>;1377pub type RmrkComposableResource = ComposableResource<RmrkString, RmrkBoundedParts>;1378pub type RmrkSlotResource = SlotResource<RmrkString>;13791380pub type RmrkString = BoundedVec<u8, RmrkStringLimit>;1381pub type RmrkCollectionSymbol = BoundedVec<u8, RmrkCollectionSymbolLimit>;1382pub type RmrkBaseSymbol = BoundedVec<u8, RmrkBaseSymbolLimit>;1383pub type RmrkKeyString = BoundedVec<u8, RmrkKeyLimit>;1384pub type RmrkValueString = BoundedVec<u8, RmrkValueLimit>;1385pub type RmrkBoundedResource = BoundedVec<u8, RmrkResourceSymbolLimit>;1386pub type RmrkBoundedParts = BoundedVec<RmrkPartId, RmrkPartsLimit>; // todo make sure it is needed13871388pub type RmrkRpcString = Vec<u8>;1389pub type RmrkThemeName = RmrkRpcString;1390pub type RmrkPropertyKey = RmrkRpcString;
modifiedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -20,7 +20,7 @@
 
 use up_data_structs::{
 	CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property,
-	PropertyKeyPermission, TokenData, TokenChild, RpcCollectionVersion1,
+	PropertyKeyPermission, TokenData, TokenChild, RpcCollectionVersion1, TokenDataVersion1,
 };
 
 use sp_std::vec::Vec;
@@ -77,6 +77,13 @@
 			keys: Option<Vec<Vec<u8>>>
 		) -> Result<TokenData<CrossAccountId>>;
 
+		#[changed_in(3)]
+		fn token_data(
+			collection: CollectionId,
+			token_id: TokenId,
+			keys: Option<Vec<Vec<u8>>>
+		) -> Result<TokenDataVersion1<CrossAccountId>>;
+
 		/// Total number of tokens in collection.
 		fn total_supply(collection: CollectionId) -> Result<u32>;
 
modifiedruntime/common/config/pallets/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -27,7 +27,7 @@
 	runtime_common::{scheduler::SchedulerPaymentExecutor, config::substrate::RuntimeBlockWeights},
 	Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, OriginCaller, Balances,
 };
-use pallet_unique_scheduler_v2::ScheduledEnsureOriginSuccess;
+use pallet_unique_scheduler::ScheduledEnsureOriginSuccess;
 use up_common::types::AccountId;
 
 parameter_types! {
@@ -70,34 +70,19 @@
 	}
 }
 
-// impl pallet_unique_scheduler::Config for Runtime {
-// 	type RuntimeEvent = RuntimeEvent;
-// 	type RuntimeOrigin = RuntimeOrigin;
-// 	type Currency = Balances;
-// 	type PalletsOrigin = OriginCaller;
-// 	type RuntimeCall = RuntimeCall;
-// 	type MaximumWeight = MaximumSchedulerWeight;
-// 	type ScheduleOrigin = EnsureSignedOrRoot<AccountId>;
-// 	type PrioritySetOrigin = EnsureRoot<AccountId>;
-// 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// 	type WeightInfo = ();
-// 	type CallExecutor = SchedulerPaymentExecutor;
-// 	type OriginPrivilegeCmp = EqualOrRootOnly;
-// 	type PreimageProvider = ();
-// 	type NoPreimagePostponement = NoPreimagePostponement;
-// }
-
-impl pallet_unique_scheduler_v2::Config for Runtime {
+impl pallet_unique_scheduler::Config for Runtime {
 	type RuntimeEvent = RuntimeEvent;
 	type RuntimeOrigin = RuntimeOrigin;
+	type Currency = Balances;
 	type PalletsOrigin = OriginCaller;
 	type RuntimeCall = RuntimeCall;
 	type MaximumWeight = MaximumSchedulerWeight;
 	type ScheduleOrigin = EnsureSignedOrRoot<AccountId>;
-	type OriginPrivilegeCmp = EqualOrRootOnly;
+	type PrioritySetOrigin = EnsureRoot<AccountId>;
 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
 	type WeightInfo = ();
-	type Preimages = ();
 	type CallExecutor = SchedulerPaymentExecutor;
-	type PrioritySetOrigin = EnsureRoot<AccountId>;
+	type OriginPrivilegeCmp = EqualOrRootOnly;
+	type PreimageProvider = ();
+	type NoPreimagePostponement = NoPreimagePostponement;
 }
modifiedruntime/common/construct_runtime/mod.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -57,8 +57,8 @@
                 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
                 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
 
-                // #[runtimes(opal)]
-                // Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+                #[runtimes(opal)]
+                Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 
                 Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
 
@@ -93,9 +93,6 @@
                 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage, Event<T>} = 151,
                 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,
                 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,
-
-                #[runtimes(opal)]
-                Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 154,
 
                 #[runtimes(opal)]
                 TestUtils: pallet_test_utils = 255,
modifiedruntime/common/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -28,11 +28,11 @@
 use crate::{Runtime, RuntimeCall, RuntimeOrigin, Balances};
 use up_common::types::{AccountId, Balance};
 use fp_self_contained::SelfContainedCall;
-use pallet_unique_scheduler_v2::DispatchCall;
+use pallet_unique_scheduler::DispatchCall;
 use pallet_transaction_payment::ChargeTransactionPayment;
 
-// type SponsorshipChargeTransactionPayment =
-// 	pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+type SponsorshipChargeTransactionPayment =
+	pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
 
 /// The SignedExtension to the basic transaction logic.
 pub type SignedExtraScheduler = (
@@ -59,7 +59,7 @@
 
 pub struct SchedulerPaymentExecutor;
 
-impl<T: frame_system::Config + pallet_unique_scheduler_v2::Config, SelfContainedSignedInfo>
+impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::RuntimeCall: Member
@@ -69,13 +69,13 @@
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
 	RuntimeCall: From<<T as frame_system::Config>::RuntimeCall>
-		+ From<<T as pallet_unique_scheduler_v2::Config>::RuntimeCall>
+		+ From<<T as pallet_unique_scheduler::Config>::RuntimeCall>
 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
 	fn dispatch_call(
 		signer: Option<<T as frame_system::Config>::AccountId>,
-		call: <T as pallet_unique_scheduler_v2::Config>::RuntimeCall,
+		call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
 	) -> Result<
 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
 		TransactionValidityError,
@@ -103,98 +103,52 @@
 
 		extrinsic.apply::<Runtime>(&dispatch_info, len)
 	}
-}
 
-// impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
-// 	DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
-// where
-// 	<T as frame_system::Config>::Call: Member
-// 		+ Dispatchable<Origin = Origin, Info = DispatchInfo>
-// 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
-// 		+ GetDispatchInfo
-// 		+ From<frame_system::Call<Runtime>>,
-// 	SelfContainedSignedInfo: Send + Sync + 'static,
-// 	Call: From<<T as frame_system::Config>::Call>
-// 		+ From<<T as pallet_unique_scheduler::Config>::Call>
-// 		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
-// 	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
-// {
-// 	fn dispatch_call(
-// 		signer: Option<<T as frame_system::Config>::AccountId>,
-// 		call: <T as pallet_unique_scheduler::Config>::Call,
-// 	) -> Result<
-// 		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
-// 		TransactionValidityError,
-// 	> {
-// 		let dispatch_info = call.get_dispatch_info();
-// 		let len = call.encoded_size();
+	fn reserve_balance(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
+		count: u32,
+	) -> Result<(), DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance =
+			SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+				.saturating_mul(count.into());
 
-// 		let signed = match signer {
-// 			Some(signer) => fp_self_contained::CheckedSignature::Signed(
-// 				signer.clone().into(),
-// 				get_signed_extras(signer.into()),
-// 			),
-// 			None => fp_self_contained::CheckedSignature::Unsigned,
-// 		};
+		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+			&id,
+			&(sponsor.into()),
+			weight,
+		)
+	}
 
-// 		let extrinsic = fp_self_contained::CheckedExtrinsic::<
-// 			AccountId,
-// 			Call,
-// 			SignedExtraScheduler,
-// 			SelfContainedSignedInfo,
-// 		> {
-// 			signed,
-// 			function: call.into(),
-// 		};
-
-// 		extrinsic.apply::<Runtime>(&dispatch_info, len)
-// 	}
-
-// 	fn reserve_balance(
-// 		id: [u8; 16],
-// 		sponsor: <T as frame_system::Config>::AccountId,
-// 		call: <T as pallet_unique_scheduler::Config>::Call,
-// 		count: u32,
-// 	) -> Result<(), DispatchError> {
-// 		let dispatch_info = call.get_dispatch_info();
-// 		let weight: Balance =
-// 			SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
-// 				.saturating_mul(count.into());
+	fn pay_for_call(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unique_scheduler::Config>::RuntimeCall,
+	) -> Result<u128, DispatchError> {
+		let dispatch_info = call.get_dispatch_info();
+		let weight: Balance =
+			SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				weight,
+			),
+		)
+	}
 
-// 		<Balances as NamedReservableCurrency<AccountId>>::reserve_named(
-// 			&id,
-// 			&(sponsor.into()),
-// 			weight,
-// 		)
-// 	}
-
-// 	fn pay_for_call(
-// 		id: [u8; 16],
-// 		sponsor: <T as frame_system::Config>::AccountId,
-// 		call: <T as pallet_unique_scheduler::Config>::Call,
-// 	) -> Result<u128, DispatchError> {
-// 		let dispatch_info = call.get_dispatch_info();
-// 		let weight: Balance =
-// 			SponsorshipChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
-// 		Ok(
-// 			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
-// 				&id,
-// 				&(sponsor.into()),
-// 				weight,
-// 			),
-// 		)
-// 	}
-
-// 	fn cancel_reserve(
-// 		id: [u8; 16],
-// 		sponsor: <T as frame_system::Config>::AccountId,
-// 	) -> Result<u128, DispatchError> {
-// 		Ok(
-// 			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
-// 				&id,
-// 				&(sponsor.into()),
-// 				u128::MAX,
-// 			),
-// 		)
-// 	}
-// }
+	fn cancel_reserve(
+		id: [u8; 16],
+		sponsor: <T as frame_system::Config>::AccountId,
+	) -> Result<u128, DispatchError> {
+		Ok(
+			<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+				&id,
+				&(sponsor.into()),
+				u128::MAX,
+			),
+		)
+	}
+}
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -42,7 +42,6 @@
     'pallet-inflation/runtime-benchmarks',
     'pallet-app-promotion/runtime-benchmarks',
     'pallet-unique-scheduler/runtime-benchmarks',
-    'pallet-unique-scheduler-v2/runtime-benchmarks',
     'pallet-xcm/runtime-benchmarks',
     'sp-runtime/runtime-benchmarks',
     'xcm-builder/runtime-benchmarks',
@@ -141,7 +140,6 @@
     'pallet-proxy-rmrk-equip/std',
     'pallet-unique/std',
     'pallet-unique-scheduler/std',
-    'pallet-unique-scheduler-v2/std',
     'pallet-charge-transaction/std',
     'up-data-structs/std',
     'sp-api/std',
@@ -474,7 +472,6 @@
 pallet-proxy-rmrk-equip = { default-features = false, path = "../../pallets/proxy-rmrk-equip", package = "pallet-rmrk-equip" }
 pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 pallet-charge-transaction = { git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.30", package = "pallet-template-transaction-payment", default-features = false, version = "3.0.0" }
-pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
 pallet-evm-migration = { path = '../../pallets/evm-migration', default-features = false }
 pallet-evm-contract-helpers = { path = '../../pallets/evm-contract-helpers', default-features = false }
 pallet-evm-transaction-payment = { path = '../../pallets/evm-transaction-payment', default-features = false }
modifiedtest-pallets/utils/Cargo.tomldiffbeforeafterboth
--- a/test-pallets/utils/Cargo.toml
+++ b/test-pallets/utils/Cargo.toml
@@ -10,8 +10,7 @@
 scale-info = { version = "2.1.1", default-features = false, features = ["derive"] }
 frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
 frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
-# pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
-pallet-unique-scheduler-v2 = { path = '../../pallets/scheduler-v2', default-features = false }
+pallet-unique-scheduler = { path = '../../pallets/scheduler', default-features = false }
 
 [features]
 default = ["std"]
@@ -20,5 +19,5 @@
 	"scale-info/std",
 	"frame-support/std",
 	"frame-system/std",
-	"pallet-unique-scheduler-v2/std",
+	"pallet-unique-scheduler/std",
 ]
modifiedtest-pallets/utils/src/lib.rsdiffbeforeafterboth
--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -24,10 +24,10 @@
 pub mod pallet {
 	use frame_support::pallet_prelude::*;
 	use frame_system::pallet_prelude::*;
-	use pallet_unique_scheduler_v2::{TaskName, Pallet as SchedulerPallet};
+	use pallet_unique_scheduler::{ScheduledId, Pallet as SchedulerPallet};
 
 	#[pallet::config]
-	pub trait Config: frame_system::Config + pallet_unique_scheduler_v2::Config {
+	pub trait Config: frame_system::Config + pallet_unique_scheduler::Config {
 		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
 	}
 
@@ -94,13 +94,14 @@
 		#[pallet::weight(10_000)]
 		pub fn self_canceling_inc(
 			origin: OriginFor<T>,
-			id: TaskName,
+			id: ScheduledId,
 			max_test_value: u32,
 		) -> DispatchResult {
 			Self::ensure_origin_and_enabled(origin.clone())?;
-			Self::inc_test_value(origin.clone())?;
 
-			if <TestValue<T>>::get() == max_test_value {
+			if <TestValue<T>>::get() < max_test_value {
+				Self::inc_test_value(origin)?;
+			} else {
 				SchedulerPallet::<T>::cancel_named(origin, id)?;
 			}
 
modifiedtests/src/util/playgrounds/unique.dev.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.dev.ts
+++ b/tests/src/util/playgrounds/unique.dev.ts
@@ -308,7 +308,7 @@
     await this.helper.wait.noScheduledTasks();
 
     function makeId(slider: number) {
-      const scheduledIdSize = 64;
+      const scheduledIdSize = 32;
       const hexId = slider.toString(16);
       const prefixSize = scheduledIdSize - hexId.length;
 
modifiedtests/src/util/playgrounds/unique.tsdiffbeforeafterboth
--- a/tests/src/util/playgrounds/unique.ts
+++ b/tests/src/util/playgrounds/unique.ts
@@ -2838,7 +2838,7 @@
           this.blocksNum,
           this.options.periodic ? [this.options.periodic.period, this.options.periodic.repetitions] : null,
           this.options.priority ?? null,
-          scheduledTx,
+          {Value: scheduledTx},
         ],
         expectSuccess,
       );