difftreelog
feat(Scheduler) most critical improvements done, polishing needed
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6108,7 +6108,7 @@
[[package]]
name = "pallet-template-transaction-payment"
version = "3.0.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"frame-benchmarking",
"frame-support",
@@ -6272,7 +6272,6 @@
"parity-scale-codec",
"scale-info",
"serde",
- "sp-api",
"sp-core",
"sp-io",
"sp-runtime",
@@ -11313,7 +11312,7 @@
"chrono",
"lazy_static",
"matchers",
- "parking_lot 0.11.2",
+ "parking_lot 0.10.2",
"regex",
"serde",
"serde_json",
@@ -11443,7 +11442,7 @@
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ee73e6e4924fe940354b8d4d98cad5231175d615cd855b758adc658c0aac6a0"
dependencies = [
- "cfg-if 1.0.0",
+ "cfg-if 0.1.10",
"rand 0.8.4",
"static_assertions",
]
@@ -11812,7 +11811,7 @@
[[package]]
name = "up-sponsorship"
version = "0.1.0"
-source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#858001a6fd841614eb3bc47562e1a08685e6c8df"
+source = "git+https://github.com/UniqueNetwork/pallet-sponsoring?branch=polkadot-v0.9.14#0f6291079a781cb9f8815efd5113a6a61059ce97"
dependencies = [
"impl-trait-for-tuples",
]
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -20,11 +20,11 @@
sp-io = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
frame-benchmarking = { default-features = false, optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/UniqueNetwork/pallet-sponsoring", branch = 'polkadot-v0.9.14' }
log = { version = "0.4.14", default-features = false }
[dev-dependencies]
-sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
substrate-test-utils = { git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.14' }
[features]
@@ -38,6 +38,7 @@
"up-sponsorship/std",
"sp-io/std",
"sp-std/std",
+ "sp-core/std",
"log/std",
]
runtime-benchmarks = [
pallets/scheduler/src/lib.rsdiffbeforeafterboth1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//! specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//! index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//! `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63};64use frame_support::{65 decl_module, decl_storage, decl_event, decl_error,66 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67 traits::{68 Get,69 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,71 },72 weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use scale_info::TypeInfo;77use sp_runtime::ApplyExtrinsicResult;78use sp_runtime::traits::{IdentifyAccount, Verify};79use sp_runtime::{MultiSignature};8081pub trait ApplyExtrinsic<C: Dispatchable> {82 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;83}8485/// The address format for describing accounts.86pub type Signature = MultiSignature;87pub type Address = sp_runtime::MultiAddress<AccountId, ()>;88pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;8990/// Our pallet's configuration trait. All our types and constants go in here. If the91/// pallet is dependent on specific other pallets, then their configuration traits92/// should be added to our implied traits list.93///94/// `system::Config` should always be included in our implied traits.95/// //96pub trait Config: system::Config {97 /// The overarching event type.98 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;99100 /// The aggregated origin which the dispatch will take.101 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>102 + From<Self::PalletsOrigin>103 + IsType<<Self as system::Config>::Origin>;104105 /// The caller origin, overarching type of all pallets origins.106 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;107108 /// The aggregated call type.109 type Call: Parameter110 + Dispatchable<Origin = <Self as Config>::Origin>111 + GetDispatchInfo112 + From<system::Call<Self>>;113114 /// The maximum weight that may be scheduled per block for any dispatchables of less priority115 /// than `schedule::HARD_DEADLINE`.116 type MaximumWeight: Get<Weight>;117118 /// Required origin to schedule or cancel calls.119 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;120121 /// The maximum number of scheduled calls in the queue for a single block.122 /// Not strictly enforced, but used for weight estimation.123 type MaxScheduledPerBlock: Get<u32>;124125 /// Weight information for extrinsics in this pallet.126 type WeightInfo: WeightInfo;127128 type Executor: ApplyExtrinsic<<Self as Config>::Call>;129}130131pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;132133pub const PERIODIC_CALLS_LIMIT: u32 = 100;134135// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;136137/// Just a simple index for naming period tasks.138pub type PeriodicIndex = u32;139/// The location of a scheduled task that can be used to remove it.140pub type TaskAddress<BlockNumber> = (BlockNumber, u32);141142#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]143#[derive(Clone, RuntimeDebug, Encode, Decode)]144struct ScheduledV1<Call, BlockNumber> {145 maybe_id: Option<Vec<u8>>,146 priority: schedule::Priority,147 call: Call,148 maybe_periodic: Option<schedule::Period<BlockNumber>>,149}150151/// Information regarding an item to be executed in the future.152#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]153#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]154pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {155 /// The unique identity for this task, if there is one.156 maybe_id: Option<Vec<u8>>,157 /// This task's priority.158 priority: schedule::Priority,159 /// The call to be dispatched.160 call: Call,161 /// If the call is periodic, then this points to the information concerning that.162 maybe_periodic: Option<schedule::Period<BlockNumber>>,163 /// The origin to dispatch the call.164 origin: PalletsOrigin,165 _phantom: PhantomData<AccountId>,166}167168/// The current version of Scheduled struct.169pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =170 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;171172// A value placed in storage that represents the current version of the Scheduler storage.173// This value is used by the `on_runtime_upgrade` logic to determine whether we run174// storage migration logic.175#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]176enum Releases {177 V1,178 V2,179}180181impl Default for Releases {182 fn default() -> Self {183 Releases::V1184 }185}186187#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]188pub struct CallSpec {189 module: u32,190 method: u32,191}192193decl_storage! {194 trait Store for Module<T: Config> as Scheduler {195 /// Items to be executed, indexed by the block number that they should be executed on.196 pub Agenda: map hasher(twox_64_concat) T::BlockNumber197 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;198199 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber200 => Vec<Option<CallSpec>>;201202 /// Lookup from identity to the block number and index of the task.203 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;204205 /// Storage version of the pallet.206 ///207 /// New networks start with last version.208 StorageVersion build(|_| Releases::V2): Releases;209 }210}211212decl_event!(213 pub enum Event<T> where <T as system::Config>::BlockNumber {214 /// Scheduled some task. \[when, index\]215 Scheduled(BlockNumber, u32),216 /// Canceled some task. \[when, index\]217 Canceled(BlockNumber, u32),218 /// Dispatched some task. \[task, id, result\]219 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),220 }221);222223decl_error! {224 pub enum Error for Module<T: Config> {225 /// Failed to schedule a call226 FailedToSchedule,227 /// Cannot find the scheduled call.228 NotFound,229 /// Given target block number is in the past.230 TargetBlockNumberInPast,231 /// Reschedule failed because it does not change scheduled time.232 RescheduleNoChange,233 }234}235236decl_module! {237 /// Scheduler module declaration.238 pub struct Module<T: Config> for enum Call239 where240 origin: <T as system::Config>::Origin241 {242 type Error = Error<T>;243 fn deposit_event() = default;244245 /// Anonymously schedule a task.246 ///247 /// # <weight>248 /// - S = Number of already scheduled calls249 /// - Base Weight: 22.29 + .126 * S µs250 /// - DB Weight:251 /// - Read: Agenda252 /// - Write: Agenda253 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls254 /// # </weight>255 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]256 fn schedule(origin,257 when: T::BlockNumber,258 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,259 priority: schedule::Priority,260 call: Box<<T as Config>::Call>,261 )262 {263 let origin = <T as Config>::Origin::from(origin);264 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;265 }266267 /// Cancel an anonymously scheduled task.268 ///269 /// # <weight>270 /// - S = Number of already scheduled calls271 /// - Base Weight: 22.15 + 2.869 * S µs272 /// - DB Weight:273 /// - Read: Agenda274 /// - Write: Agenda, Lookup275 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls276 /// # </weight>277 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]278 fn cancel(origin, when: T::BlockNumber, index: u32) {279 T::ScheduleOrigin::ensure_origin(origin.clone())?;280 let origin = <T as Config>::Origin::from(origin);281 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;282 }283284 /// Schedule a named task.285 ///286 /// # <weight>287 /// - S = Number of already scheduled calls288 /// - Base Weight: 29.6 + .159 * S µs289 /// - DB Weight:290 /// - Read: Agenda, Lookup291 /// - Write: Agenda, Lookup292 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls293 /// # </weight>294 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]295 fn schedule_named(origin,296 id: Vec<u8>,297 when: T::BlockNumber,298 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,299 priority: schedule::Priority,300 call: Box<<T as Config>::Call>,301 ) {302 T::ScheduleOrigin::ensure_origin(origin.clone())?;303 let origin = <T as Config>::Origin::from(origin);304 Self::do_schedule_named(305 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call306 )?;307 }308309 /// Cancel a named scheduled task.310 ///311 /// # <weight>312 /// - S = Number of already scheduled calls313 /// - Base Weight: 24.91 + 2.907 * S µs314 /// - DB Weight:315 /// - Read: Agenda, Lookup316 /// - Write: Agenda, Lookup317 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls318 /// # </weight>319 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]320 fn cancel_named(origin, id: Vec<u8>) {321 T::ScheduleOrigin::ensure_origin(origin.clone())?;322 let origin = <T as Config>::Origin::from(origin);323 Self::do_cancel_named(Some(origin.caller().clone()), id)?;324 }325326 /// Anonymously schedule a task after a delay.327 ///328 /// # <weight>329 /// Same as [`schedule`].330 /// # </weight>331 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]332 fn schedule_after(origin,333 after: T::BlockNumber,334 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,335 priority: schedule::Priority,336 call: Box<<T as Config>::Call>,337 ) {338 T::ScheduleOrigin::ensure_origin(origin.clone())?;339 let origin = <T as Config>::Origin::from(origin);340 Self::do_schedule_nameless(341 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call342 )?;343 }344345 /// Schedule a named task after a delay.346 ///347 /// # <weight>348 /// Same as [`schedule_named`].349 /// # </weight>350 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]351 fn schedule_named_after(origin,352 id: Vec<u8>,353 after: T::BlockNumber,354 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,355 priority: schedule::Priority,356 call: Box<<T as Config>::Call>,357 ) {358 T::ScheduleOrigin::ensure_origin(origin.clone())?;359 let origin = <T as Config>::Origin::from(origin);360 Self::do_schedule_named(361 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call362 )?;363 }364365 /// Execute the scheduled calls366 ///367 /// # <weight>368 /// - S = Number of already scheduled calls369 /// - N = Named scheduled calls370 /// - P = Periodic Calls371 /// - Base Weight: 9.243 + 23.45 * S µs372 /// - DB Weight:373 /// - Read: Agenda + Lookup * N + Agenda(Future) * P374 /// - Write: Agenda + Lookup * N + Agenda(future) * P375 /// # </weight>376 fn on_initialize(now: T::BlockNumber) -> Weight {377 let limit = T::MaximumWeight::get();378 let mut queued = Agenda::<T>::take(now)379 .into_iter()380 .enumerate()381 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))382 .collect::<Vec<_>>();383 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {384 log::warn!(385 target: "runtime::scheduler",386 "Warning: This block has more items queued in Scheduler than \387 expected from the runtime configuration. An update might be needed."388 );389 }390 queued.sort_by_key(|(_, s)| s.priority);391 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)392 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)393 queued.into_iter()394 .enumerate()395 .scan(base_weight, |cumulative_weight, (order, (index, s))| {396 *cumulative_weight = cumulative_weight397 .saturating_add(s.call.get_dispatch_info().weight);398399 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(400 s.origin.clone()401 ).into();402403 if ensure_signed(origin).is_ok() {404 // AccountData for inner call origin accountdata.405 *cumulative_weight = cumulative_weight406 .saturating_add(T::DbWeight::get().reads_writes(1, 1));407 }408409 if s.maybe_id.is_some() {410 // Remove/Modify Lookup411 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));412 }413 if s.maybe_periodic.is_some() {414 // Read/Write Agenda for future block415 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));416 }417418 Some((order, index, *cumulative_weight, s))419 })420 .filter_map(|(order, index, cumulative_weight, mut s)| {421 // We allow a scheduled call if any is true:422 // - It's priority is `HARD_DEADLINE`423 // - It does not push the weight past the limit.424 // - It is the first item in the schedule425 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {426427 // let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(428 // s.origin.clone()429 // ).into();430 // let sender = ensure_signed(origin).unwrap_or_default();431 // let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);432 // let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));433 // let r = s.call.clone().dispatch(sponsor.into());434 let maybe_id = s.maybe_id.clone();435 if let Some((period, count)) = s.maybe_periodic {436 if count > 1 {437 s.maybe_periodic = Some((period, count - 1));438 } else {439 s.maybe_periodic = None;440 }441 let next = now + period;442 // If scheduled is named, place it's information in `Lookup`443 if let Some(ref id) = s.maybe_id {444 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);445 Lookup::<T>::insert(id, (next, next_index as u32));446 }447 Agenda::<T>::append(next, Some(s));448 } else if let Some(ref id) = s.maybe_id {449 Lookup::<T>::remove(id);450 }451 Self::deposit_event(RawEvent::Dispatched(452 (now, index),453 maybe_id,454 Ok(())// r.map(|_| ()).map_err(|e| e.error)455 ));456 total_weight = cumulative_weight;457 None458 } else {459 Some(Some(s))460 }461 })462 .for_each(|unused| {463 let next = now + One::one();464 Agenda::<T>::append(next, unused);465 });466467 total_weight468 }469 }470}471472impl<T: Config> Module<T> {473 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {474 let now = frame_system::Pallet::<T>::block_number();475476 let when = match when {477 DispatchTime::At(x) => x,478 // The current block has already completed it's scheduled tasks, so479 // Schedule the task at lest one block after this current block.480 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),481 };482483 if when <= now {484 return Err(Error::<T>::TargetBlockNumberInPast.into());485 }486487 Ok(when)488 }489490 fn do_schedule(491 maybe_id: Option<Vec<u8>>,492 when: DispatchTime<T::BlockNumber>,493 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,494 priority: schedule::Priority,495 origin: T::PalletsOrigin,496 call: <T as Config>::Call,497 ) -> Result<(T::BlockNumber, u32), DispatchError> {498 let when = Self::resolve_time(when)?;499500 let sender = ensure_signed(501 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),502 )503 .unwrap_or_default();504 let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);505 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));506 let r = call.clone().dispatch(sponsor.into());507508 //T::PaymentHandler::apply();509 //T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch extrinsic here510511 // sanitize maybe_periodic512 let maybe_periodic = maybe_periodic513 .filter(|p| p.1 > 1 && !p.0.is_zero())514 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.515 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));516517 let s = Some(Scheduled {518 maybe_id,519 priority,520 call,521 maybe_periodic,522 origin,523 _phantom: PhantomData::<T::AccountId>::default(),524 });525 Agenda::<T>::append(when, s);526 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;527 if index > T::MaxScheduledPerBlock::get() {528 log::warn!(529 target: "runtime::scheduler",530 "Warning: There are more items queued in the Scheduler than \531 expected from the runtime configuration. An update might be needed.",532 );533 }534535 Ok((when, index))536 }537538 fn do_schedule_nameless(539 when: DispatchTime<T::BlockNumber>,540 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,541 priority: schedule::Priority,542 origin: T::PalletsOrigin,543 call: <T as Config>::Call,544 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {545 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;546 let (when, index) = address;547548 Self::deposit_event(RawEvent::Scheduled(when, index));549550 Ok(address)551 }552553 fn do_cancel(554 origin: Option<T::PalletsOrigin>,555 (when, index): TaskAddress<T::BlockNumber>,556 ) -> Result<(), DispatchError> {557 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {558 agenda.get_mut(index as usize).map_or(559 Ok(None),560 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {561 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {562 if *o != s.origin {563 return Err(BadOrigin.into());564 }565 };566 Ok(s.take())567 },568 )569 })?;570 if let Some(s) = scheduled {571 if let Some(id) = s.maybe_id {572 Lookup::<T>::remove(id);573 // todo add back money / displace to another function for consistency574 }575 Self::deposit_event(RawEvent::Canceled(when, index));576 Ok(())577 } else {578 Err(Error::<T>::NotFound.into())579 }580 }581582 fn do_reschedule(583 (when, index): TaskAddress<T::BlockNumber>,584 new_time: DispatchTime<T::BlockNumber>,585 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {586 let new_time = Self::resolve_time(new_time)?;587588 if new_time == when {589 return Err(Error::<T>::RescheduleNoChange.into());590 }591592 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {593 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;594 let task = task.take().ok_or(Error::<T>::NotFound)?;595 Agenda::<T>::append(new_time, Some(task));596 Ok(())597 })?;598599 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;600 Self::deposit_event(RawEvent::Canceled(when, index));601 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));602603 Ok((new_time, new_index))604 }605606 fn do_schedule_named(607 id: Vec<u8>,608 when: DispatchTime<T::BlockNumber>,609 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,610 priority: schedule::Priority,611 origin: T::PalletsOrigin,612 call: <T as Config>::Call,613 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {614 // ensure id length does not exceed expectations & is unique615 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()616 || Lookup::<T>::contains_key(&id)617 {618 return Err(Error::<T>::FailedToSchedule.into());619 }620621 let address = Self::do_schedule(622 Some(id.clone()),623 when,624 maybe_periodic,625 priority,626 origin,627 call,628 )?;629 let (when, index) = address;630631 Lookup::<T>::insert(&id, &address);632 Self::deposit_event(RawEvent::Scheduled(when, index));633 Ok(address)634 }635636 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {637 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {638 if let Some((when, index)) = lookup.take() {639 let i = index as usize;640 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {641 if let Some(s) = agenda.get_mut(i) {642 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {643 if *o != s.origin {644 return Err(BadOrigin.into());645 }646 }647 *s = None;648 }649 Ok(())650 })?;651 // todo add money back / displace to another function652 Self::deposit_event(RawEvent::Canceled(when, index));653 Ok(())654 } else {655 Err(Error::<T>::NotFound.into())656 }657 })658 }659660 fn do_reschedule_named(661 id: Vec<u8>,662 new_time: DispatchTime<T::BlockNumber>,663 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {664 let new_time = Self::resolve_time(new_time)?;665666 Lookup::<T>::try_mutate_exists(667 id,668 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {669 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;670671 if new_time == when {672 return Err(Error::<T>::RescheduleNoChange.into());673 }674675 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {676 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;677 let task = task.take().ok_or(Error::<T>::NotFound)?;678 Agenda::<T>::append(new_time, Some(task));679680 Ok(())681 })?;682683 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;684 Self::deposit_event(RawEvent::Canceled(when, index));685 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));686687 *lookup = Some((new_time, new_index));688689 Ok((new_time, new_index))690 },691 )692 }693}694695impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>696 for Module<T>697{698 type Address = TaskAddress<T::BlockNumber>;699700 fn schedule(701 when: DispatchTime<T::BlockNumber>,702 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,703 priority: schedule::Priority,704 origin: T::PalletsOrigin,705 call: <T as Config>::Call,706 ) -> Result<Self::Address, DispatchError> {707 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)708 }709710 fn cancel((when, index): Self::Address) -> Result<(), ()> {711 Self::do_cancel(None, (when, index)).map_err(|_| ())712 }713714 fn reschedule(715 address: Self::Address,716 when: DispatchTime<T::BlockNumber>,717 ) -> Result<Self::Address, DispatchError> {718 Self::do_reschedule(address, when)719 }720721 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {722 Agenda::<T>::get(when)723 .get(index as usize)724 .ok_or(())725 .map(|_| when)726 }727}728729impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>730 for Module<T>731{732 type Address = TaskAddress<T::BlockNumber>;733734 fn schedule_named(735 id: Vec<u8>,736 when: DispatchTime<T::BlockNumber>,737 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,738 priority: schedule::Priority,739 origin: T::PalletsOrigin,740 call: <T as Config>::Call,741 ) -> Result<Self::Address, ()> {742 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())743 }744745 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {746 Self::do_cancel_named(None, id).map_err(|_| ())747 }748749 fn reschedule_named(750 id: Vec<u8>,751 when: DispatchTime<T::BlockNumber>,752 ) -> Result<Self::Address, DispatchError> {753 Self::do_reschedule_named(id, when)754 }755756 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {757 Lookup::<T>::get(id)758 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))759 .ok_or(())760 }761}762763#[cfg(test)]764#[allow(clippy::from_over_into)]765mod tests {766 use super::*;767768 use frame_support::{769 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,770 };771 use sp_core::H256;772 use sp_runtime::{773 Perbill,774 testing::Header,775 traits::{BlakeTwo256, IdentityLookup},776 };777 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};778 use crate as scheduler;779780 mod logger {781 use super::*;782 use std::cell::RefCell;783784 thread_local! {785 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());786 }787 pub trait Config: system::Config {788 type Event: From<Event> + Into<<Self as system::Config>::Event>;789 }790 decl_event! {791 pub enum Event {792 Logged(u32, Weight),793 }794 }795 decl_module! {796 pub struct Module<T: Config> for enum Call797 where798 origin: <T as system::Config>::Origin,799 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>800 {801 fn deposit_event() = default;802803 #[weight = *weight]804 fn log(origin, i: u32, weight: Weight) {805 Self::deposit_event(Event::Logged(i, weight));806 LOG.with(|log| {807 log.borrow_mut().push((origin.caller().clone(), i));808 })809 }810811 #[weight = *weight]812 fn log_without_filter(origin, i: u32, weight: Weight) {813 Self::deposit_event(Event::Logged(i, weight));814 LOG.with(|log| {815 log.borrow_mut().push((origin.caller().clone(), i));816 })817 }818 }819 }820 }821822 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;823 type Block = frame_system::mocking::MockBlock<Test>;824825 frame_support::construct_runtime!(826 pub enum Test where827 Block = Block,828 NodeBlock = Block,829 UncheckedExtrinsic = UncheckedExtrinsic,830 {831 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},832 Logger: logger::{Pallet, Call, Event},833 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},834 }835 );836837 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.838 pub struct BaseFilter;839 impl Contains<Call> for BaseFilter {840 fn contains(call: &Call) -> bool {841 !matches!(call, Call::Logger(logger::Call::log { .. }))842 }843 }844845 pub struct DummyExecutor; // todo do something with naming and function body846 impl<C: Dispatchable> ApplyExtrinsic<C> for DummyExecutor {847 fn apply_extrinsic(_signer: Address, _function: C) -> ApplyExtrinsicResult {848 todo!()849 }850 }851852 parameter_types! {853 pub const BlockHashCount: u64 = 250;854 pub BlockWeights: frame_system::limits::BlockWeights =855 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);856 }857 impl system::Config for Test {858 type BaseCallFilter = BaseFilter;859 type BlockWeights = ();860 type BlockLength = ();861 type DbWeight = RocksDbWeight;862 type Origin = Origin;863 type Call = Call;864 type Index = u64;865 type BlockNumber = u64;866 type Hash = H256;867 type Hashing = BlakeTwo256;868 type AccountId = u64;869 type Lookup = IdentityLookup<Self::AccountId>;870 type Header = Header;871 type Event = Event;872 type BlockHashCount = BlockHashCount;873 type Version = ();874 type PalletInfo = PalletInfo;875 type AccountData = ();876 type OnNewAccount = ();877 type OnKilledAccount = ();878 type SystemWeightInfo = ();879 type SS58Prefix = ();880 type OnSetCode = ();881 }882 impl logger::Config for Test {883 type Event = Event;884 }885 parameter_types! {886 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;887 pub const MaxScheduledPerBlock: u32 = 10;888 }889 ord_parameter_types! {890 pub const One: u64 = 1;891 }892893 impl Config for Test {894 type Event = Event;895 type Origin = Origin;896 type PalletsOrigin = OriginCaller;897 type Call = Call;898 type MaximumWeight = MaximumSchedulerWeight;899 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;900 type MaxScheduledPerBlock = MaxScheduledPerBlock;901 type WeightInfo = ();902 type Executor = DummyExecutor;903 }904}1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//! specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//! index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//! `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63 transaction_validity::TransactionValidityError,64 DispatchErrorWithPostInfo,65};66use frame_support::{67 decl_module, decl_storage, decl_event, decl_error,68 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},69 traits::{70 Get,71 schedule::{self, DispatchTime},72 OriginTrait, EnsureOrigin, IsType,73 },74 weights::{GetDispatchInfo, Weight, PostDispatchInfo},75};76use frame_system::{self as system, ensure_signed};77pub use weights::WeightInfo;78use up_sponsorship::SponsorshipHandler;79use scale_info::TypeInfo;80use sp_core::H160;8182/// Our pallet's configuration trait. All our types and constants go in here. If the83/// pallet is dependent on specific other pallets, then their configuration traits84/// should be added to our implied traits list.85///86/// `system::Config` should always be included in our implied traits.87/// //88pub trait Config: system::Config {89 /// The overarching event type.90 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;9192 /// The aggregated origin which the dispatch will take.93 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>94 + From<Self::PalletsOrigin>95 + IsType<<Self as system::Config>::Origin>;9697 /// The caller origin, overarching type of all pallets origins.98 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;99100 /// The aggregated call type.101 type Call: Parameter102 + Dispatchable<Origin = <Self as Config>::Origin>103 + GetDispatchInfo104 + From<system::Call<Self>>;105106 /// The maximum weight that may be scheduled per block for any dispatchables of less priority107 /// than `schedule::HARD_DEADLINE`.108 type MaximumWeight: Get<Weight>;109110 /// Required origin to schedule or cancel calls.111 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;112113 /// The maximum number of scheduled calls in the queue for a single block.114 /// Not strictly enforced, but used for weight estimation.115 type MaxScheduledPerBlock: Get<u32>;116117 /// Sponsoring function.118 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;119120 /// Weight information for extrinsics in this pallet.121 type WeightInfo: WeightInfo;122123 /// The helper type used for custom transaction fee logic.124 type CallExecutor: DispatchCall<Self, H160>;125}126127/// A Scheduler-Runtime interface for finer payment handling.128pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {129 /// The type that encodes information that can be passed from pre_dispatch to post-dispatch.130 type Pre: Default + Codec + Clone + TypeInfo;131132 /// Resolve the call dispatch, including any post-dispatch operations.133 fn dispatch_call(134 pre_dispatch: Self::Pre,135 function: <T as Config>::Call,136 ) -> Result<137 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,138 TransactionValidityError,139 >;140141 /// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).142 fn pre_dispatch(143 signer: T::AccountId,144 function: <T as Config>::Call,145 ) -> Result<Self::Pre, TransactionValidityError>;146147 /// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).148 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;149}150151pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;152153pub const PERIODIC_CALLS_LIMIT: u32 = 100;154155// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;156157/// Just a simple index for naming period tasks.158pub type PeriodicIndex = u32;159/// The location of a scheduled task that can be used to remove it.160pub type TaskAddress<BlockNumber> = (BlockNumber, u32);161162/*#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))] todo remove completely?163#[derive(Clone, RuntimeDebug, Encode, Decode)]164struct ScheduledV1<Call, BlockNumber> {165 maybe_id: Option<Vec<u8>>,166 priority: schedule::Priority,167 call: Call,168 maybe_periodic: Option<schedule::Period<BlockNumber>>,169}*/170171/// Information regarding an item to be executed in the future.172#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]173#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]174pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {175 /// The unique identity for this task, if there is one.176 maybe_id: Option<Vec<u8>>,177 /// This task's priority.178 priority: schedule::Priority,179 /// The call to be dispatched.180 call: Call,181 /// If the call is periodic, then this points to the information concerning that.182 maybe_periodic: Option<schedule::Period<BlockNumber>>,183 /// The origin to dispatch the call.184 origin: PalletsOrigin,185 /// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.186 pre_dispatch: PreDispatch,187 _phantom: PhantomData<AccountId>,188}189190/// The current version of Scheduled struct.191/*pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> =192 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch>;*/193194// A value placed in storage that represents the current version of the Scheduler storage.195// This value is used by the `on_runtime_upgrade` logic to determine whether we run196// storage migration logic.197/*#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)] todo remove completely?198enum Releases {199 V1,200 V2,201}202203impl Default for Releases {204 fn default() -> Self {205 Releases::V1206 }207}*/208209#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]210pub struct CallSpec {211 module: u32,212 method: u32,213}214215decl_storage! {216 trait Store for Module<T: Config> as Scheduler {217 /// Items to be executed, indexed by the block number that they should be executed on.218 pub Agenda: map hasher(twox_64_concat) T::BlockNumber219 => Vec<Option<Scheduled<220 <T as Config>::Call,221 T::BlockNumber,222 T::PalletsOrigin,223 T::AccountId,224 <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre225 >>>;226227 /*pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber todo remove completely?228 => Vec<Option<CallSpec>>;*/229230 /// Lookup from identity to the block number and index of the task.231 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;232233 // / Storage version of the pallet.234 // /235 // / New networks start with last version.236 //StorageVersion build(|_| Releases::V2): Releases; todo remove completely?237 }238}239240decl_event!(241 pub enum Event<T> where <T as system::Config>::BlockNumber {242 /// Scheduled some task. \[when, index\]243 Scheduled(BlockNumber, u32),244 /// Canceled some task. \[when, index\]245 Canceled(BlockNumber, u32),246 /// Dispatched some task. \[task, id, result\]247 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),248 }249);250251decl_error! {252 pub enum Error for Module<T: Config> {253 /// Failed to schedule a call254 FailedToSchedule,255 /// Cannot find the scheduled call.256 NotFound,257 /// Given target block number is in the past.258 TargetBlockNumberInPast,259 /// Reschedule failed because it does not change scheduled time.260 RescheduleNoChange,261 }262}263264decl_module! {265 /// Scheduler module declaration.266 pub struct Module<T: Config> for enum Call267 where268 origin: <T as system::Config>::Origin269 {270 type Error = Error<T>;271 fn deposit_event() = default;272273 /// Anonymously schedule a task.274 ///275 /// # <weight>276 /// - S = Number of already scheduled calls277 /// - Base Weight: 22.29 + .126 * S µs278 /// - DB Weight:279 /// - Read: Agenda280 /// - Write: Agenda281 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls282 /// # </weight>283 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]284 fn schedule(origin,285 when: T::BlockNumber,286 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,287 priority: schedule::Priority,288 call: Box<<T as Config>::Call>,289 )290 {291 let origin = <T as Config>::Origin::from(origin);292 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;293 }294295 /// Cancel an anonymously scheduled task.296 ///297 /// # <weight>298 /// - S = Number of already scheduled calls299 /// - Base Weight: 22.15 + 2.869 * S µs300 /// - DB Weight:301 /// - Read: Agenda302 /// - Write: Agenda, Lookup303 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls304 /// # </weight>305 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]306 fn cancel(origin, when: T::BlockNumber, index: u32) {307 T::ScheduleOrigin::ensure_origin(origin.clone())?;308 let origin = <T as Config>::Origin::from(origin);309 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;310 }311312 /// Schedule a named task.313 ///314 /// # <weight>315 /// - S = Number of already scheduled calls316 /// - Base Weight: 29.6 + .159 * S µs317 /// - DB Weight:318 /// - Read: Agenda, Lookup319 /// - Write: Agenda, Lookup320 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls321 /// # </weight>322 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]323 fn schedule_named(origin,324 id: Vec<u8>,325 when: T::BlockNumber,326 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,327 priority: schedule::Priority,328 call: Box<<T as Config>::Call>,329 ) {330 T::ScheduleOrigin::ensure_origin(origin.clone())?;331 let origin = <T as Config>::Origin::from(origin);332 Self::do_schedule_named(333 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call334 )?;335 }336337 /// Cancel a named scheduled task.338 ///339 /// # <weight>340 /// - S = Number of already scheduled calls341 /// - Base Weight: 24.91 + 2.907 * S µs342 /// - DB Weight:343 /// - Read: Agenda, Lookup344 /// - Write: Agenda, Lookup345 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls346 /// # </weight>347 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]348 fn cancel_named(origin, id: Vec<u8>) {349 T::ScheduleOrigin::ensure_origin(origin.clone())?;350 let origin = <T as Config>::Origin::from(origin);351 Self::do_cancel_named(Some(origin.caller().clone()), id)?;352 }353354 /// Anonymously schedule a task after a delay.355 ///356 /// # <weight>357 /// Same as [`schedule`].358 /// # </weight>359 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]360 fn schedule_after(origin,361 after: T::BlockNumber,362 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,363 priority: schedule::Priority,364 call: Box<<T as Config>::Call>,365 ) {366 T::ScheduleOrigin::ensure_origin(origin.clone())?;367 let origin = <T as Config>::Origin::from(origin);368 Self::do_schedule_nameless(369 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call370 )?;371 }372373 /// Schedule a named task after a delay.374 ///375 /// # <weight>376 /// Same as [`schedule_named`].377 /// # </weight>378 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]379 fn schedule_named_after(origin,380 id: Vec<u8>,381 after: T::BlockNumber,382 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,383 priority: schedule::Priority,384 call: Box<<T as Config>::Call>,385 ) {386 T::ScheduleOrigin::ensure_origin(origin.clone())?;387 let origin = <T as Config>::Origin::from(origin);388 Self::do_schedule_named(389 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call390 )?;391 }392393 /// Execute the scheduled calls394 ///395 /// # <weight>396 /// - S = Number of already scheduled calls397 /// - N = Named scheduled calls398 /// - P = Periodic Calls399 /// - Base Weight: 9.243 + 23.45 * S µs400 /// - DB Weight:401 /// - Read: Agenda + Lookup * N + Agenda(Future) * P402 /// - Write: Agenda + Lookup * N + Agenda(future) * P403 /// # </weight>404 fn on_initialize(now: T::BlockNumber) -> Weight {405 let limit = T::MaximumWeight::get();406 let mut queued = Agenda::<T>::take(now)407 .into_iter()408 .enumerate()409 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))410 .collect::<Vec<_>>();411 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {412 log::warn!(413 target: "runtime::scheduler",414 "Warning: This block has more items queued in Scheduler than \415 expected from the runtime configuration. An update might be needed."416 );417 }418 queued.sort_by_key(|(_, s)| s.priority);419 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)420 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)421 queued.into_iter()422 .enumerate()423 .scan(base_weight, |cumulative_weight, (order, (index, s))| {424 *cumulative_weight = cumulative_weight425 .saturating_add(s.call.get_dispatch_info().weight);426427 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(428 s.origin.clone()429 ).into();430431 if ensure_signed(origin).is_ok() {432 // AccountData for inner call origin accountdata.433 *cumulative_weight = cumulative_weight434 .saturating_add(T::DbWeight::get().reads_writes(1, 1));435 }436437 if s.maybe_id.is_some() {438 // Remove/Modify Lookup439 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));440 }441 if s.maybe_periodic.is_some() {442 // Read/Write Agenda for future block443 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));444 }445446 Some((order, index, *cumulative_weight, s))447 })448 .filter_map(|(order, index, cumulative_weight, mut s)| {449 // We allow a scheduled call if:450 // - It's priority is `HARD_DEADLINE`451 // - It does not push the weight past the limit452 // or, alternatively,453 // - It is the first item in the schedule454 if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {455 let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());456457 if let Err(_) = r {458 log::warn!(459 target: "runtime::scheduler",460 "Warning: Scheduler has failed to execute a post-dispatch transaction. \461 This block might have become invalid.",462 );463 // todo possibly force a skip/return here, do something with the error464 }465466 let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?467468 let maybe_id = s.maybe_id.clone();469 if let Some((period, count)) = s.maybe_periodic {470 if count > 1 {471 s.maybe_periodic = Some((period, count - 1));472 } else {473 s.maybe_periodic = None;474 }475 let next = now + period;476 // If scheduled is named, place it's information in `Lookup`477 if let Some(ref id) = s.maybe_id {478 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);479 Lookup::<T>::insert(id, (next, next_index as u32));480 }481 Agenda::<T>::append(next, Some(s));482 } else if let Some(ref id) = s.maybe_id {483 Lookup::<T>::remove(id);484 }485 Self::deposit_event(RawEvent::Dispatched(486 (now, index),487 maybe_id,488 r.map(|_| ()).map_err(|e| e.error)489 ));490 total_weight = cumulative_weight;491 None492 } else {493 Some(Some(s))494 }495 })496 .for_each(|unused| {497 let next = now + One::one();498 Agenda::<T>::append(next, unused);499 });500501 total_weight502 }503 }504}505506impl<T: Config> Module<T> {507 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {508 let now = frame_system::Pallet::<T>::block_number();509510 let when = match when {511 DispatchTime::At(x) => x,512 // The current block has already completed it's scheduled tasks, so513 // Schedule the task at lest one block after this current block.514 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),515 };516517 if when <= now {518 return Err(Error::<T>::TargetBlockNumberInPast.into());519 }520521 Ok(when)522 }523524 fn do_schedule(525 maybe_id: Option<Vec<u8>>,526 when: DispatchTime<T::BlockNumber>,527 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,528 priority: schedule::Priority,529 origin: T::PalletsOrigin,530 call: <T as Config>::Call,531 ) -> Result<(T::BlockNumber, u32), DispatchError> {532 let when = Self::resolve_time(when)?;533534 let sender = ensure_signed(535 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),536 )537 .unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment538 //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);539 //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));540 //let r = call.clone().dispatch(sponsor.into());541542 let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {543 Ok(pre_dispatch) => pre_dispatch,544 Err(_) => return Err(Error::<T>::FailedToSchedule.into()),545 };546547 // todo continually pre-dispatch according to maybe_periodic -- but it's called only once?548 // no, reschedule and cancel rely on scheduled being only the next instance549 // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee550551 // sanitize maybe_periodic552 let maybe_periodic = maybe_periodic553 .filter(|p| p.1 > 1 && !p.0.is_zero())554 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.555 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));556557 if let Some(periodic) = maybe_periodic {558 for _i in 0..=periodic.1 {559 // displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment560 // send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?561 // roadblock - they will return on post_dispatch -- oh! tips?562 }563 }564565 let s = Some(Scheduled {566 maybe_id,567 priority,568 call,569 maybe_periodic,570 origin,571 pre_dispatch,572 _phantom: PhantomData::<T::AccountId>::default(),573 });574 Agenda::<T>::append(when, s);575 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;576 if index > T::MaxScheduledPerBlock::get() {577 log::warn!(578 target: "runtime::scheduler",579 "Warning: There are more items queued in the Scheduler than \580 expected from the runtime configuration. An update might be needed.",581 );582 }583584 Ok((when, index))585 }586587 fn do_schedule_nameless(588 when: DispatchTime<T::BlockNumber>,589 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,590 priority: schedule::Priority,591 origin: T::PalletsOrigin,592 call: <T as Config>::Call,593 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {594 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;595 let (when, index) = address;596597 Self::deposit_event(RawEvent::Scheduled(when, index));598599 Ok(address)600 }601602 fn do_cancel(603 origin: Option<T::PalletsOrigin>,604 (when, index): TaskAddress<T::BlockNumber>,605 ) -> Result<(), DispatchError> {606 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {607 agenda.get_mut(index as usize).map_or(608 Ok(None),609 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {610 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {611 if *o != s.origin {612 return Err(BadOrigin.into());613 }614 };615 Ok(s.take())616 },617 )618 })?;619 if let Some(s) = scheduled {620 if let Some(id) = s.maybe_id {621 Lookup::<T>::remove(id);622 }623 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {624 log::warn!(625 target: "runtime::scheduler",626 "Warning: Scheduler has failed to execute a post-dispatch transaction. \627 This block might have become invalid.",628 );629 } // maybe do something with the error?630 Self::deposit_event(RawEvent::Canceled(when, index));631 Ok(())632 } else {633 Err(Error::<T>::NotFound.into())634 }635 }636637 fn do_reschedule(638 (when, index): TaskAddress<T::BlockNumber>,639 new_time: DispatchTime<T::BlockNumber>,640 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {641 let new_time = Self::resolve_time(new_time)?;642643 if new_time == when {644 return Err(Error::<T>::RescheduleNoChange.into());645 }646647 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {648 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;649 let task = task.take().ok_or(Error::<T>::NotFound)?;650 Agenda::<T>::append(new_time, Some(task));651 Ok(())652 })?;653654 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;655 Self::deposit_event(RawEvent::Canceled(when, index));656 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));657658 Ok((new_time, new_index))659 }660661 fn do_schedule_named(662 id: Vec<u8>,663 when: DispatchTime<T::BlockNumber>,664 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,665 priority: schedule::Priority,666 origin: T::PalletsOrigin,667 call: <T as Config>::Call,668 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {669 // ensure id length does not exceed expectations & is unique670 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()671 || Lookup::<T>::contains_key(&id)672 {673 return Err(Error::<T>::FailedToSchedule.into());674 }675676 let address = Self::do_schedule(677 Some(id.clone()),678 when,679 maybe_periodic,680 priority,681 origin,682 call,683 )?;684 let (when, index) = address;685686 Lookup::<T>::insert(&id, &address);687 Self::deposit_event(RawEvent::Scheduled(when, index));688 Ok(address)689 }690691 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {692 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {693 if let Some((when, index)) = lookup.take() {694 let i = index as usize;695 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {696 if let Some(s) = agenda.get_mut(i) {697 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {698 if *o != s.origin {699 return Err(BadOrigin.into());700 }701 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())702 {703 log::warn!(704 target: "runtime::scheduler",705 "Warning: Scheduler has failed to execute a post-dispatch transaction. \706 This block might have become invalid.",707 );708 } // maybe do something with the error?709 }710 *s = None;711 }712 Ok(())713 })?;714 Self::deposit_event(RawEvent::Canceled(when, index));715 Ok(())716 } else {717 Err(Error::<T>::NotFound.into())718 }719 })720 }721722 fn do_reschedule_named(723 id: Vec<u8>,724 new_time: DispatchTime<T::BlockNumber>,725 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {726 let new_time = Self::resolve_time(new_time)?;727728 Lookup::<T>::try_mutate_exists(729 id,730 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {731 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;732733 if new_time == when {734 return Err(Error::<T>::RescheduleNoChange.into());735 }736737 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {738 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;739 let task = task.take().ok_or(Error::<T>::NotFound)?;740 Agenda::<T>::append(new_time, Some(task));741742 Ok(())743 })?;744745 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;746 Self::deposit_event(RawEvent::Canceled(when, index));747 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));748749 *lookup = Some((new_time, new_index));750751 Ok((new_time, new_index))752 },753 )754 }755}756757impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>758 for Module<T>759{760 type Address = TaskAddress<T::BlockNumber>;761762 fn schedule(763 when: DispatchTime<T::BlockNumber>,764 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,765 priority: schedule::Priority,766 origin: T::PalletsOrigin,767 call: <T as Config>::Call,768 ) -> Result<Self::Address, DispatchError> {769 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)770 }771772 fn cancel((when, index): Self::Address) -> Result<(), ()> {773 Self::do_cancel(None, (when, index)).map_err(|_| ())774 }775776 fn reschedule(777 address: Self::Address,778 when: DispatchTime<T::BlockNumber>,779 ) -> Result<Self::Address, DispatchError> {780 Self::do_reschedule(address, when)781 }782783 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {784 Agenda::<T>::get(when)785 .get(index as usize)786 .ok_or(())787 .map(|_| when)788 }789}790791impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>792 for Module<T>793{794 type Address = TaskAddress<T::BlockNumber>;795796 fn schedule_named(797 id: Vec<u8>,798 when: DispatchTime<T::BlockNumber>,799 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,800 priority: schedule::Priority,801 origin: T::PalletsOrigin,802 call: <T as Config>::Call,803 ) -> Result<Self::Address, ()> {804 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())805 }806807 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {808 Self::do_cancel_named(None, id).map_err(|_| ())809 }810811 fn reschedule_named(812 id: Vec<u8>,813 when: DispatchTime<T::BlockNumber>,814 ) -> Result<Self::Address, DispatchError> {815 Self::do_reschedule_named(id, when)816 }817818 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {819 Lookup::<T>::get(id)820 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))821 .ok_or(())822 }823}824825#[cfg(test)]826#[allow(clippy::from_over_into)]827mod tests {828 use super::*;829830 use frame_support::{831 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,832 };833 use sp_core::H256;834 use sp_runtime::{835 Perbill,836 testing::Header,837 traits::{BlakeTwo256, IdentityLookup},838 };839 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};840 use crate as scheduler;841842 mod logger {843 use super::*;844 use std::cell::RefCell;845846 thread_local! {847 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());848 }849 pub trait Config: system::Config {850 type Event: From<Event> + Into<<Self as system::Config>::Event>;851 }852 decl_event! {853 pub enum Event {854 Logged(u32, Weight),855 }856 }857 decl_module! {858 pub struct Module<T: Config> for enum Call859 where860 origin: <T as system::Config>::Origin,861 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>862 {863 fn deposit_event() = default;864865 #[weight = *weight]866 fn log(origin, i: u32, weight: Weight) {867 Self::deposit_event(Event::Logged(i, weight));868 LOG.with(|log| {869 log.borrow_mut().push((origin.caller().clone(), i));870 })871 }872873 #[weight = *weight]874 fn log_without_filter(origin, i: u32, weight: Weight) {875 Self::deposit_event(Event::Logged(i, weight));876 LOG.with(|log| {877 log.borrow_mut().push((origin.caller().clone(), i));878 })879 }880 }881 }882 }883884 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;885 type Block = frame_system::mocking::MockBlock<Test>;886887 frame_support::construct_runtime!(888 pub enum Test where889 Block = Block,890 NodeBlock = Block,891 UncheckedExtrinsic = UncheckedExtrinsic,892 {893 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},894 Logger: logger::{Pallet, Call, Event},895 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},896 }897 );898899 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.900 pub struct BaseFilter;901 impl Contains<Call> for BaseFilter {902 fn contains(call: &Call) -> bool {903 !matches!(call, Call::Logger(logger::Call::log { .. }))904 }905 }906907 pub struct DummyExecutor;908 impl<T: frame_system::Config + Config, SelfContainedSignedInfo>909 DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor910 {911 type Pre = ();912913 fn dispatch_call(914 _pre: Self::Pre,915 _call: <T as Config>::Call,916 ) -> Result<917 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,918 TransactionValidityError,919 > {920 todo!()921 }922923 fn pre_dispatch(924 _signer: <T as frame_system::Config>::AccountId,925 _call: <T as Config>::Call,926 ) -> Result<Self::Pre, TransactionValidityError> {927 todo!()928 }929930 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {931 todo!()932 }933 }934935 parameter_types! {936 pub const BlockHashCount: u64 = 250;937 pub BlockWeights: frame_system::limits::BlockWeights =938 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);939 }940 impl system::Config for Test {941 type BaseCallFilter = BaseFilter;942 type BlockWeights = ();943 type BlockLength = ();944 type DbWeight = RocksDbWeight;945 type Origin = Origin;946 type Call = Call;947 type Index = u64;948 type BlockNumber = u64;949 type Hash = H256;950 type Hashing = BlakeTwo256;951 type AccountId = u64;952 type Lookup = IdentityLookup<Self::AccountId>;953 type Header = Header;954 type Event = Event;955 type BlockHashCount = BlockHashCount;956 type Version = ();957 type PalletInfo = PalletInfo;958 type AccountData = ();959 type OnNewAccount = ();960 type OnKilledAccount = ();961 type SystemWeightInfo = ();962 type SS58Prefix = ();963 type OnSetCode = ();964 }965 impl logger::Config for Test {966 type Event = Event;967 }968 parameter_types! {969 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;970 pub const MaxScheduledPerBlock: u32 = 10;971 }972 ord_parameter_types! {973 pub const One: u64 = 1;974 }975976 impl Config for Test {977 type Event = Event;978 type Origin = Origin;979 type PalletsOrigin = OriginCaller;980 type Call = Call;981 type MaximumWeight = MaximumSchedulerWeight;982 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;983 type MaxScheduledPerBlock = MaxScheduledPerBlock;984 type SponsorshipHandler = ();985 type WeightInfo = ();986 type CallExecutor = DummyExecutor;987 }988}runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -17,6 +17,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::{SignedExtension, Member};
// #[cfg(any(feature = "std", test))]
// pub use sp_runtime::BuildStorage;
@@ -54,7 +56,7 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
},
};
-use pallet_unq_scheduler::ApplyExtrinsic;
+use pallet_unq_scheduler::DispatchCall;
use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
@@ -66,6 +68,7 @@
traits::{BaseArithmetic, Unsigned},
};
use smallvec::smallvec;
+use scale_info::TypeInfo;
use codec::{Encode, Decode};
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
use fp_rpc::TransactionStatus;
@@ -73,6 +76,7 @@
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
transaction_validity::TransactionValidityError,
+ DispatchErrorWithPostInfo,
};
// pub use pallet_timestamp::Call as TimestampCall;
@@ -805,30 +809,114 @@
pub const MaxScheduledPerBlock: u32 = 50;
}
-type EvmSponsorshipHandler = (
- pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
- pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
-);
-type SponsorshipHandler = (
- pallet_unique::UniqueSponsorshipHandler<Runtime>,
- //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
- pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
-);
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+
+/*fn get_signed_extra(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {
+ (
+ 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(),
+ ChargeTransactionPayment::new(0),
+ )
+}*/
-// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {
-// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)
-// }
+#[derive(Default, Encode, Decode, Clone, TypeInfo)]
+pub struct SchedulerPreDispatch {
+ tip: Balance,
+ signer: AccountId,
+ fee: Option<Balance>,
+}
pub struct SchedulerPaymentExecutor;
-impl<C: Dispatchable> ApplyExtrinsic<C> for SchedulerPaymentExecutor {
- fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {
- /*let extrinsic = sign(fp_self_contained::CheckedExtrinsic {
- signed: fp_self_contained::CheckedSignature::SelfContained(None),
- function,
- });
+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>,
+{
+ type Pre = SchedulerPreDispatch;
+
+ fn dispatch_call(
+ //signer: <T as frame_system::Config>::AccountId,
+ pre_dispatch: Self::Pre,
+ 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,
+ SignedExtra,
+ SelfContainedSignedInfo,
+ > {
+ signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extra(signer.clone().into()),
+ ),
+ function: call.clone().into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)*/
+ let dispatch_info = call.get_dispatch_info();
+ let pre = (
+ pre_dispatch.tip,
+ pre_dispatch.signer.clone().into(),
+ pre_dispatch.fee.map(|fee| NegativeImbalance::new(fee)),
+ );
+
+ let maybe_who = Some(pre_dispatch.signer.clone().into());
+ let res = Call::from(call.clone()).dispatch(Origin::from(maybe_who));
+ let post_info = match res {
+ Ok(dispatch_info) => dispatch_info,
+ Err(err) => err.post_info,
+ };
+ SignedExtra::post_dispatch(
+ ((), (), (), (), (), pre),
+ &dispatch_info,
+ &post_info,
+ 0,
+ &res.map(|_| ()).map_err(|e| e.error),
+ )?;
+ Ok(res)
+ }
+
+ fn pre_dispatch(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<Self::Pre, TransactionValidityError> {
+ let dispatch_info = call.get_dispatch_info();
+ //<T as Config>::OnChargeTransaction::withdraw_fee();
+ let fee_charger = ChargeTransactionPayment::new(
+ // Linear scaling of the fee tip if the priority is high enough
+ 0, //if priority > HARD_DEADLINE { 0 } else { (HARD_DEADLINE - priority + 1) / HARD_DEADLINE * PRIORITY_TIP_MULTIPLIER * total_fee }
+ );
+ let pre = fee_charger.pre_dispatch(&signer.into(), &call.into(), &dispatch_info, 0)?;
+
+ Ok(SchedulerPreDispatch {
+ tip: pre.0,
+ signer: pre.1,
+ fee: pre.2.map(|imbalance| imbalance.peek()),
+ })
+ }
- Executive::apply_extrinsic(extrinsic)*/
+ fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError> {
todo!()
+ // simply call post_dispatch with 0 actual fee and the whole remaining, already withdrawn, fee
}
}
@@ -840,10 +928,22 @@
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureSigned<AccountId>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type SponsorshipHandler = SponsorshipHandler;
type WeightInfo = ();
- type Executor = SchedulerPaymentExecutor;
+ type CallExecutor = SchedulerPaymentExecutor;
}
+type EvmSponsorshipHandler = (
+ pallet_unique::UniqueEthSponsorshipHandler<Runtime>,
+ pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
+);
+
+type SponsorshipHandler = (
+ pallet_unique::UniqueSponsorshipHandler<Runtime>,
+ //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
+ pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
+);
+
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
type Currency = Balances;
@@ -965,7 +1065,7 @@
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
- pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+ ChargeTransactionPayment,
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -3,22 +3,41 @@
// file 'LICENSE', which is part of this source code package.
//
-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,
+ submitTransactionExpectFailAsync,
+} from './substrate/substrate-api';
+import {
createItemExpectSuccess,
createCollectionExpectSuccess,
scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ setCollectionLimitsExpectSuccess,
+ getDetailedCollectionInfo,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
} from './util/helpers';
import {IKeyringPair} from '@polkadot/types/types';
+import {getBalanceSingle} from './substrate/get-balance';
chai.use(chaiAsPromised);
-describe('Integration Test scheduler base transaction', () => {
+describe('Scheduling token and balance transfers', () => {
let alice: IKeyringPair;
let bob: IKeyringPair;
@@ -29,7 +48,7 @@
});
});
- it('User can transfer owned token with delay (scheduler)', async () => {
+ it('Can schedule a transfer of an owned token with delay', async () => {
await usingApi(async () => {
// nft
const nftCollectionId = await createCollectionExpectSuccess();
@@ -37,7 +56,219 @@
await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async (api) => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
+ const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+ 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 aliceBalanceBefore = await getFreeBalance(alice);
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
+ const aliceBalanceAfter = await getFreeBalance(alice);
+ expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ });
+ });
+
+ /*it('Can\'t schedule a transaction with no funds', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
+
+ await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
+
+ await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ });
+ });*/
+
+ 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);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ 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.skip('Going bankrupt after sponsoring a scheduled transaction does not nullify the transaction', async () => {
+ await usingApi(async (api) => {
+ // Find two empty, unused accounts
+ const zeroBalance = await findUnusedAddress(api);
+ const zeroBalanceSponsor = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Grace these with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Grace these with money, enough to cover future transactions
+ const balanceSponsorTx = api.tx.balances.transfer(zeroBalanceSponsor.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceSponsorTx);
+
+ // Set a collection sponsor
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalanceSponsor.address);
+ await confirmSponsorshipExpectSuccess(collectionId);
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ // const waitForBlocks = 4;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
+ //await waitAfterScheduleExpectSuccess(collectionId, tokenId, alice, 3);
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalanceSponsor.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(4);
+
+ 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);
+
+ /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
+ sponsoredDataRateLimit: 2,
+ });*/
+ //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
+ 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);
+
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+
+ 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(2);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+});
+
+describe.skip('Scheduling EVM smart contracts', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+
+ before(async() => {
+ await usingApi(async () => {
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+ });
+
+ // todo contract testing
+ it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api) => {
+ // Find unused address
+ const zeroBalance = await findUnusedAddress(api);
+
+ // Mint token for alice
+ const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ // Transfer this token from Alice to unused address and back
+ // Alice to Zero gets sponsored
+ const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
+ const events1 = await submitTransactionAsync(alice, aliceToZero);
+ const result1 = getGenericResult(events1);
+
+ // Second transfer should fail
+ const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
+ const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
+ const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
+ const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+
+ // Try again after Zero gets some balance - now it should succeed
+ const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balancetx);
+ const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
+ const result2 = getGenericResult(events2);
+
+ expect(result1.success).to.be.true;
+ expect(result2.success).to.be.true;
+ expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -481,10 +481,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);
@@ -792,7 +798,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();
@@ -822,6 +828,31 @@
}
export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);
+
+ const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ console.log(await getFreeBalance(sender));
+
+ // sleep for n + 1 blocks
+ await waitNewBlocks(blockSchedule + 1);
+
+ const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
+ expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ });
+}
+
+export async function
scheduleTransferExpectSuccess(
collectionId: number,
tokenId: number,
@@ -838,19 +869,36 @@
const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
- await submitTransactionAsync(sender, scheduleTx);
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- 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));
+ });
+}
- 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,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
- // sleep for 4 blocks
- await waitNewBlocks(blockSchedule + 1);
+ const balanceBefore = await getFreeBalance(recipient);
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+ const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);
- const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(recipient.address));
- expect(recipientBalanceAfter).to.be.equal(recipientBalanceBefore);
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
});
}