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.1920// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A module for scheduling dispatches.37//!38//! - [`Config`]39//! - [`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 dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a61//! specified block and with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and63//! index.64//! * `schedule_named` - augments the `schedule` interface with an additional65//! `Vec<u8>` parameter that can be used for identification.66//! * `cancel_named` - the named complement to the cancel function.6768// Ensure we're `no_std` when compiling for Wasm.69#![cfg_attr(not(feature = "std"), no_std)]70#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]7172mod benchmarking;73pub mod weights;7475use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};76use codec::{Encode, Decode, Codec};77use sp_runtime::{78 RuntimeDebug,79 traits::{Zero, One, BadOrigin, Saturating},80};81use frame_support::{82 decl_module, decl_storage, decl_event, decl_error,83 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},84 traits::{85 Get,86 schedule::{self, DispatchTime},87 OriginTrait, EnsureOrigin, IsType,88 },89 weights::{GetDispatchInfo, Weight},90};91use frame_system::{self as system, ensure_signed};92pub use weights::WeightInfo;93use up_sponsorship::SponsorshipHandler;94use scale_info::TypeInfo;9596/// 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.141pub type PeriodicIndex = u32;142/// The location of a scheduled task that can be used to remove it.143pub type TaskAddress<BlockNumber> = (BlockNumber, u32);144145#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]146#[derive(Clone, RuntimeDebug, Encode, Decode)]147struct ScheduledV1<Call, BlockNumber> {148 maybe_id: Option<Vec<u8>>,149 priority: schedule::Priority,150 call: Call,151 maybe_periodic: Option<schedule::Period<BlockNumber>>,152}153154/// Information regarding an item to be executed in the future.155#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]156#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]157pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {158 /// The unique identity for this task, if there is one.159 maybe_id: Option<Vec<u8>>,160 /// This task's priority.161 priority: schedule::Priority,162 /// The call to be dispatched.163 call: Call,164 /// If the call is periodic, then this points to the information concerning that.165 maybe_periodic: Option<schedule::Period<BlockNumber>>,166 /// The origin to dispatch the call.167 origin: PalletsOrigin,168 _phantom: PhantomData<AccountId>,169}170171/// The current version of Scheduled struct.172pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =173 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;174175// A value placed in storage that represents the current version of the Scheduler storage.176// This value is used by the `on_runtime_upgrade` logic to determine whether we run177// storage migration logic.178#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]179enum Releases {180 V1,181 V2,182}183184impl Default for Releases {185 fn default() -> Self {186 Releases::V1187 }188}189190#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]191pub struct CallSpec {192 module: u32,193 method: u32,194}195196decl_storage! {197 trait Store for Module<T: Config> as Scheduler {198 /// Items to be executed, indexed by the block number that they should be executed on.199 pub Agenda: map hasher(twox_64_concat) T::BlockNumber200 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;201202 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber203 => Vec<Option<CallSpec>>;204205 /// Lookup from identity to the block number and index of the task.206 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;207208 /// Storage version of the pallet.209 ///210 /// New networks start with last version.211 StorageVersion build(|_| Releases::V2): Releases;212 }213}214215decl_event!(216 pub enum Event<T> where <T as system::Config>::BlockNumber {217 /// Scheduled some task. \[when, index\]218 Scheduled(BlockNumber, u32),219 /// Canceled some task. \[when, index\]220 Canceled(BlockNumber, u32),221 /// Dispatched some task. \[task, id, result\]222 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),223 }224);225226decl_error! {227 pub enum Error for Module<T: Config> {228 /// Failed to schedule a call229 FailedToSchedule,230 /// Cannot find the scheduled call.231 NotFound,232 /// Given target block number is in the past.233 TargetBlockNumberInPast,234 /// Reschedule failed because it does not change scheduled time.235 RescheduleNoChange,236 }237}238239decl_module! {240 /// Scheduler module declaration.241 pub struct Module<T: Config> for enum Call242 where243 origin: <T as system::Config>::Origin244 {245 type Error = Error<T>;246 fn deposit_event() = default;247248249 /// Anonymously schedule a task.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,262 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,263 priority: schedule::Priority,264 call: Box<<T as Config>::Call>,265 )266 {267 let origin = <T as Config>::Origin::from(origin);268 Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;269 }270271 /// Cancel an anonymously scheduled task.272 ///273 /// # <weight>274 /// - S = Number of already scheduled calls275 /// - Base Weight: 22.15 + 2.869 * S µs276 /// - DB Weight:277 /// - Read: Agenda278 /// - Write: Agenda, Lookup279 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls280 /// # </weight>281 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]282 fn cancel(origin, when: T::BlockNumber, index: u32) {283 T::ScheduleOrigin::ensure_origin(origin.clone())?;284 let origin = <T as Config>::Origin::from(origin);285 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;286 }287288 /// Schedule a named task.289 ///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,300 id: Vec<u8>,301 when: T::BlockNumber,302 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,303 priority: schedule::Priority,304 call: Box<<T as Config>::Call>,305 ) {306 T::ScheduleOrigin::ensure_origin(origin.clone())?;307 let origin = <T as Config>::Origin::from(origin);308 Self::do_schedule_named(309 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call310 )?;311 }312313 /// Cancel a named scheduled task.314 ///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>) {325 T::ScheduleOrigin::ensure_origin(origin.clone())?;326 let origin = <T as Config>::Origin::from(origin);327 Self::do_cancel_named(Some(origin.caller().clone()), id)?;328 }329330 /// 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.350 ///351 /// # <weight>352 /// Same as [`schedule_named`].353 /// # </weight>354 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]355 fn schedule_named_after(origin,356 id: Vec<u8>,357 after: T::BlockNumber,358 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,359 priority: schedule::Priority,360 call: Box<<T as Config>::Call>,361 ) {362 T::ScheduleOrigin::ensure_origin(origin.clone())?;363 let origin = <T as Config>::Origin::from(origin);364 Self::do_schedule_named(365 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call366 )?;367 }368369 /// Execute the scheduled calls370 ///371 /// # <weight>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!(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 }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_weight400 .saturating_add(s.call.get_dispatch_info().weight);401402 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(403 s.origin.clone()404 ).into();405406 if ensure_signed(origin).is_ok() {407 // AccountData for inner call origin accountdata.408 *cumulative_weight = cumulative_weight409 .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 }476 }477}478479impl<T: Config> Module<T> {480 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {481 let now = frame_system::Pallet::<T>::block_number();482483 let when = match when {484 DispatchTime::At(x) => x,485 // The current block has already completed it's scheduled tasks, so486 // Schedule the task at lest one block after this current block.487 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),488 };489490 if when <= now {491 return Err(Error::<T>::TargetBlockNumberInPast.into());492 }493494 Ok(when)495 }496497 fn do_schedule(498 when: DispatchTime<T::BlockNumber>,499 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500 priority: schedule::Priority,501 origin: T::PalletsOrigin,502 call: <T as Config>::Call,503 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {504 let when = Self::resolve_time(when)?;505506 // sanitize maybe_periodic507 let maybe_periodic = maybe_periodic508 .filter(|p| p.1 > 1 && !p.0.is_zero())509 // Remove one from the number of repetitions since we will schedule one now.510 .map(|(p, c)| (p, c - 1));511 let s = Some(Scheduled {512 maybe_id: None,513 priority,514 call,515 maybe_periodic,516 origin,517 _phantom: PhantomData::<T::AccountId>::default(),518 });519 Agenda::<T>::append(when, s);520 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;521 if index > T::MaxScheduledPerBlock::get() {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));529530 Ok((when, index))531 }532533 fn do_cancel(534 origin: Option<T::PalletsOrigin>,535 (when, index): TaskAddress<T::BlockNumber>,536 ) -> Result<(), DispatchError> {537 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {538 agenda.get_mut(index as usize).map_or(539 Ok(None),540 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {541 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {542 if *o != s.origin {543 return Err(BadOrigin.into());544 }545 };546 Ok(s.take())547 },548 )549 })?;550 if let Some(s) = scheduled {551 if let Some(id) = s.maybe_id {552 Lookup::<T>::remove(id);553 }554 Self::deposit_event(RawEvent::Canceled(when, index));555 Ok(())556 } else {557 Err(Error::<T>::NotFound.into())558 }559 }560561 fn do_reschedule(562 (when, index): TaskAddress<T::BlockNumber>,563 new_time: DispatchTime<T::BlockNumber>,564 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {565 let new_time = Self::resolve_time(new_time)?;566567 if new_time == when {568 return Err(Error::<T>::RescheduleNoChange.into());569 }570571 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {572 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;573 let task = task.take().ok_or(Error::<T>::NotFound)?;574 Agenda::<T>::append(new_time, Some(task));575 Ok(())576 })?;577578 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;579 Self::deposit_event(RawEvent::Canceled(when, index));580 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));581582 Ok((new_time, new_index))583 }584585 fn do_schedule_named(586 id: Vec<u8>,587 when: DispatchTime<T::BlockNumber>,588 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,589 priority: schedule::Priority,590 origin: T::PalletsOrigin,591 call: <T as Config>::Call,592 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {593 // ensure id it is unique594 if Lookup::<T>::contains_key(&id) {595 return Err(Error::<T>::FailedToSchedule.into());596 }597598 let when = Self::resolve_time(when)?;599600 // sanitize maybe_periodic601 let maybe_periodic = maybe_periodic602 .filter(|p| p.1 > 1 && !p.0.is_zero())603 // Remove one from the number of repetitions since we will schedule one now.604 .map(|(p, c)| (p, c - 1));605606 let s = Scheduled {607 maybe_id: Some(id.clone()),608 priority,609 call,610 maybe_periodic,611 origin,612 _phantom: Default::default(),613 };614 Agenda::<T>::append(when, Some(s));615 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);624 Lookup::<T>::insert(&id, &address);625 Self::deposit_event(RawEvent::Scheduled(when, index));626627 Ok(address)628 }629630 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {631 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {632 if let Some((when, index)) = lookup.take() {633 let i = index as usize;634 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {635 if let Some(s) = agenda.get_mut(i) {636 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {637 if *o != s.origin {638 return Err(BadOrigin.into());639 }640 }641 *s = None;642 }643 Ok(())644 })?;645 Self::deposit_event(RawEvent::Canceled(when, index));646 Ok(())647 } else {648 Err(Error::<T>::NotFound.into())649 }650 })651 }652653 fn do_reschedule_named(654 id: Vec<u8>,655 new_time: DispatchTime<T::BlockNumber>,656 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {657 let new_time = Self::resolve_time(new_time)?;658659 Lookup::<T>::try_mutate_exists(660 id,661 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;663664 if new_time == when {665 return Err(Error::<T>::RescheduleNoChange.into());666 }667668 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {669 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;670 let task = task.take().ok_or(Error::<T>::NotFound)?;671 Agenda::<T>::append(new_time, Some(task));672673 Ok(())674 })?;675676 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;677 Self::deposit_event(RawEvent::Canceled(when, index));678 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));679680 *lookup = Some((new_time, new_index));681682 Ok((new_time, new_index))683 },684 )685 }686}687688#[cfg(test)]689#[allow(clippy::from_over_into)]690mod tests {691 use super::*;692693 use frame_support::{694 ord_parameter_types, parameter_types,695 traits::{Contains, ConstU32, EnsureOneOf},696 weights::constants::RocksDbWeight,697 };698 use sp_core::H256;699 use sp_runtime::{700 Perbill,701 testing::Header,702 traits::{BlakeTwo256, IdentityLookup},703 };704 use frame_system::{EnsureRoot, EnsureSignedBy};705 use crate as scheduler;706707 #[frame_support::pallet]708 pub mod logger {709 use super::{OriginCaller, OriginTrait};710 use frame_support::pallet_prelude::*;711 use frame_system::pallet_prelude::*;712 use std::cell::RefCell;713714 thread_local! {715 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());716 }717 pub fn log() -> Vec<(OriginCaller, u32)> {718 LOG.with(|log| log.borrow().clone())719 }720721 #[pallet::pallet]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)]745 pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {746 Self::deposit_event(Event::Logged(i, weight));747 LOG.with(|log| {748 log.borrow_mut().push((origin.caller().clone(), i));749 });750 Ok(())751 }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 }767768 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;769 type Block = frame_system::mocking::MockBlock<Test>;770771 frame_support::construct_runtime!(772 pub enum Test where773 Block = Block,774 NodeBlock = Block,775 UncheckedExtrinsic = UncheckedExtrinsic,776 {777 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},778 Logger: logger::{Pallet, Call, Event<T>},779 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},780 }781 );782783 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.784 pub struct BaseFilter;785 impl Contains<Call> for BaseFilter {786 fn contains(call: &Call) -> bool {787 !matches!(call, Call::Logger(logger::Call::log { .. }))788 }789 }790791 parameter_types! {792 pub const BlockHashCount: u64 = 250;793 pub BlockWeights: frame_system::limits::BlockWeights =794 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);795 }796 impl system::Config for Test {797 type BaseCallFilter = BaseFilter;798 type BlockWeights = ();799 type BlockLength = ();800 type DbWeight = RocksDbWeight;801 type Origin = Origin;802 type Call = Call;803 type Index = u64;804 type BlockNumber = u64;805 type Hash = H256;806 type Hashing = BlakeTwo256;807 type AccountId = u64;808 type Lookup = IdentityLookup<Self::AccountId>;809 type Header = Header;810 type Event = Event;811 type BlockHashCount = BlockHashCount;812 type Version = ();813 type PalletInfo = PalletInfo;814 type AccountData = ();815 type OnNewAccount = ();816 type OnKilledAccount = ();817 type SystemWeightInfo = ();818 type SS58Prefix = ();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 }832833 impl Config for Test {834 type Event = Event;835 type Origin = Origin;836 type PalletsOrigin = OriginCaller;837 type Call = Call;838 type MaximumWeight = MaximumSchedulerWeight;839 type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;840 type MaxScheduledPerBlock = MaxScheduledPerBlock;841 type WeightInfo = ();842 type SponsorshipHandler = ();843 }844}pallets/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(