difftreelog
Merge pull request #341 from UniqueNetwork/feature/simple-scheduler
in: master
Feature/simple scheduler
11 files changed
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -15,11 +15,13 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.22' }
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22" }
@@ -40,6 +42,7 @@
"up-sponsorship/std",
"sp-io/std",
"sp-std/std",
+ "sp-core/std",
"log/std",
]
runtime-benchmarks = [
pallets/scheduler/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 license18// This file is part of Substrate.1// This file is part of Substrate.19220// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.3// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.04// SPDX-License-Identifier: Apache-2.022523// Licensed under the Apache License, Version 2.0 (the "License");6// Licensed under the Apache License, Version 2.0 (the "License");32// See the License for the specific language governing permissions and15// See the License for the specific language governing permissions and33// limitations under the License.16// limitations under the License.341735//! # Scheduler18//! # Schedulerdo_reschedule36//! A module for scheduling dispatches.37//!19//!38//! - [`Config`]20//! This Pallet exposes capabilities for scheduling dispatches to occur at a39//! - [`Call`]40//! - [`Module`]41//!42//! ## Overview43//!44//! This module exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches21//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.22//! may be named or anonymous and may be canceled.47//!23//!57//!33//!58//! ### Dispatchable Functions34//! ### Dispatchable Functions59//!35//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a36//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//! specified block and with a specified priority.37//! with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and38//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! index.64//! * `schedule_named` - augments the `schedule` interface with an additional39//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter65//! `Vec<u8>` parameter that can be used for identification.40//! that can be used for identification.66//! * `cancel_named` - the named complement to the cancel function.41//! * `cancel_named` - the named complement to the cancel function.674268// Ensure we're `no_std` when compiling for Wasm.43// Ensure we're `no_std` when compiling for Wasm.69#![cfg_attr(not(feature = "std"), no_std)]44#![cfg_attr(not(feature = "std"), no_std)]70#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]714546#[cfg(feature = "runtime-benchmarks")]72mod benchmarking;47mod benchmarking;4873pub mod weights;49pub mod weights;745075use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};51use sp_core::H160;52use codec::{Codec, Decode, Encode};76use codec::{Encode, Decode, Codec};53use frame_system::{self as system, ensure_signed};54pub use pallet::*;55use scale_info::TypeInfo;77use sp_runtime::{56use sp_runtime::{78 RuntimeDebug,57 traits::{BadOrigin, One, Saturating, Zero},79 traits::{Zero, One, BadOrigin, Saturating},58 RuntimeDebug, DispatchErrorWithPostInfo,80};59};60use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};6181use frame_support::{62use frame_support::{82 decl_module, decl_storage, decl_event, decl_error,63 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},83 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},84 traits::{64 traits::{85 Get,65 schedule::{self, DispatchTime, MaybeHashed},86 schedule::{self, DispatchTime},87 OriginTrait, EnsureOrigin, IsType,66 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,67 StorageVersion,88 },68 },89 weights::{GetDispatchInfo, Weight},69 weights::{GetDispatchInfo, Weight},90};70};91use frame_system::{self as system, ensure_signed};7192pub use weights::WeightInfo;72pub use weights::WeightInfo;93use up_sponsorship::SponsorshipHandler;94use scale_info::TypeInfo;957396/// Our pallet's configuration trait. All our types and constants go in here. If the97/// pallet is dependent on specific other pallets, then their configuration traits98/// should be added to our implied traits list.99///100/// `system::Config` should always be included in our implied traits.101/// //102pub trait Config: system::Config {103 /// The overarching event type.104 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;105106 /// The aggregated origin which the dispatch will take.107 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>108 + From<Self::PalletsOrigin>109 + IsType<<Self as system::Config>::Origin>;110111 /// The caller origin, overarching type of all pallets origins.112 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;113114 /// The aggregated call type.115 type Call: Parameter116 + Dispatchable<Origin = <Self as Config>::Origin>117 + GetDispatchInfo118 + From<system::Call<Self>>;119120 /// The maximum weight that may be scheduled per block for any dispatchables of less priority121 /// than `schedule::HARD_DEADLINE`.122 type MaximumWeight: Get<Weight>;123124 /// Required origin to schedule or cancel calls.125 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;126127 /// The maximum number of scheduled calls in the queue for a single block.128 /// Not strictly enforced, but used for weight estimation.129 type MaxScheduledPerBlock: Get<u32>;130131 /// Sponsoring function132 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;133134 /// Weight information for extrinsics in this pallet.135 type WeightInfo: WeightInfo;136}137138// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;139140/// Just a simple index for naming period tasks.74/// Just a simple index for naming period tasks.141pub type PeriodicIndex = u32;75pub type PeriodicIndex = u32;142/// The location of a scheduled task that can be used to remove it.76/// The location of a scheduled task that can be used to remove it.143pub type TaskAddress<BlockNumber> = (BlockNumber, u32);77pub type TaskAddress<BlockNumber> = (BlockNumber, u32);78pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;14479145#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]80type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];146#[derive(Clone, RuntimeDebug, Encode, Decode)]147struct ScheduledV1<Call, BlockNumber> {81pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;148 maybe_id: Option<Vec<u8>>,149 priority: schedule::Priority,150 call: Call,151 maybe_periodic: Option<schedule::Period<BlockNumber>>,152}15382154/// Information regarding an item to be executed in the future.83/// Information regarding an item to be executed in the future.155#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]84#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]156#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]85#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]157pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {86pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {158 /// The unique identity for this task, if there is one.87 /// The unique identity for this task, if there is one.159 maybe_id: Option<Vec<u8>>,88 maybe_id: Option<ScheduledId>,160 /// This task's priority.89 /// This task's priority.161 priority: schedule::Priority,90 priority: schedule::Priority,162 /// The call to be dispatched.91 /// The call to be dispatched.168 _phantom: PhantomData<AccountId>,97 _phantom: PhantomData<AccountId>,169}98}17099100pub type ScheduledV3Of<T> = ScheduledV3<101 CallOrHashOf<T>,102 <T as frame_system::Config>::BlockNumber,103 <T as Config>::PalletsOrigin,104 <T as frame_system::Config>::AccountId,105>;106107pub type ScheduledOf<T> = ScheduledV3Of<T>;108171/// The current version of Scheduled struct.109/// The current version of Scheduled struct.172pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =110pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =173 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;111 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;174112175// A value placed in storage that represents the current version of the Scheduler storage.113#[cfg(feature = "runtime-benchmarks")]176// This value is used by the `on_runtime_upgrade` logic to determine whether we run114mod preimage_provider {177// storage migration logic.115 use frame_support::traits::PreimageRecipient;178#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]116 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}179enum Releases {117 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}180 V1,181 V2,182}118}183119184impl Default for Releases {120#[cfg(not(feature = "runtime-benchmarks"))]121mod preimage_provider {185 fn default() -> Self {122 use frame_support::traits::PreimageProvider;123 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}186 Releases::V1124 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}187 }188}125}189126127pub use preimage_provider::PreimageProviderAndMaybeRecipient;128190#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]129pub(crate) trait MarginalWeightInfo: WeightInfo {130 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {131 match (periodic, named, resolved) {132 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),191pub struct CallSpec {133 (_, true, None) => {192 module: u32,134 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)135 }136 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),193 method: u32,137 (false, true, Some(false)) => {138 Self::on_initialize_named(2) - Self::on_initialize_named(1)139 }140 (true, false, Some(false)) => {141 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)142 }143 (true, true, Some(false)) => {144 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)145 }146 (false, false, Some(true)) => {147 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)148 }149 (false, true, Some(true)) => {150 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)151 }152 (true, false, Some(true)) => {153 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)154 }155 (true, true, Some(true)) => {156 Self::on_initialize_periodic_named_resolved(2)157 - Self::on_initialize_periodic_named_resolved(1)158 }159 }160 }194}161}162impl<T: WeightInfo> MarginalWeightInfo for T {}195163164#[frame_support::pallet]196decl_storage! {165pub mod pallet {197 trait Store for Module<T: Config> as Scheduler {166 use super::*;167 use frame_support::{198 /// Items to be executed, indexed by the block number that they should be executed on.168 dispatch::PostDispatchInfo,199 pub Agenda: map hasher(twox_64_concat) T::BlockNumber169 pallet_prelude::*,200 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;170 traits::{schedule::LookupError, PreimageProvider},171 };172 use frame_system::pallet_prelude::*;201173202 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber174 /// The current storage version.203 => Vec<Option<CallSpec>>;175 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);204176205 /// Lookup from identity to the block number and index of the task.177 #[pallet::pallet]178 #[pallet::generate_store(pub(super) trait Store)]206 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;179 #[pallet::storage_version(STORAGE_VERSION)]180 #[pallet::without_storage_info]181 pub struct Pallet<T>(_);207182208 /// Storage version of the pallet.183 /// `system::Config` should always be included in our implied traits.184 #[pallet::config]185 pub trait Config: frame_system::Config {186 /// The overarching event type.187 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;188189 /// The aggregated origin which the dispatch will take.190 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>191 + From<Self::PalletsOrigin>192 + IsType<<Self as system::Config>::Origin>;193194 /// The caller origin, overarching type of all pallets origins.195 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;196197 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;198199 /// The aggregated call type.200 type Call: Parameter201 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>202 + GetDispatchInfo203 + From<system::Call<Self>>;204205 /// The maximum weight that may be scheduled per block for any dispatchables of less206 /// priority than `schedule::HARD_DEADLINE`.207 #[pallet::constant]208 type MaximumWeight: Get<Weight>;209210 /// Required origin to schedule or cancel calls.211 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;212213 /// Compare the privileges of origins.209 ///214 ///210 /// New networks start with last version.215 /// This will be used when canceling a task, to ensure that the origin that tries216 /// to cancel has greater or equal privileges as the origin that created the scheduled task.211 StorageVersion build(|_| Releases::V2): Releases;217 ///218 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can219 /// be used. This will only check if two given origins are equal.220 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;221222 /// The maximum number of scheduled calls in the queue for a single block.223 /// Not strictly enforced, but used for weight estimation.224 #[pallet::constant]225 type MaxScheduledPerBlock: Get<u32>;226227 /// Weight information for extrinsics in this pallet.228 type WeightInfo: WeightInfo;229230 /// The preimage provider with which we look up call hashes to get the call.231 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;232233 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.234 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;235236 /// Sponsoring function.237 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;238239 /// The helper type used for custom transaction fee logic.240 type CallExecutor: DispatchCall<Self, H160>;212 }241 }213}214242215decl_event!(243 /// A Scheduler-Runtime interface for finer payment handling.216 pub enum Event<T> where <T as system::Config>::BlockNumber {244 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {245 fn reserve_balance(246 id: ScheduledId,247 sponsor: <T as frame_system::Config>::AccountId,217 /// Scheduled some task. \[when, index\]248 call: <T as Config>::Call,249 count: u32,250 ) -> Result<(), DispatchError>;251218 Scheduled(BlockNumber, u32),252 fn pay_for_call(253 id: ScheduledId,254 sponsor: <T as frame_system::Config>::AccountId,255 call: <T as Config>::Call,256 ) -> Result<u128, DispatchError>;257219 /// Canceled some task. \[when, index\]258 /// Resolve the call dispatch, including any post-dispatch operations.220 Canceled(BlockNumber, u32),259 fn dispatch_call(260 signer: T::AccountId,221 /// Dispatched some task. \[task, id, result\]261 function: <T as Config>::Call,262 ) -> Result<222 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),263 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,264 TransactionValidityError,265 >;266267 fn cancel_reserve(268 id: ScheduledId,269 sponsor: <T as frame_system::Config>::AccountId,270 ) -> Result<u128, DispatchError>;223 }271 }224);225272226decl_error! {273 /// Items to be executed, indexed by the block number that they should be executed on.227 pub enum Error for Module<T: Config> {274 #[pallet::storage]275 pub type Agenda<T: Config> =276 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;277278 /// Lookup from identity to the block number and index of the task.279 #[pallet::storage]280 pub(crate) type Lookup<T: Config> =281 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;282283 /// Events type.284 #[pallet::event]285 #[pallet::generate_deposit(pub(super) fn deposit_event)]286 pub enum Event<T: Config> {287 /// Scheduled some task.288 Scheduled { when: T::BlockNumber, index: u32 },289 /// Canceled some task.290 Canceled { when: T::BlockNumber, index: u32 },291 /// Dispatched some task.292 Dispatched {293 task: TaskAddress<T::BlockNumber>,294 id: Option<ScheduledId>,295 result: DispatchResult,296 },297 /// The call for the provided hash was not found so the task has been aborted.298 CallLookupFailed {299 task: TaskAddress<T::BlockNumber>,300 id: Option<ScheduledId>,301 error: LookupError,302 },303 }304305 #[pallet::error]306 pub enum Error<T> {228 /// Failed to schedule a call307 /// Failed to schedule a call229 FailedToSchedule,308 FailedToSchedule,230 /// Cannot find the scheduled call.309 /// Cannot find the scheduled call.234 /// Reschedule failed because it does not change scheduled time.313 /// Reschedule failed because it does not change scheduled time.235 RescheduleNoChange,314 RescheduleNoChange,236 }315 }237}238316239decl_module! {240 /// Scheduler module declaration.317 #[pallet::hooks]241 pub struct Module<T: Config> for enum Call318 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {242 where319 /// Execute the scheduled calls243 origin: <T as system::Config>::Origin320 fn on_initialize(now: T::BlockNumber) -> Weight {244 {245 type Error = Error<T>;321 let limit = T::MaximumWeight::get();246 fn deposit_event() = default;247322323 let mut queued = Agenda::<T>::take(now)324 .into_iter()325 .enumerate()326 .filter_map(|(index, s)| Some((index as u32, s?)))327 .collect::<Vec<_>>();248328249 /// Anonymously schedule a task.329 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {250 ///251 /// # <weight>252 /// - S = Number of already scheduled calls253 /// - Base Weight: 22.29 + .126 * S µs254 /// - DB Weight:255 /// - Read: Agenda256 /// - Write: Agenda257 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls258 /// # </weight>259 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]260 fn schedule(origin,261 when: T::BlockNumber,330 log::warn!(262 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,331 target: "runtime::scheduler",263 priority: schedule::Priority,264 call: Box<<T as Config>::Call>,332 "Warning: This block has more items queued in Scheduler than \265 )333 expected from the runtime configuration. An update might be needed."266 {267 let origin = <T as Config>::Origin::from(origin);268 Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;334 );269 }335 }270336271 /// Cancel an anonymously scheduled task.337 queued.sort_by_key(|(_, s)| s.priority);272 ///338273 /// # <weight>339 let next = now + One::one();274 /// - S = Number of already scheduled calls340275 /// - Base Weight: 22.15 + 2.869 * S µs341 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);276 /// - DB Weight:342 for (order, (index, mut s)) in queued.into_iter().enumerate() {277 /// - Read: Agenda343 let named = if let Some(ref id) = s.maybe_id {278 /// - Write: Agenda, Lookup344 Lookup::<T>::remove(id);279 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls345 true280 /// # </weight>346 } else {281 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]347 false282 fn cancel(origin, when: T::BlockNumber, index: u32) {348 };283 T::ScheduleOrigin::ensure_origin(origin.clone())?;349284 let origin = <T as Config>::Origin::from(origin);350 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();285 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;351 s.call = call;352353 let resolved = if let Some(completed) = maybe_completed {354 T::PreimageProvider::unrequest_preimage(&completed);355 true356 } else {357 false358 };359 let call = match s.call.as_value().cloned() {360 Some(c) => c,361 None => {362 // Preimage not available - postpone until some block.363 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));364 if let Some(delay) = T::NoPreimagePostponement::get() {365 let until = now.saturating_add(delay);366 if let Some(ref id) = s.maybe_id {367 let index = Agenda::<T>::decode_len(until).unwrap_or(0);368 Lookup::<T>::insert(id, (until, index as u32));369 }370 Agenda::<T>::append(until, Some(s));371 }372 continue;373 }374 };375376 let periodic = s.maybe_periodic.is_some();377 let call_weight = call.get_dispatch_info().weight;378 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));379 let origin =380 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())381 .into();382 if ensure_signed(origin).is_ok() {383 // Weights of Signed dispatches expect their signing account to be whitelisted.384 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));385 }386387 // We allow a scheduled call if any is true:388 // - It's priority is `HARD_DEADLINE`389 // - It does not push the weight past the limit.390 // - It is the first item in the schedule391 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;392 let test_weight = total_weight393 .saturating_add(call_weight)394 .saturating_add(item_weight);395 if !hard_deadline && order > 0 && test_weight > limit {396 // Cannot be scheduled this block - postpone until next.397 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));398 if let Some(ref id) = s.maybe_id {399 // NOTE: We could reasonably not do this (in which case there would be one400 // block where the named and delayed item could not be referenced by name),401 // but we will do it anyway since it should be mostly free in terms of402 // weight and it is slightly cleaner.403 let index = Agenda::<T>::decode_len(next).unwrap_or(0);404 Lookup::<T>::insert(id, (next, index as u32));405 }406 Agenda::<T>::append(next, Some(s));407 continue;408 }409410 let sender = ensure_signed(411 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())412 .into(),413 )414 .unwrap();415416 // // if call have id it was be reserved417 // if s.maybe_id.is_some() {418 // let _ = T::CallExecutor::pay_for_call(419 // s.maybe_id.unwrap(),420 // sender.clone(),421 // call.clone(),422 // );423 // }424425 let r = T::CallExecutor::dispatch_call(sender, call.clone());426427 let mut actual_call_weight: Weight = item_weight;428 let result: Result<_, DispatchError> = match r {429 Ok(o) => match o {430 Ok(di) => {431 actual_call_weight = di.actual_weight.unwrap_or(item_weight);432 Ok(())433 }434 Err(err) => Err(err.error),435 },436 Err(_) => {437 log::error!(438 target: "runtime::scheduler",439 "Warning: Scheduler has failed to execute a post-dispatch transaction. \440 This block might have become invalid.");441 Err(DispatchError::CannotLookup)442 } // todo possibly force a skip/return here, do something with the error443 };444445 total_weight.saturating_accrue(item_weight);446 total_weight.saturating_accrue(actual_call_weight);447448 Self::deposit_event(Event::Dispatched {449 task: (now, index),450 id: s.maybe_id.clone(),451 result,452 });453454 if let &Some((period, count)) = &s.maybe_periodic {455 if count > 1 {456 s.maybe_periodic = Some((period, count - 1));457 } else {458 s.maybe_periodic = None;459 }460 let wake = now + period;461 // If scheduled is named, place its information in `Lookup`462 if let Some(ref id) = s.maybe_id {463 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);464 Lookup::<T>::insert(id, (wake, wake_index as u32));465 }466 Agenda::<T>::append(wake, Some(s));467 }468 }469 0470 //total_weight286 }471 }472 }287473474 #[pallet::call]475 impl<T: Config> Pallet<T> {288 /// Schedule a named task.476 /// Schedule a named task.289 ///477 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]290 /// # <weight>291 /// - S = Number of already scheduled calls292 /// - Base Weight: 29.6 + .159 * S µs293 /// - DB Weight:294 /// - Read: Agenda, Lookup295 /// - Write: Agenda, Lookup296 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls297 /// # </weight>298 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]299 fn schedule_named(origin,478 pub fn schedule_named(479 origin: OriginFor<T>,300 id: Vec<u8>,480 id: ScheduledId,301 when: T::BlockNumber,481 when: T::BlockNumber,302 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,482 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,303 priority: schedule::Priority,483 priority: schedule::Priority,304 call: Box<<T as Config>::Call>,484 call: Box<CallOrHashOf<T>>,305 ) {485 ) -> DispatchResult {306 T::ScheduleOrigin::ensure_origin(origin.clone())?;486 T::ScheduleOrigin::ensure_origin(origin.clone())?;307 let origin = <T as Config>::Origin::from(origin);487 let origin = <T as Config>::Origin::from(origin);308 Self::do_schedule_named(488 Self::do_schedule_named(309 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call489 id,490 DispatchTime::At(when),491 maybe_periodic,492 priority,493 origin.caller().clone(),494 *call,310 )?;495 )?;496 Ok(())311 }497 }312498313 /// Cancel a named scheduled task.499 /// Cancel a named scheduled task.314 ///500 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]315 /// # <weight>316 /// - S = Number of already scheduled calls317 /// - Base Weight: 24.91 + 2.907 * S µs318 /// - DB Weight:319 /// - Read: Agenda, Lookup320 /// - Write: Agenda, Lookup321 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls322 /// # </weight>323 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]324 fn cancel_named(origin, id: Vec<u8>) {501 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {325 T::ScheduleOrigin::ensure_origin(origin.clone())?;502 T::ScheduleOrigin::ensure_origin(origin.clone())?;326 let origin = <T as Config>::Origin::from(origin);503 let origin = <T as Config>::Origin::from(origin);327 Self::do_cancel_named(Some(origin.caller().clone()), id)?;504 Self::do_cancel_named(Some(origin.caller().clone()), id)?;505 Ok(())328 }506 }329507330 /// Anonymously schedule a task after a delay.331 ///332 /// # <weight>333 /// Same as [`schedule`].334 /// # </weight>335 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]336 fn schedule_after(origin,337 after: T::BlockNumber,338 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,339 priority: schedule::Priority,340 call: Box<<T as Config>::Call>,341 ) {342 T::ScheduleOrigin::ensure_origin(origin.clone())?;343 let origin = <T as Config>::Origin::from(origin);344 Self::do_schedule(345 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call346 )?;347 }348349 /// Schedule a named task after a delay.508 /// Schedule a named task after a delay.350 ///509 ///351 /// # <weight>510 /// # <weight>352 /// Same as [`schedule_named`].511 /// Same as [`schedule_named`](Self::schedule_named).353 /// # </weight>512 /// # </weight>354 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]513 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]355 fn schedule_named_after(origin,514 pub fn schedule_named_after(515 origin: OriginFor<T>,356 id: Vec<u8>,516 id: ScheduledId,357 after: T::BlockNumber,517 after: T::BlockNumber,358 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,518 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,359 priority: schedule::Priority,519 priority: schedule::Priority,360 call: Box<<T as Config>::Call>,520 call: Box<CallOrHashOf<T>>,361 ) {521 ) -> DispatchResult {362 T::ScheduleOrigin::ensure_origin(origin.clone())?;522 T::ScheduleOrigin::ensure_origin(origin.clone())?;363 let origin = <T as Config>::Origin::from(origin);523 let origin = <T as Config>::Origin::from(origin);364 Self::do_schedule_named(524 Self::do_schedule_named(365 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call525 id,526 DispatchTime::After(after),527 maybe_periodic,528 priority,529 origin.caller().clone(),530 *call,366 )?;531 )?;532 Ok(())367 }533 }534 }535}368536369 /// Execute the scheduled calls370 ///371 /// # <weight>537impl<T: Config> Pallet<T> {372 /// - S = Number of already scheduled calls373 /// - N = Named scheduled calls374 /// - P = Periodic Calls375 /// - Base Weight: 9.243 + 23.45 * S µs376 /// - DB Weight:377 /// - Read: Agenda + Lookup * N + Agenda(Future) * P378 /// - Write: Agenda + Lookup * N + Agenda(future) * P379 /// # </weight>380 fn on_initialize(now: T::BlockNumber) -> Weight {381 let limit = T::MaximumWeight::get();382 let mut queued = Agenda::<T>::take(now).into_iter()383 .enumerate()384 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))385 .collect::<Vec<_>>();386 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {387 log::warn!(538 #[cfg(feature = "try-runtime")]388 target: "runtime::scheduler",389 "Warning: This block has more items queued in Scheduler than \390 expected from the runtime configuration. An update might be needed."391 );392 }539 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {393 queued.sort_by_key(|(_, s)| s.priority);394 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)395 let mut total_weight: Weight = 0;396 queued.into_iter()397 .enumerate()398 .scan(base_weight, |cumulative_weight, (order, (index, s))| {399 *cumulative_weight = cumulative_weight540 Ok(())400 .saturating_add(s.call.get_dispatch_info().weight);541 }401542402 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(543 #[cfg(feature = "try-runtime")]403 s.origin.clone()544 pub fn post_migrate_to_v3() -> Result<(), &'static str> {404 ).into();545 use frame_support::dispatch::GetStorageVersion;405546406 if ensure_signed(origin).is_ok() {547 assert!(Self::current_storage_version() == 3);407 // AccountData for inner call origin accountdata.548 for k in Agenda::<T>::iter_keys() {408 *cumulative_weight = cumulative_weight549 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;409 .saturating_add(T::DbWeight::get().reads_writes(1, 1));410 }411412 if s.maybe_id.is_some() {413 // Remove/Modify Lookup414 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));415 }416 if s.maybe_periodic.is_some() {417 // Read/Write Agenda for future block418 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));419 }420421 Some((order, index, *cumulative_weight, s))422 })423 .filter_map(|(order, index, cumulative_weight, mut s)| {424 // We allow a scheduled call if any is true:425 // - It's priority is `HARD_DEADLINE`426 // - It does not push the weight past the limit.427 // - It is the first item in the schedule428 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {429430 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(431 s.origin.clone()432 ).into();433 let sender = match ensure_signed(origin) {434 Ok(v) => v,435 // TODO: Support for unsigned extrinsics?436 Err(_) => return Some(Some(s))437 };438 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);439 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));440 let r = s.call.clone().dispatch(sponsor.into());441 let maybe_id = s.maybe_id.clone();442 if let Some((period, count)) = s.maybe_periodic {443 if count > 1 {444 s.maybe_periodic = Some((period, count - 1));445 } else {446 s.maybe_periodic = None;447 }448 let next = now + period;449 // If scheduled is named, place it's information in `Lookup`450 if let Some(ref id) = s.maybe_id {451 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);452 Lookup::<T>::insert(id, (next, next_index as u32));453 }454 Agenda::<T>::append(next, Some(s));455 } else if let Some(ref id) = s.maybe_id {456 Lookup::<T>::remove(id);457 }458 Self::deposit_event(RawEvent::Dispatched(459 (now, index),460 maybe_id,461 r.map(|_| ()).map_err(|e| e.error)462 ));463 total_weight = cumulative_weight;464 None465 } else {466 Some(Some(s))467 }468 })469 .for_each(|unused| {470 let next = now + One::one();471 Agenda::<T>::append(next, unused);472 });473474 total_weight475 }550 }551 Ok(())476 }552 }477}478553554 /// Helper to migrate scheduler when the pallet origin type has changed.479impl<T: Config> Module<T> {555 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {556 Agenda::<T>::translate::<557 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,558 _,559 >(|_, agenda| {560 Some(561 agenda562 .into_iter()563 .map(|schedule| {564 schedule.map(|schedule| Scheduled {565 maybe_id: schedule.maybe_id,566 priority: schedule.priority,567 call: schedule.call,568 maybe_periodic: schedule.maybe_periodic,569 origin: schedule.origin.into(),570 _phantom: Default::default(),571 })572 })573 .collect::<Vec<_>>(),574 )575 });576 }577480 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {578 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {481 let now = frame_system::Pallet::<T>::block_number();579 let now = frame_system::Pallet::<T>::block_number();499 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,597 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500 priority: schedule::Priority,598 priority: schedule::Priority,501 origin: T::PalletsOrigin,599 origin: T::PalletsOrigin,502 call: <T as Config>::Call,600 call: CallOrHashOf<T>,503 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {601 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {504 let when = Self::resolve_time(when)?;602 let when = Self::resolve_time(when)?;603 call.ensure_requested::<T::PreimageProvider>();505604506 // sanitize maybe_periodic605 // sanitize maybe_periodic507 let maybe_periodic = maybe_periodic606 let maybe_periodic = maybe_periodic518 });617 });519 Agenda::<T>::append(when, s);618 Agenda::<T>::append(when, s);520 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;619 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;521 if index > T::MaxScheduledPerBlock::get() {620 Self::deposit_event(Event::Scheduled { when, index });522 log::warn!(523 target: "runtime::scheduler",524 "Warning: There are more items queued in the Scheduler than \525 expected from the runtime configuration. An update might be needed.",526 );527 }528 Self::deposit_event(RawEvent::Scheduled(when, index));529621530 Ok((when, index))622 Ok((when, index))531 }623 }539 Ok(None),631 Ok(None),540 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {632 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {541 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {633 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {542 if *o != s.origin {634 if matches!(635 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),636 Some(Ordering::Less) | None637 ) {543 return Err(BadOrigin.into());638 return Err(BadOrigin.into());544 }639 }545 };640 };548 )643 )549 })?;644 })?;550 if let Some(s) = scheduled {645 if let Some(s) = scheduled {646 s.call.ensure_unrequested::<T::PreimageProvider>();551 if let Some(id) = s.maybe_id {647 if let Some(id) = s.maybe_id {552 Lookup::<T>::remove(id);648 Lookup::<T>::remove(id);553 }649 }554 Self::deposit_event(RawEvent::Canceled(when, index));650 Self::deposit_event(Event::Canceled { when, index });555 Ok(())651 Ok(())556 } else {652 } else {557 Err(Error::<T>::NotFound.into())653 Err(Error::<T>::NotFound)?558 }654 }559 }655 }560656576 })?;672 })?;577673578 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;674 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;579 Self::deposit_event(RawEvent::Canceled(when, index));675 Self::deposit_event(Event::Canceled { when, index });580 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));676 Self::deposit_event(Event::Scheduled {677 when: new_time,678 index: new_index,679 });581680582 Ok((new_time, new_index))681 Ok((new_time, new_index))583 }682 }584683585 fn do_schedule_named(684 fn do_schedule_named(586 id: Vec<u8>,685 id: ScheduledId,587 when: DispatchTime<T::BlockNumber>,686 when: DispatchTime<T::BlockNumber>,588 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,687 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,589 priority: schedule::Priority,688 priority: schedule::Priority,590 origin: T::PalletsOrigin,689 origin: T::PalletsOrigin,591 call: <T as Config>::Call,690 call: CallOrHashOf<T>,592 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {691 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {593 // ensure id it is unique692 // ensure id it is unique594 if Lookup::<T>::contains_key(&id) {693 if Lookup::<T>::contains_key(&id) {595 return Err(Error::<T>::FailedToSchedule.into());694 return Err(Error::<T>::FailedToSchedule)?;596 }695 }597696598 let when = Self::resolve_time(when)?;697 let when = Self::resolve_time(when)?;599698699 call.ensure_requested::<T::PreimageProvider>();700600 // sanitize maybe_periodic701 // sanitize maybe_periodic601 let maybe_periodic = maybe_periodic702 let maybe_periodic = maybe_periodic602 .filter(|p| p.1 > 1 && !p.0.is_zero())703 .filter(|p| p.1 > 1 && !p.0.is_zero())606 let s = Scheduled {707 let s = Scheduled {607 maybe_id: Some(id.clone()),708 maybe_id: Some(id.clone()),608 priority,709 priority,609 call,710 call: call.clone(),610 maybe_periodic,711 maybe_periodic,611 origin,712 origin: origin.clone(),612 _phantom: Default::default(),713 _phantom: Default::default(),613 };714 };715716 // reserve balance for periodic execution717 // let sender =718 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;719 // let repeats = match maybe_periodic {720 // Some(p) => p.1,721 // None => 1,722 // };723 // let _ = T::CallExecutor::reserve_balance(724 // id.clone(),725 // sender,726 // call.as_value().unwrap().clone(),727 // repeats,728 // );729614 Agenda::<T>::append(when, Some(s));730 Agenda::<T>::append(when, Some(s));615 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;731 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;616 if index > T::MaxScheduledPerBlock::get() {617 log::warn!(618 target: "runtime::scheduler",619 "Warning: There are more items queued in the Scheduler than \620 expected from the runtime configuration. An update might be needed.",621 );622 }623 let address = (when, index);732 let address = (when, index);624 Lookup::<T>::insert(&id, &address);733 Lookup::<T>::insert(&id, &address);625 Self::deposit_event(RawEvent::Scheduled(when, index));734 Self::deposit_event(Event::Scheduled { when, index });626735627 Ok(address)736 Ok(address)628 }737 }629738630 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {739 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {631 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {740 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {632 if let Some((when, index)) = lookup.take() {741 if let Some((when, index)) = lookup.take() {633 let i = index as usize;742 let i = index as usize;634 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {743 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {635 if let Some(s) = agenda.get_mut(i) {744 if let Some(s) = agenda.get_mut(i) {636 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {745 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {637 if *o != s.origin {746 if matches!(747 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),748 Some(Ordering::Less) | None749 ) {638 return Err(BadOrigin.into());750 return Err(BadOrigin.into());639 }751 }752 // release balance reserve753 // let sender = ensure_signed(754 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(755 // origin.unwrap(),756 // )757 // .into(),758 // )?;759 // let _ = T::CallExecutor::cancel_reserve(id, sender);760761 s.call.ensure_unrequested::<T::PreimageProvider>();640 }762 }641 *s = None;763 *s = None;642 }764 }643 Ok(())765 Ok(())644 })?;766 })?;767645 Self::deposit_event(RawEvent::Canceled(when, index));768 Self::deposit_event(Event::Canceled { when, index });646 Ok(())769 Ok(())647 } else {770 } else {648 Err(Error::<T>::NotFound.into())771 Err(Error::<T>::NotFound)?649 }772 }650 })773 })651 }774 }652775653 fn do_reschedule_named(776 fn do_reschedule_named(654 id: Vec<u8>,777 id: ScheduledId,655 new_time: DispatchTime<T::BlockNumber>,778 new_time: DispatchTime<T::BlockNumber>,656 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {779 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {657 let new_time = Self::resolve_time(new_time)?;780 let new_time = Self::resolve_time(new_time)?;674 })?;797 })?;675798676 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;799 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;677 Self::deposit_event(RawEvent::Canceled(when, index));800 Self::deposit_event(Event::Canceled { when, index });678 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));801 Self::deposit_event(Event::Scheduled {802 when: new_time,803 index: new_index,804 });679805680 *lookup = Some((new_time, new_index));806 *lookup = Some((new_time, new_index));681807685 }811 }686}812}687813688#[cfg(test)]689#[allow(clippy::from_over_into)]814impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>690mod tests {815 for Pallet<T>816{691 use super::*;817 type Address = TaskAddress<T::BlockNumber>;818 type Hash = T::Hash;692819693 use frame_support::{820 fn schedule(694 ord_parameter_types, parameter_types,821 when: DispatchTime<T::BlockNumber>,695 traits::{Contains, ConstU32, EnsureOneOf},696 weights::constants::RocksDbWeight,822 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,697 };823 priority: schedule::Priority,698 use sp_core::H256;699 use sp_runtime::{824 origin: T::PalletsOrigin,700 Perbill,701 testing::Header,825 call: CallOrHashOf<T>,702 traits::{BlakeTwo256, IdentityLookup},826 ) -> Result<Self::Address, DispatchError> {703 };827 Self::do_schedule(when, maybe_periodic, priority, origin, call)704 use frame_system::{EnsureRoot, EnsureSignedBy};828 }705 use crate as scheduler;706829707 #[frame_support::pallet]830 fn cancel((when, index): Self::Address) -> Result<(), ()> {708 pub mod logger {709 use super::{OriginCaller, OriginTrait};831 Self::do_cancel(None, (when, index)).map_err(|_| ())710 use frame_support::pallet_prelude::*;711 use frame_system::pallet_prelude::*;712 use std::cell::RefCell;832 }713833714 thread_local! {834 fn reschedule(715 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());835 address: Self::Address,716 }836 when: DispatchTime<T::BlockNumber>,717 pub fn log() -> Vec<(OriginCaller, u32)> {837 ) -> Result<Self::Address, DispatchError> {718 LOG.with(|log| log.borrow().clone())838 Self::do_reschedule(address, when)719 }839 }720840721 #[pallet::pallet]841 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {722 #[pallet::generate_store(pub(super) trait Store)]723 pub struct Pallet<T>(PhantomData<T>);724725 #[pallet::hooks]726 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}727728 #[pallet::config]729 pub trait Config: frame_system::Config {730 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;731 }732733 #[pallet::event]734 #[pallet::generate_deposit(pub(super) fn deposit_event)]735 pub enum Event<T: Config> {736 Logged(u32, Weight),737 }738739 #[pallet::call]740 impl<T: Config> Pallet<T>741 where742 <T as frame_system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>,743 {744 #[pallet::weight(*weight)]842 Agenda::<T>::get(when)745 pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {746 Self::deposit_event(Event::Logged(i, weight));747 LOG.with(|log| {843 .get(index as usize)748 log.borrow_mut().push((origin.caller().clone(), i));749 });844 .ok_or(())750 Ok(())751 }845 .map(|_| when)752753 #[pallet::weight(*weight)]754 pub fn log_without_filter(755 origin: OriginFor<T>,756 i: u32,757 weight: Weight,758 ) -> DispatchResult {759 Self::deposit_event(Event::Logged(i, weight));760 LOG.with(|log| {761 log.borrow_mut().push((origin.caller().clone(), i));762 });763 Ok(())764 }765 }766 }846 }847}767848768 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;849impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>850 for Pallet<T>851{769 type Block = frame_system::mocking::MockBlock<Test>;852 type Address = TaskAddress<T::BlockNumber>;853 type Hash = T::Hash;770854771 frame_support::construct_runtime!(855 fn schedule_named(772 pub enum Test where856 id: Vec<u8>,773 Block = Block,774 NodeBlock = Block,857 when: DispatchTime<T::BlockNumber>,775 UncheckedExtrinsic = UncheckedExtrinsic,858 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,776 {777 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},778 Logger: logger::{Pallet, Call, Event<T>},859 priority: schedule::Priority,779 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},860 origin: T::PalletsOrigin,861 call: CallOrHashOf<T>,780 }862 ) -> Result<Self::Address, ()> {781 );782783 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.784 pub struct BaseFilter;863 let inner_id: ScheduledId = id785 impl Contains<Call> for BaseFilter {786 fn contains(call: &Call) -> bool {864 .try_into()787 !matches!(call, Call::Logger(logger::Call::log { .. }))865 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);866 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)788 }867 .map_err(|_| ())789 }868 }790869791 parameter_types! {870 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {792 pub const BlockHashCount: u64 = 250;871 let inner_id: ScheduledId = id793 pub BlockWeights: frame_system::limits::BlockWeights =872 .try_into()873 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);794 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);874 Self::do_cancel_named(None, inner_id).map_err(|_| ())795 }875 }796 impl system::Config for Test {876797 type BaseCallFilter = BaseFilter;877 fn reschedule_named(798 type BlockWeights = ();799 type BlockLength = ();878 id: Vec<u8>,800 type DbWeight = RocksDbWeight;879 when: DispatchTime<T::BlockNumber>,801 type Origin = Origin;802 type Call = Call;803 type Index = u64;804 type BlockNumber = u64;805 type Hash = H256;880 ) -> Result<Self::Address, DispatchError> {806 type Hashing = BlakeTwo256;807 type AccountId = u64;808 type Lookup = IdentityLookup<Self::AccountId>;809 type Header = Header;810 type Event = Event;881 let inner_id: ScheduledId = id811 type BlockHashCount = BlockHashCount;812 type Version = ();882 .try_into()813 type PalletInfo = PalletInfo;814 type AccountData = ();815 type OnNewAccount = ();883 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);816 type OnKilledAccount = ();817 type SystemWeightInfo = ();818 type SS58Prefix = ();884 Self::do_reschedule_named(inner_id, when)819 type OnSetCode = ();820 type MaxConsumers = ConstU32<16>;821 }822 impl logger::Config for Test {823 type Event = Event;824 }825 parameter_types! {826 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;827 pub const MaxScheduledPerBlock: u32 = 10;828 }829 ord_parameter_types! {830 pub const One: u64 = 1;831 }885 }832886833 impl Config for Test {887 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {834 type Event = Event;835 type Origin = Origin;888 let inner_id: ScheduledId = id836 type PalletsOrigin = OriginCaller;837 type Call = Call;889 .try_into()838 type MaximumWeight = MaximumSchedulerWeight;890 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);839 type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;891 Lookup::<T>::get(inner_id)840 type MaxScheduledPerBlock = MaxScheduledPerBlock;892 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))841 type WeightInfo = ();842 type SponsorshipHandler = ();893 .ok_or(())843 }894 }844}895}845896pallets/scheduler/src/weights.rsdiffbeforeafterboth--- a/pallets/scheduler/src/weights.rs
+++ b/pallets/scheduler/src/weights.rs
@@ -1,23 +1,6 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license
// This file is part of Substrate.
-// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
+// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,13 +15,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! Weights for pallet_scheduler
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0
-//! DATE: 2020-10-27, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: [], HIGH RANGE: []
-//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
+//! Autogenerated weights for pallet_scheduler
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
-// target/release/substrate
+// ./target/production/substrate
// benchmark
// --chain=dev
// --steps=50
@@ -49,78 +33,332 @@
// --wasm-execution=compiled
// --heap-pages=4096
// --output=./frame/scheduler/src/weights.rs
-// --template=./.maintain/frame-weight-template.hbs
+// --template=.maintain/frame-weight-template.hbs
+// --header=HEADER-APACHE2
+// --raw
+#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
-use frame_support::{
- traits::Get,
- weights::{Weight, constants::RocksDbWeight},
-};
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use sp_std::marker::PhantomData;
/// Weight functions needed for pallet_scheduler.
pub trait WeightInfo {
- fn schedule(s: u32) -> Weight;
- fn cancel(s: u32) -> Weight;
- fn schedule_named(s: u32) -> Weight;
- fn cancel_named(s: u32) -> Weight;
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
+ fn on_initialize_named_resolved(s: u32, ) -> Weight;
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
+ fn on_initialize_resolved(s: u32, ) -> Weight;
+ fn on_initialize_named_aborted(s: u32, ) -> Weight;
+ fn on_initialize_aborted(s: u32, ) -> Weight;
+ fn on_initialize_periodic_named(s: u32, ) -> Weight;
+ fn on_initialize_periodic(s: u32, ) -> Weight;
+ fn on_initialize_named(s: u32, ) -> Weight;
+ fn on_initialize(s: u32, ) -> Weight;
+ fn schedule(s: u32, ) -> Weight;
+ fn cancel(s: u32, ) -> Weight;
+ fn schedule_named(s: u32, ) -> Weight;
+ fn cancel_named(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> {
- fn schedule(s: u32) -> Weight {
- 35_029_000_u64
- .saturating_add(77_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(1_u64))
- .saturating_add(T::DbWeight::get().writes(1_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+ (11_587_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_resolved(s: u32, ) -> Weight {
+ (8_965_000 as Weight)
+ // Standard Error: 11_000
+ .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn cancel(s: u32) -> Weight {
- 31_419_000_u64
- .saturating_add(4_015_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(1_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+ (8_654_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_resolved(s: u32, ) -> Weight {
+ (9_303_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_aborted(s: u32, ) -> Weight {
+ (7_506_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ fn on_initialize_aborted(s: u32, ) -> Weight {
+ (8_046_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named(s: u32, ) -> Weight {
+ (13_704_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ fn on_initialize_periodic(s: u32, ) -> Weight {
+ (12_668_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named(s: u32, ) -> Weight {
+ (13_946_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn on_initialize(s: u32, ) -> Weight {
+ (13_151_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ (14_040_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ (14_376_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
- fn schedule_named(s: u32) -> Weight {
- 44_752_000_u64
- .saturating_add(123_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(2_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ (16_806_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
- fn cancel_named(s: u32) -> Weight {
- 35_712_000_u64
- .saturating_add(4_008_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(2_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ (15_852_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
- fn schedule(s: u32) -> Weight {
- 35_029_000_u64
- .saturating_add(77_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(1_u64))
- .saturating_add(RocksDbWeight::get().writes(1_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+ (11_587_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_resolved(s: u32, ) -> Weight {
+ (8_965_000 as Weight)
+ // Standard Error: 11_000
+ .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn cancel(s: u32) -> Weight {
- 31_419_000_u64
- .saturating_add(4_015_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(1_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+ (8_654_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn schedule_named(s: u32) -> Weight {
- 44_752_000_u64
- .saturating_add(123_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(2_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_resolved(s: u32, ) -> Weight {
+ (9_303_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
}
- fn cancel_named(s: u32) -> Weight {
- 35_712_000_u64
- .saturating_add(4_008_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(2_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_aborted(s: u32, ) -> Weight {
+ (7_506_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ fn on_initialize_aborted(s: u32, ) -> Weight {
+ (8_046_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named(s: u32, ) -> Weight {
+ (13_704_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ fn on_initialize_periodic(s: u32, ) -> Weight {
+ (12_668_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named(s: u32, ) -> Weight {
+ (13_946_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn on_initialize(s: u32, ) -> Weight {
+ (13_151_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ (14_040_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ (14_376_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ (16_806_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ (15_852_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -28,6 +28,8 @@
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};
use sp_runtime::DispatchError;
+use fp_self_contained::*;
+use sp_runtime::traits::{Member};
// #[cfg(any(feature = "std", test))]
// pub use sp_runtime::BuildStorage;
@@ -59,7 +61,7 @@
traits::{
tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
- OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+ OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -67,8 +69,13 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,
},
};
-use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
-use up_data_structs::*;
+use pallet_unq_scheduler::DispatchCall;
+use up_data_structs::{
+ CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+ CollectionStats, RpcCollection,
+ mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},
+};
+
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
use frame_system::{
@@ -79,12 +86,17 @@
traits::{BaseArithmetic, Unsigned},
};
use smallvec::smallvec;
+// use scale_info::TypeInfo;
use codec::{Encode, Decode};
use fp_rpc::TransactionStatus;
use sp_runtime::{
- traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf, Saturating},
+ traits::{
+ Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf,
+ Saturating, CheckedConversion,
+ },
+ generic::Era,
transaction_validity::TransactionValidityError,
- SaturatedConversion,
+ DispatchErrorWithPostInfo, SaturatedConversion,
};
// pub use pallet_timestamp::Call as TimestampCall;
@@ -102,7 +114,7 @@
ParentIsPreset,
};
use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
+use sp_std::{cmp::Ordering, marker::PhantomData};
use xcm::latest::{
// Xcm,
@@ -113,7 +125,6 @@
};
use xcm_executor::traits::{MatchesFungible, WeightTrader};
//use xcm_executor::traits::MatchesFungible;
-use sp_runtime::traits::CheckedConversion;
use unique_runtime_common::{
impl_common_runtime_apis,
@@ -406,12 +417,13 @@
// pub const ExistentialDeposit: u128 = 500;
pub const ExistentialDeposit: u128 = 0;
pub const MaxLocks: u32 = 50;
+ pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
- type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type MaxReserves = MaxReserves;
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -930,33 +942,156 @@
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
-// parameter_types! {
-// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// RuntimeBlockWeights::get().max_block;
-// pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+ RuntimeBlockWeights::get().max_block;
+ pub const MaxScheduledPerBlock: u32 = 50;
+}
+
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+ (
+ frame_system::CheckSpecVersion::<Runtime>::new(),
+ frame_system::CheckGenesis::<Runtime>::new(),
+ frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+ frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+ from,
+ )),
+ frame_system::CheckWeight::<Runtime>::new(),
+ // sponsoring transaction logic
+ // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+ )
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_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_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ fn dispatch_call(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let dispatch_info = call.get_dispatch_info();
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtraScheduler,
+ SelfContainedSignedInfo,
+ > {
+ signed:
+ CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
+ function: call.into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)
+ }
+
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+ .saturating_mul(count.into());
+
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ weight,
+ )
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<u128, DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::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,
+ ),
+ )
+ }
+}
+
+parameter_types! {
+ pub const NoPreimagePostponement: Option<u32> = Some(10);
+ pub const Preimage: Option<u32> = Some(10);
+}
+
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+ fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+ Some(Ordering::Equal)
+ }
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+ type Event = Event;
+ type Origin = Origin;
+ type Currency = Balances;
+ type PalletsOrigin = OriginCaller;
+ type Call = Call;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSigned<AccountId>;
+ type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type WeightInfo = ();
+ type CallExecutor = SchedulerPaymentExecutor;
+ type OriginPrivilegeCmp = OriginPrivilegeCmp;
+ type PreimageProvider = ();
+ type NoPreimagePostponement = NoPreimagePostponement;
+}
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
);
+
type SponsorshipHandler = (
UniqueSponsorshipHandler<Runtime>,
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-
-// impl pallet_unq_scheduler::Config for Runtime {
-// type Event = Event;
-// type Origin = Origin;
-// type PalletsOrigin = OriginCaller;
-// type Call = Call;
-// type MaximumWeight = MaximumSchedulerWeight;
-// type ScheduleOrigin = EnsureSigned<AccountId>;
-// type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// type SponsorshipHandler = SponsorshipHandler;
-// type WeightInfo = ();
-// }
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -1020,7 +1155,7 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1087,10 +1222,17 @@
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
- pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+ ChargeTransactionPayment,
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
+pub type SignedExtraScheduler = (
+ frame_system::CheckSpecVersion<Runtime>,
+ frame_system::CheckGenesis<Runtime>,
+ frame_system::CheckEra<Runtime>,
+ frame_system::CheckNonce<Runtime>,
+ frame_system::CheckWeight<Runtime>,
+);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -33,7 +33,7 @@
use sp_runtime::{
Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
- traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
+ traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero, Member},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, RuntimeAppPublic,
};
@@ -58,7 +58,7 @@
traits::{
tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
- OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+ OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -81,18 +81,28 @@
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};
use fp_rpc::TransactionStatus;
use sp_runtime::{
- traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
+ traits::{
+ Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+ CheckedConversion,
+ },
+ generic::Era,
transaction_validity::TransactionValidityError,
- SaturatedConversion,
+ SaturatedConversion, DispatchErrorWithPostInfo,
};
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+
// pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
// Polkadot imports
use pallet_xcm::XcmPassthrough;
use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+ CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+ CollectionStats, RpcCollection,
+ mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
use xcm_builder::{
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -102,7 +112,8 @@
ParentIsPreset,
};
use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
use xcm::latest::{
// Xcm,
@@ -112,8 +123,6 @@
Error as XcmError,
};
use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
-use sp_runtime::traits::CheckedConversion;
use unique_runtime_common::{
impl_common_runtime_apis,
@@ -390,7 +399,7 @@
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -913,11 +922,11 @@
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
-// parameter_types! {
-// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// RuntimeBlockWeights::get().max_block;
-// pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+ RuntimeBlockWeights::get().max_block;
+ pub const MaxScheduledPerBlock: u32 = 50;
+}
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
@@ -929,17 +938,34 @@
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-// impl pallet_unq_scheduler::Config for Runtime {
-// type Event = Event;
-// type Origin = Origin;
-// type PalletsOrigin = OriginCaller;
-// type Call = Call;
-// type MaximumWeight = MaximumSchedulerWeight;
-// type ScheduleOrigin = EnsureSigned<AccountId>;
-// type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// type SponsorshipHandler = SponsorshipHandler;
-// type WeightInfo = ();
-// }
+parameter_types! {
+ pub const NoPreimagePostponement: Option<u32> = Some(10);
+ pub const Preimage: Option<u32> = Some(10);
+}
+
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+ fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+ Some(Ordering::Equal)
+ }
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+ type Event = Event;
+ type Origin = Origin;
+ type Currency = Balances;
+ type PalletsOrigin = OriginCaller;
+ type Call = Call;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSigned<AccountId>;
+ type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type WeightInfo = ();
+ type CallExecutor = SchedulerPaymentExecutor;
+ type OriginPrivilegeCmp = OriginPrivilegeCmp;
+ type PreimageProvider = ();
+ type NoPreimagePostponement = NoPreimagePostponement;
+}
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -954,6 +980,110 @@
// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
// }
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+ (
+ frame_system::CheckSpecVersion::<Runtime>::new(),
+ frame_system::CheckGenesis::<Runtime>::new(),
+ frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+ frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+ from,
+ )),
+ frame_system::CheckWeight::<Runtime>::new(),
+ // sponsoring transaction logic
+ // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+ )
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_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_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ fn dispatch_call(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let dispatch_info = call.get_dispatch_info();
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtraScheduler,
+ SelfContainedSignedInfo,
+ > {
+ signed:
+ CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
+ function: call.into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)
+ }
+
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+ .saturating_mul(count.into());
+
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ )
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<u128, DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ ),
+ )
+ }
+
+ 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,
+ ),
+ )
+ }
+}
+
parameter_types! {
// 0x842899ECF380553E8a4de75bF534cdf6fBF64049
pub const HelpersContractAddress: H160 = H160([
@@ -1003,7 +1133,7 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1073,6 +1203,15 @@
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
+
+pub type SignedExtraScheduler = (
+ frame_system::CheckSpecVersion<Runtime>,
+ frame_system::CheckGenesis<Runtime>,
+ frame_system::CheckEra<Runtime>,
+ frame_system::CheckNonce<Runtime>,
+ frame_system::CheckWeight<Runtime>,
+ // pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -33,11 +33,20 @@
use sp_runtime::{
Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
- traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
- transaction_validity::{TransactionSource, TransactionValidity},
- ApplyExtrinsicResult, RuntimeAppPublic,
+ generic::Era,
+ traits::{
+ Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+ CheckedConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion,
+ Zero, Member,
+ },
+ transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
+ ApplyExtrinsicResult, RuntimeAppPublic, SaturatedConversion, DispatchErrorWithPostInfo,
};
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
+
use sp_std::prelude::*;
#[cfg(feature = "std")]
@@ -59,7 +68,7 @@
traits::{
tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
- OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+ OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -86,18 +95,17 @@
use smallvec::smallvec;
use codec::{Encode, Decode};
use fp_rpc::TransactionStatus;
-use sp_runtime::{
- traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
- transaction_validity::TransactionValidityError,
- SaturatedConversion,
-};
// pub use pallet_timestamp::Call as TimestampCall;
// Polkadot imports
use pallet_xcm::XcmPassthrough;
use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+ CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+ CollectionStats, RpcCollection,
+ mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
use xcm_builder::{
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -107,7 +115,6 @@
ParentIsPreset,
};
use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
use xcm::latest::{
// Xcm,
@@ -117,7 +124,6 @@
Error as XcmError,
};
use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
use sp_runtime::traits::CheckedConversion;
use unique_runtime_common::{
@@ -395,7 +401,7 @@
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -918,12 +924,145 @@
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
-// parameter_types! {
-// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// RuntimeBlockWeights::get().max_block;
-// pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+ RuntimeBlockWeights::get().max_block;
+ pub const MaxScheduledPerBlock: u32 = 50;
+}
+
+parameter_types! {
+ pub const NoPreimagePostponement: Option<u32> = Some(10);
+ pub const Preimage: Option<u32> = Some(10);
+}
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+ fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+ Some(Ordering::Equal)
+ }
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+ type Event = Event;
+ type Origin = Origin;
+ type Currency = Balances;
+ type PalletsOrigin = OriginCaller;
+ type Call = Call;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSigned<AccountId>;
+ type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type WeightInfo = ();
+ type CallExecutor = SchedulerPaymentExecutor;
+ type OriginPrivilegeCmp = OriginPrivilegeCmp;
+ type PreimageProvider = ();
+ type NoPreimagePostponement = NoPreimagePostponement;
+}
+
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+ (
+ frame_system::CheckSpecVersion::<Runtime>::new(),
+ frame_system::CheckGenesis::<Runtime>::new(),
+ frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+ frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+ from,
+ )),
+ frame_system::CheckWeight::<Runtime>::new(),
+ // sponsoring transaction logic
+ // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+ )
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_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_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ fn dispatch_call(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let dispatch_info = call.get_dispatch_info();
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtraScheduler,
+ SelfContainedSignedInfo,
+ > {
+ signed:
+ CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
+ function: call.into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)
+ }
+
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+ .saturating_mul(count.into());
+
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ )
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<u128, DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ ),
+ )
+ }
+
+ 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,
+ ),
+ )
+ }
+}
+
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
@@ -933,18 +1072,6 @@
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-
-// impl pallet_unq_scheduler::Config for Runtime {
-// type Event = Event;
-// type Origin = Origin;
-// type PalletsOrigin = OriginCaller;
-// type Call = Call;
-// type MaximumWeight = MaximumSchedulerWeight;
-// type ScheduleOrigin = EnsureSigned<AccountId>;
-// type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// type SponsorshipHandler = SponsorshipHandler;
-// type WeightInfo = ();
-// }
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -1008,7 +1135,7 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1078,6 +1205,14 @@
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
+pub type SignedExtraScheduler = (
+ frame_system::CheckSpecVersion<Runtime>,
+ frame_system::CheckGenesis<Runtime>,
+ frame_system::CheckEra<Runtime>,
+ frame_system::CheckNonce<Runtime>,
+ frame_system::CheckWeight<Runtime>,
+ // pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -68,6 +68,8 @@
"testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
"testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
"testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
+ "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
+ "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
"testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/scheduling.test.ts
@@ -0,0 +1,55 @@
+// 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/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
+import {scheduleExpectSuccess, waitNewBlocks} from '../util/helpers';
+import privateKey from '../substrate/privateKey';
+
+describe('Scheduing EVM smart contracts', () => {
+ itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3}) => {
+ const deployer = await createEthAccountWithBalance(api, web3);
+ const flipper = await deployFlipper(web3, deployer);
+ const initialValue = await flipper.methods.getValue().call();
+ const alice = privateKey('//Alice');
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+ {
+ const tx = api.tx.evm.call(
+ subToEth(alice.address),
+ flipper.options.address,
+ flipper.methods.flip().encodeABI(),
+ '0',
+ GAS_ARGS.gas,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const waitForBlocks = 4;
+ const periodBlocks = 2;
+
+ await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+
+ await waitNewBlocks(waitForBlocks - 1);
+ expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+
+ await waitNewBlocks(periodBlocks);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+ }
+ });
+});
\ No newline at end of file
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -50,7 +50,7 @@
'unique',
'nonfungible',
'refungible',
- //'scheduler',
+ 'scheduler',
'charging',
];
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -14,32 +14,197 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import chai from 'chai';
+import chai, {expect} from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
import {
+ default as usingApi,
+ submitTransactionAsync,
+} from './substrate/substrate-api';
+import {
createItemExpectSuccess,
createCollectionExpectSuccess,
scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
+ scheduleExpectFailure,
} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
chai.use(chaiAsPromised);
-describe.skip('Integration Test scheduler base transaction', () => {
- it('User can transfer owned token with delay (scheduler)', async () => {
+describe.skip('Scheduling token and balance transfers', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let scheduledIdBase: string;
+ let scheduledIdSlider: number;
+
+ before(async() => {
await usingApi(async () => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- // nft
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+
+ scheduledIdBase = '0x' + '0'.repeat(31);
+ scheduledIdSlider = 0;
+ });
+
+ // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+ function makeScheduledId(): string {
+ return scheduledIdBase + ((scheduledIdSlider++) % 10);
+ }
+
+ it('Can schedule a transfer of an owned token with delay', async () => {
+ await usingApi(async () => {
const nftCollectionId = await createCollectionExpectSuccess();
const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async () => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+ const bobsBalanceBefore = await getFreeBalance(bob);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getFreeBalance(bob);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getFreeBalance(bob);
+ expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+ });
+ });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async () => {
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+ const waitForBlocks = 4;
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+ const bobBalanceAfter = await getFreeBalance(bob);
+ // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+ // wait for sequentiality matters
+ await waitNewBlocks(waitForBlocks - 1);
+ });
+ });
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Grace zeroBalance with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+ const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+ expect(getGenericResult(events).success).to.be.true;
+ /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;*/
+
+ // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
+
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+
+ it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+
+ const createData = {nft: {const_data: [], variable_data: []}};
+ const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+
+ /*const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
+
+ await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
+
+ expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -630,10 +630,16 @@
}
export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async () => {
+ const sender = privateKey(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
await usingApi(async (api) => {
// Run the transaction
- const sender = privateKey(senderSeed);
const tx = api.tx.unique.confirmSponsorship(collectionId);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -899,7 +905,7 @@
}
/* eslint no-async-promise-executor: "off" */
-async function getBlockNumber(api: ApiPromise): Promise<number> {
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
return new Promise<number>(async (resolve) => {
const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
unsubscribe();
@@ -935,29 +941,76 @@
}
export async function
-scheduleTransferExpectSuccess(
- collectionId: number,
- tokenId: number,
+scheduleExpectSuccess(
+ operationTx: any,
sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
) {
await usingApi(async (api: ApiPromise) => {
const blockNumber: number | undefined = await getBlockNumber(api);
const expectedBlockNumber = blockNumber + blockSchedule;
expect(blockNumber).to.be.greaterThan(0);
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
- const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions > 1 ? [period, repetitions] : null,
+ 0,
+ {value: operationTx as any},
+ );
+
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function
+scheduleExpectFailure(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions <= 1 ? null : [period, repetitions],
+ 0,
+ {value: operationTx as any},
+ );
+
+ //const events =
+ await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
+ //expect(getGenericResult(events).success).to.be.false;
+ });
+}
- await submitTransactionAsync(sender, scheduleTx);
+export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
-
- // sleep for 4 blocks
+ // sleep for n + 1 blocks
await waitNewBlocks(blockSchedule + 1);
const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
@@ -967,6 +1020,45 @@
});
}
+export async function
+scheduleTransferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
+
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+
+ const balanceBefore = await getFreeBalance(recipient);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
+
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
+ });
+}
export async function
transferExpectSuccess(