difftreelog
Merge branch 'develop' into feature/ci-refactoring
in: master
19 files changed
Cargo.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]]
client/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);
kb/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
+```
pallets/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"]
pallets/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);
-}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//! with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//! that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72#[cfg(test)]73mod mock;74#[cfg(test)]75mod tests;76pub mod weights;7778use codec::{Codec, Decode, Encode, MaxEncodedLen};79use frame_support::{80 dispatch::{81 DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,82 },83 traits::{84 schedule::{self, DispatchTime, LOWEST_PRIORITY},85 EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,86 ConstU32, UnfilteredDispatchable,87 },88 weights::Weight,89 unsigned::TransactionValidityError,90};9192use frame_system::{self as system};93use scale_info::TypeInfo;94use sp_runtime::{95 traits::{BadOrigin, One, Saturating, Zero, Hash},96 BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,97};98use sp_core::H160;99use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};100pub use weights::WeightInfo;101102pub use pallet::*;103104/// Just a simple index for naming period tasks.105pub type PeriodicIndex = u32;106/// The location of a scheduled task that can be used to remove it.107pub type TaskAddress<BlockNumber> = (BlockNumber, u32);108109pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;110111#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]112#[scale_info(skip_type_params(T))]113pub enum ScheduledCall<T: Config> {114 Inline(EncodedCall),115 PreimageLookup { hash: T::Hash, unbounded_len: u32 },116}117118impl<T: Config> ScheduledCall<T> {119 pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {120 let encoded = call.encode();121 let len = encoded.len();122123 match EncodedCall::try_from(encoded.clone()) {124 Ok(bounded) => Ok(Self::Inline(bounded)),125 Err(_) => {126 let hash = <T as system::Config>::Hashing::hash_of(&encoded);127 <T as Config>::Preimages::note_preimage(128 encoded129 .try_into()130 .map_err(|_| <Error<T>>::TooBigScheduledCall)?,131 );132133 Ok(Self::PreimageLookup {134 hash,135 unbounded_len: len as u32,136 })137 }138 }139 }140141 /// The maximum length of the lookup that is needed to peek `Self`.142 pub fn lookup_len(&self) -> Option<u32> {143 match self {144 Self::Inline(..) => None,145 Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),146 }147 }148149 /// Returns whether the image will require a lookup to be peeked.150 pub fn lookup_needed(&self) -> bool {151 match self {152 Self::Inline(_) => false,153 Self::PreimageLookup { .. } => true,154 }155 }156157 fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {158 <T as Config>::RuntimeCall::decode(&mut data)159 .map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())160 }161}162163pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {164 fn drop(call: &ScheduledCall<T>);165166 fn peek(167 call: &ScheduledCall<T>,168 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;169170 /// Convert the given scheduled `call` value back into its original instance. If successful,171 /// `drop` any data backing it. This will not break the realisability of independently172 /// created instances of `ScheduledCall` which happen to have identical data.173 fn realize(174 call: &ScheduledCall<T>,175 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;176}177178impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {179 fn drop(call: &ScheduledCall<T>) {180 match call {181 ScheduledCall::Inline(_) => {}182 ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),183 }184 }185186 fn peek(187 call: &ScheduledCall<T>,188 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {189 match call {190 ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),191 ScheduledCall::PreimageLookup {192 hash,193 unbounded_len,194 } => {195 let (preimage, len) = Self::get_preimage(hash)196 .ok_or(<Error<T>>::PreimageNotFound)197 .map(|preimage| (preimage, *unbounded_len))?;198199 Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))200 }201 }202 }203204 fn realize(205 call: &ScheduledCall<T>,206 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {207 let r = Self::peek(call)?;208 Self::drop(call);209 Ok(r)210 }211}212213pub enum ScheduledEnsureOriginSuccess<AccountId> {214 Root,215 Signed(AccountId),216}217218pub type TaskName = [u8; 32];219220/// Information regarding an item to be executed in the future.221#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]222#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]223pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {224 /// The unique identity for this task, if there is one.225 maybe_id: Option<Name>,226227 /// This task's priority.228 priority: schedule::Priority,229230 /// The call to be dispatched.231 call: Call,232233 /// If the call is periodic, then this points to the information concerning that.234 maybe_periodic: Option<schedule::Period<BlockNumber>>,235236 /// The origin with which to dispatch the call.237 origin: PalletsOrigin,238 _phantom: PhantomData<AccountId>,239}240241pub type ScheduledOf<T> = Scheduled<242 TaskName,243 ScheduledCall<T>,244 <T as frame_system::Config>::BlockNumber,245 <T as Config>::PalletsOrigin,246 <T as frame_system::Config>::AccountId,247>;248249struct WeightCounter {250 used: Weight,251 limit: Weight,252}253254impl WeightCounter {255 fn check_accrue(&mut self, w: Weight) -> bool {256 let test = self.used.saturating_add(w);257 if test.any_gt(self.limit) {258 false259 } else {260 self.used = test;261 true262 }263 }264265 fn can_accrue(&mut self, w: Weight) -> bool {266 self.used.saturating_add(w).all_lte(self.limit)267 }268}269270pub(crate) trait MarginalWeightInfo: WeightInfo {271 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {272 let base = Self::service_task_base();273 let mut total = match maybe_lookup_len {274 None => base,275 Some(l) => Self::service_task_fetched(l as u32),276 };277 if named {278 total.saturating_accrue(Self::service_task_named().saturating_sub(base));279 }280 if periodic {281 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));282 }283 total284 }285}286287impl<T: WeightInfo> MarginalWeightInfo for T {}288289#[frame_support::pallet]290pub mod pallet {291 use super::*;292 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};293 use system::pallet_prelude::*;294295 /// The current storage version.296 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);297298 #[pallet::pallet]299 #[pallet::generate_store(pub(super) trait Store)]300 #[pallet::storage_version(STORAGE_VERSION)]301 pub struct Pallet<T>(_);302303 #[pallet::config]304 pub trait Config: frame_system::Config {305 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;306307 /// The aggregated origin which the dispatch will take.308 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>309 + From<Self::PalletsOrigin>310 + IsType<<Self as system::Config>::RuntimeOrigin>311 + Clone;312313 /// The caller origin, overarching type of all pallets origins.314 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>315 + Codec316 + Clone317 + Eq318 + TypeInfo319 + MaxEncodedLen;320321 /// The aggregated call type.322 type RuntimeCall: Parameter323 + Dispatchable<324 RuntimeOrigin = <Self as Config>::RuntimeOrigin,325 PostInfo = PostDispatchInfo,326 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>327 + GetDispatchInfo328 + From<system::Call<Self>>;329330 /// The maximum weight that may be scheduled per block for any dispatchables.331 #[pallet::constant]332 type MaximumWeight: Get<Weight>;333334 /// Required origin to schedule or cancel calls.335 type ScheduleOrigin: EnsureOrigin<336 <Self as system::Config>::RuntimeOrigin,337 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,338 >;339340 /// Compare the privileges of origins.341 ///342 /// This will be used when canceling a task, to ensure that the origin that tries343 /// to cancel has greater or equal privileges as the origin that created the scheduled task.344 ///345 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can346 /// be used. This will only check if two given origins are equal.347 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;348349 /// The maximum number of scheduled calls in the queue for a single block.350 #[pallet::constant]351 type MaxScheduledPerBlock: Get<u32>;352353 /// Weight information for extrinsics in this pallet.354 type WeightInfo: WeightInfo;355356 /// The preimage provider with which we look up call hashes to get the call.357 type Preimages: SchedulerPreimages<Self>;358359 /// The helper type used for custom transaction fee logic.360 type CallExecutor: DispatchCall<Self, H160>;361362 /// Required origin to set/change calls' priority.363 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;364 }365366 #[pallet::storage]367 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;368369 /// Items to be executed, indexed by the block number that they should be executed on.370 #[pallet::storage]371 pub type Agenda<T: Config> = StorageMap<372 _,373 Twox64Concat,374 T::BlockNumber,375 BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,376 ValueQuery,377 >;378379 /// Lookup from a name to the block number and index of the task.380 #[pallet::storage]381 pub(crate) type Lookup<T: Config> =382 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;383384 /// Events type.385 #[pallet::event]386 #[pallet::generate_deposit(pub(super) fn deposit_event)]387 pub enum Event<T: Config> {388 /// Scheduled some task.389 Scheduled { when: T::BlockNumber, index: u32 },390 /// Canceled some task.391 Canceled { when: T::BlockNumber, index: u32 },392 /// Dispatched some task.393 Dispatched {394 task: TaskAddress<T::BlockNumber>,395 id: Option<[u8; 32]>,396 result: DispatchResult,397 },398 /// Scheduled task's priority has changed399 PriorityChanged {400 when: T::BlockNumber,401 index: u32,402 priority: schedule::Priority,403 },404 /// The call for the provided hash was not found so the task has been aborted.405 CallUnavailable {406 task: TaskAddress<T::BlockNumber>,407 id: Option<[u8; 32]>,408 },409 /// The given task was unable to be renewed since the agenda is full at that block.410 PeriodicFailed {411 task: TaskAddress<T::BlockNumber>,412 id: Option<[u8; 32]>,413 },414 /// The given task can never be executed since it is overweight.415 PermanentlyOverweight {416 task: TaskAddress<T::BlockNumber>,417 id: Option<[u8; 32]>,418 },419 }420421 #[pallet::error]422 pub enum Error<T> {423 /// Failed to schedule a call424 FailedToSchedule,425 /// There is no place for a new task in the agenda426 AgendaIsExhausted,427 /// Scheduled call is corrupted428 ScheduledCallCorrupted,429 /// Scheduled call preimage is not found430 PreimageNotFound,431 /// Scheduled call is too big432 TooBigScheduledCall,433 /// Cannot find the scheduled call.434 NotFound,435 /// Given target block number is in the past.436 TargetBlockNumberInPast,437 /// Attempt to use a non-named function on a named task.438 Named,439 }440441 #[pallet::hooks]442 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {443 /// Execute the scheduled calls444 fn on_initialize(now: T::BlockNumber) -> Weight {445 let mut weight_counter = WeightCounter {446 used: Weight::zero(),447 limit: T::MaximumWeight::get(),448 };449 Self::service_agendas(&mut weight_counter, now, u32::max_value());450 weight_counter.used451 }452 }453454 #[pallet::call]455 impl<T: Config> Pallet<T> {456 /// Anonymously schedule a task.457 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]458 pub fn schedule(459 origin: OriginFor<T>,460 when: T::BlockNumber,461 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,462 priority: Option<schedule::Priority>,463 call: Box<<T as Config>::RuntimeCall>,464 ) -> DispatchResult {465 T::ScheduleOrigin::ensure_origin(origin.clone())?;466467 if priority.is_some() {468 T::PrioritySetOrigin::ensure_origin(origin.clone())?;469 }470471 let origin = <T as Config>::RuntimeOrigin::from(origin);472 Self::do_schedule(473 DispatchTime::At(when),474 maybe_periodic,475 priority.unwrap_or(LOWEST_PRIORITY),476 origin.caller().clone(),477 <ScheduledCall<T>>::new(*call)?,478 )?;479 Ok(())480 }481482 /// Cancel an anonymously scheduled task.483 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]484 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {485 T::ScheduleOrigin::ensure_origin(origin.clone())?;486 let origin = <T as Config>::RuntimeOrigin::from(origin);487 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;488 Ok(())489 }490491 /// Schedule a named task.492 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]493 pub fn schedule_named(494 origin: OriginFor<T>,495 id: TaskName,496 when: T::BlockNumber,497 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,498 priority: Option<schedule::Priority>,499 call: Box<<T as Config>::RuntimeCall>,500 ) -> DispatchResult {501 T::ScheduleOrigin::ensure_origin(origin.clone())?;502503 if priority.is_some() {504 T::PrioritySetOrigin::ensure_origin(origin.clone())?;505 }506507 let origin = <T as Config>::RuntimeOrigin::from(origin);508 Self::do_schedule_named(509 id,510 DispatchTime::At(when),511 maybe_periodic,512 priority.unwrap_or(LOWEST_PRIORITY),513 origin.caller().clone(),514 <ScheduledCall<T>>::new(*call)?,515 )?;516 Ok(())517 }518519 /// Cancel a named scheduled task.520 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]521 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {522 T::ScheduleOrigin::ensure_origin(origin.clone())?;523 let origin = <T as Config>::RuntimeOrigin::from(origin);524 Self::do_cancel_named(Some(origin.caller().clone()), id)?;525 Ok(())526 }527528 /// Anonymously schedule a task after a delay.529 ///530 /// # <weight>531 /// Same as [`schedule`].532 /// # </weight>533 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]534 pub fn schedule_after(535 origin: OriginFor<T>,536 after: T::BlockNumber,537 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,538 priority: Option<schedule::Priority>,539 call: Box<<T as Config>::RuntimeCall>,540 ) -> DispatchResult {541 T::ScheduleOrigin::ensure_origin(origin.clone())?;542543 if priority.is_some() {544 T::PrioritySetOrigin::ensure_origin(origin.clone())?;545 }546547 let origin = <T as Config>::RuntimeOrigin::from(origin);548 Self::do_schedule(549 DispatchTime::After(after),550 maybe_periodic,551 priority.unwrap_or(LOWEST_PRIORITY),552 origin.caller().clone(),553 <ScheduledCall<T>>::new(*call)?,554 )?;555 Ok(())556 }557558 /// Schedule a named task after a delay.559 ///560 /// # <weight>561 /// Same as [`schedule_named`](Self::schedule_named).562 /// # </weight>563 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]564 pub fn schedule_named_after(565 origin: OriginFor<T>,566 id: TaskName,567 after: T::BlockNumber,568 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,569 priority: Option<schedule::Priority>,570 call: Box<<T as Config>::RuntimeCall>,571 ) -> DispatchResult {572 T::ScheduleOrigin::ensure_origin(origin.clone())?;573574 if priority.is_some() {575 T::PrioritySetOrigin::ensure_origin(origin.clone())?;576 }577578 let origin = <T as Config>::RuntimeOrigin::from(origin);579 Self::do_schedule_named(580 id,581 DispatchTime::After(after),582 maybe_periodic,583 priority.unwrap_or(LOWEST_PRIORITY),584 origin.caller().clone(),585 <ScheduledCall<T>>::new(*call)?,586 )?;587 Ok(())588 }589590 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]591 pub fn change_named_priority(592 origin: OriginFor<T>,593 id: TaskName,594 priority: schedule::Priority,595 ) -> DispatchResult {596 T::PrioritySetOrigin::ensure_origin(origin.clone())?;597 let origin = <T as Config>::RuntimeOrigin::from(origin);598 Self::do_change_named_priority(origin.caller().clone(), id, priority)599 }600 }601}602603impl<T: Config> Pallet<T> {604 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {605 let now = frame_system::Pallet::<T>::block_number();606607 let when = match when {608 DispatchTime::At(x) => x,609 // The current block has already completed it's scheduled tasks, so610 // Schedule the task at lest one block after this current block.611 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),612 };613614 if when <= now {615 return Err(Error::<T>::TargetBlockNumberInPast.into());616 }617618 Ok(when)619 }620621 fn place_task(622 when: T::BlockNumber,623 what: ScheduledOf<T>,624 ) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {625 let maybe_name = what.maybe_id;626 let index = Self::push_to_agenda(when, what)?;627 let address = (when, index);628 if let Some(name) = maybe_name {629 Lookup::<T>::insert(name, address)630 }631 Self::deposit_event(Event::Scheduled {632 when: address.0,633 index: address.1,634 });635 Ok(address)636 }637638 fn push_to_agenda(639 when: T::BlockNumber,640 what: ScheduledOf<T>,641 ) -> Result<u32, (DispatchError, ScheduledOf<T>)> {642 let mut agenda = Agenda::<T>::get(when);643 let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {644 // will always succeed due to the above check.645 let _ = agenda.try_push(Some(what));646 agenda.len() as u32 - 1647 } else {648 if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {649 agenda[hole_index] = Some(what);650 hole_index as u32651 } else {652 return Err((<Error<T>>::AgendaIsExhausted.into(), what));653 }654 };655 Agenda::<T>::insert(when, agenda);656 Ok(index)657 }658659 fn do_schedule(660 when: DispatchTime<T::BlockNumber>,661 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,662 priority: schedule::Priority,663 origin: T::PalletsOrigin,664 call: ScheduledCall<T>,665 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {666 let when = Self::resolve_time(when)?;667668 // sanitize maybe_periodic669 let maybe_periodic = maybe_periodic670 .filter(|p| p.1 > 1 && !p.0.is_zero())671 // Remove one from the number of repetitions since we will schedule one now.672 .map(|(p, c)| (p, c - 1));673 let task = Scheduled {674 maybe_id: None,675 priority,676 call,677 maybe_periodic,678 origin,679 _phantom: PhantomData,680 };681 Self::place_task(when, task).map_err(|x| x.0)682 }683684 fn do_cancel(685 origin: Option<T::PalletsOrigin>,686 (when, index): TaskAddress<T::BlockNumber>,687 ) -> Result<(), DispatchError> {688 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {689 agenda.get_mut(index as usize).map_or(690 Ok(None),691 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {692 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {693 if matches!(694 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),695 Some(Ordering::Less) | None696 ) {697 return Err(BadOrigin.into());698 }699 };700 Ok(s.take())701 },702 )703 })?;704 if let Some(s) = scheduled {705 T::Preimages::drop(&s.call);706707 if let Some(id) = s.maybe_id {708 Lookup::<T>::remove(id);709 }710 Self::deposit_event(Event::Canceled { when, index });711 Ok(())712 } else {713 return Err(Error::<T>::NotFound.into());714 }715 }716717 fn do_schedule_named(718 id: TaskName,719 when: DispatchTime<T::BlockNumber>,720 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,721 priority: schedule::Priority,722 origin: T::PalletsOrigin,723 call: ScheduledCall<T>,724 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {725 // ensure id it is unique726 if Lookup::<T>::contains_key(&id) {727 return Err(Error::<T>::FailedToSchedule.into());728 }729730 let when = Self::resolve_time(when)?;731732 // sanitize maybe_periodic733 let maybe_periodic = maybe_periodic734 .filter(|p| p.1 > 1 && !p.0.is_zero())735 // Remove one from the number of repetitions since we will schedule one now.736 .map(|(p, c)| (p, c - 1));737738 let task = Scheduled {739 maybe_id: Some(id),740 priority,741 call,742 maybe_periodic,743 origin,744 _phantom: Default::default(),745 };746 Self::place_task(when, task).map_err(|x| x.0)747 }748749 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {750 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {751 if let Some((when, index)) = lookup.take() {752 let i = index as usize;753 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {754 if let Some(s) = agenda.get_mut(i) {755 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {756 if matches!(757 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),758 Some(Ordering::Less) | None759 ) {760 return Err(BadOrigin.into());761 }762 T::Preimages::drop(&s.call);763 }764 *s = None;765 }766 Ok(())767 })?;768 Self::deposit_event(Event::Canceled { when, index });769 Ok(())770 } else {771 return Err(Error::<T>::NotFound.into());772 }773 })774 }775776 fn do_change_named_priority(777 origin: T::PalletsOrigin,778 id: TaskName,779 priority: schedule::Priority,780 ) -> DispatchResult {781 match Lookup::<T>::get(id) {782 Some((when, index)) => {783 let i = index as usize;784 Agenda::<T>::try_mutate(when, |agenda| {785 if let Some(Some(s)) = agenda.get_mut(i) {786 if matches!(787 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),788 Some(Ordering::Less) | None789 ) {790 return Err(BadOrigin.into());791 }792793 s.priority = priority;794 Self::deposit_event(Event::PriorityChanged {795 when,796 index,797 priority,798 });799 }800 Ok(())801 })802 }803 None => Err(Error::<T>::NotFound.into()),804 }805 }806}807808enum ServiceTaskError {809 /// Could not be executed due to missing preimage.810 Unavailable,811 /// Could not be executed due to weight limitations.812 Overweight,813}814use ServiceTaskError::*;815816/// A Scheduler-Runtime interface for finer payment handling.817pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {818 /// Resolve the call dispatch, including any post-dispatch operations.819 fn dispatch_call(820 signer: Option<T::AccountId>,821 function: <T as Config>::RuntimeCall,822 ) -> Result<823 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,824 TransactionValidityError,825 >;826}827828impl<T: Config> Pallet<T> {829 /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.830 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {831 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {832 return;833 }834835 let mut incomplete_since = now + One::one();836 let mut when = IncompleteSince::<T>::take().unwrap_or(now);837 let mut executed = 0;838839 let max_items = T::MaxScheduledPerBlock::get();840 let mut count_down = max;841 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);842 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {843 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {844 incomplete_since = incomplete_since.min(when);845 }846 when.saturating_inc();847 count_down.saturating_dec();848 }849 incomplete_since = incomplete_since.min(when);850 if incomplete_since <= now {851 IncompleteSince::<T>::put(incomplete_since);852 }853 }854855 /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a856 /// later block.857 fn service_agenda(858 weight: &mut WeightCounter,859 executed: &mut u32,860 now: T::BlockNumber,861 when: T::BlockNumber,862 max: u32,863 ) -> bool {864 let mut agenda = Agenda::<T>::get(when);865 let mut ordered = agenda866 .iter()867 .enumerate()868 .filter_map(|(index, maybe_item)| {869 maybe_item870 .as_ref()871 .map(|item| (index as u32, item.priority))872 })873 .collect::<Vec<_>>();874 ordered.sort_by_key(|k| k.1);875 let within_limit =876 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));877 debug_assert!(878 within_limit,879 "weight limit should have been checked in advance"880 );881882 // Items which we know can be executed and have postponed for execution in a later block.883 let mut postponed = (ordered.len() as u32).saturating_sub(max);884 // Items which we don't know can ever be executed.885 let mut dropped = 0;886887 for (agenda_index, _) in ordered.into_iter().take(max as usize) {888 let task = match agenda[agenda_index as usize].take() {889 None => continue,890 Some(t) => t,891 };892 let base_weight = T::WeightInfo::service_task(893 task.call.lookup_len().map(|x| x as usize),894 task.maybe_id.is_some(),895 task.maybe_periodic.is_some(),896 );897 if !weight.can_accrue(base_weight) {898 postponed += 1;899 break;900 }901 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);902 agenda[agenda_index as usize] = match result {903 Err((Unavailable, slot)) => {904 dropped += 1;905 slot906 }907 Err((Overweight, slot)) => {908 postponed += 1;909 slot910 }911 Ok(()) => {912 *executed += 1;913 None914 }915 };916 }917 if postponed > 0 || dropped > 0 {918 Agenda::<T>::insert(when, agenda);919 } else {920 Agenda::<T>::remove(when);921 }922 postponed == 0923 }924925 /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.926 ///927 /// This involves:928 /// - removing and potentially replacing the `Lookup` entry for the task.929 /// - realizing the task's call which can include a preimage lookup.930 /// - Rescheduling the task for execution in a later agenda if periodic.931 fn service_task(932 weight: &mut WeightCounter,933 now: T::BlockNumber,934 when: T::BlockNumber,935 agenda_index: u32,936 is_first: bool,937 mut task: ScheduledOf<T>,938 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {939 let (call, lookup_len) = match T::Preimages::peek(&task.call) {940 Ok(c) => c,941 Err(_) => {942 if let Some(ref id) = task.maybe_id {943 Lookup::<T>::remove(id);944 }945946 return Err((Unavailable, Some(task)));947 }948 };949950 weight.check_accrue(T::WeightInfo::service_task(951 lookup_len.map(|x| x as usize),952 task.maybe_id.is_some(),953 task.maybe_periodic.is_some(),954 ));955956 match Self::execute_dispatch(weight, task.origin.clone(), call) {957 Err(Unavailable) => {958 debug_assert!(false, "Checked to exist with `peek`");959960 if let Some(ref id) = task.maybe_id {961 Lookup::<T>::remove(id);962 }963964 Self::deposit_event(Event::CallUnavailable {965 task: (when, agenda_index),966 id: task.maybe_id,967 });968 Err((Unavailable, Some(task)))969 }970 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {971 T::Preimages::drop(&task.call);972973 if let Some(ref id) = task.maybe_id {974 Lookup::<T>::remove(id);975 }976977 Self::deposit_event(Event::PermanentlyOverweight {978 task: (when, agenda_index),979 id: task.maybe_id,980 });981 Err((Unavailable, Some(task)))982 }983 Err(Overweight) => {984 // Preserve Lookup -- the task will be postponed.985 Err((Overweight, Some(task)))986 }987 Ok(result) => {988 Self::deposit_event(Event::Dispatched {989 task: (when, agenda_index),990 id: task.maybe_id,991 result,992 });993994 let is_canceled = task995 .maybe_id996 .as_ref()997 .map(|id| !Lookup::<T>::contains_key(id))998 .unwrap_or(false);9991000 match &task.maybe_periodic {1001 &Some((period, count)) if !is_canceled => {1002 if count > 1 {1003 task.maybe_periodic = Some((period, count - 1));1004 } else {1005 task.maybe_periodic = None;1006 }1007 let wake = now.saturating_add(period);1008 match Self::place_task(wake, task) {1009 Ok(_) => {}1010 Err((_, task)) => {1011 // TODO: Leave task in storage somewhere for it to be rescheduled1012 // manually.1013 T::Preimages::drop(&task.call);1014 Self::deposit_event(Event::PeriodicFailed {1015 task: (when, agenda_index),1016 id: task.maybe_id,1017 });1018 }1019 }1020 }1021 _ => {1022 if let Some(ref id) = task.maybe_id {1023 Lookup::<T>::remove(id);1024 }10251026 T::Preimages::drop(&task.call)1027 }1028 }1029 Ok(())1030 }1031 }1032 }10331034 fn is_runtime_upgraded() -> bool {1035 let last = system::LastRuntimeUpgrade::<T>::get();1036 let current = T::Version::get();10371038 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1039 }10401041 /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1042 /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1043 /// post info if available).1044 ///1045 /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1046 /// call itself).1047 fn execute_dispatch(1048 weight: &mut WeightCounter,1049 origin: T::PalletsOrigin,1050 call: <T as Config>::RuntimeCall,1051 ) -> Result<DispatchResult, ServiceTaskError> {1052 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1053 let base_weight = match dispatch_origin.clone().as_signed() {1054 Some(_) => T::WeightInfo::execute_dispatch_signed(),1055 _ => T::WeightInfo::execute_dispatch_unsigned(),1056 };1057 let call_weight = call.get_dispatch_info().weight;1058 // We only allow a scheduled call if it cannot push the weight past the limit.1059 let max_weight = base_weight.saturating_add(call_weight);10601061 if !weight.can_accrue(max_weight) {1062 return Err(Overweight);1063 }10641065 // let scheduled_origin =1066 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1067 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10681069 let r = match ensured_origin {1070 Ok(ScheduledEnsureOriginSuccess::Root) => {1071 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1072 }1073 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1074 // Execute transaction via chain default pipeline1075 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1076 T::CallExecutor::dispatch_call(Some(sender), call.clone())1077 }1078 Err(e) => Ok(Err(e.into())),1079 };10801081 let (maybe_actual_call_weight, result) = match r {1082 Ok(result) => match result {1083 Ok(post_info) => (post_info.actual_weight, Ok(())),1084 Err(error_and_info) => (1085 error_and_info.post_info.actual_weight,1086 Err(error_and_info.error),1087 ),1088 },1089 Err(_) => {1090 log::error!(1091 target: "runtime::scheduler",1092 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1093 This block might have become invalid.");1094 (None, Err(DispatchError::CannotLookup))1095 }1096 };1097 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1098 weight.check_accrue(base_weight);1099 weight.check_accrue(call_weight);1100 Ok(result)1101 }1102}pallets/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()
-}
pallets/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);
- });
-}
pallets/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))
- }
-}
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -221,6 +221,7 @@
}
/// Token data.
+#[struct_versioning::versioned(version = 2, upper)]
#[derive(Encode, Decode, Clone, PartialEq, TypeInfo)]
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct TokenData<CrossAccountId> {
@@ -231,6 +232,7 @@
pub owner: Option<CrossAccountId>,
/// Token pieces.
+ #[version(2.., upper(0))]
pub pieces: u128,
}
primitives/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>;
runtime/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;
}
runtime/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,
runtime/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,
+ ),
+ )
+ }
+}
runtime/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 }
test-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",
]
test-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)?;
}
tests/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;
tests/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,
);