difftreelog
Merge branch 'master' into release-v922000
in: master
9 files changed
README.mddiffbeforeafterboth--- a/README.md
+++ b/README.md
@@ -62,8 +62,18 @@
```
5. Build:
+
+Opal
+```bash
+cargo build --release
+```
+Quartz
+```bash
+cargo build --features=quartz-runtime --release
+```
+Unique
```bash
-cargo build --features=unique-runtime,quartz-runtime --release
+cargo build --features=unique-runtime --release
```
## Building as Parachain locally
@@ -155,13 +165,13 @@
location:
V0(X2(Parent, Parachain(PARA_ID)))
metadata:
- name OPL
- symbol OPL
+ name QTZ
+ symbol QTZ
decimals 18
minimalBalance 1
```
-### Next, we can send tokens from Opal to Karura:
+### Next, we can send tokens from Quartz to Karura:
```
polkadotXcm -> reserveTransferAssets
dest:
@@ -179,7 +189,7 @@
The result will be displayed in ChainState
tokens -> accounts
-### To send tokens from Karura to Opal:
+### To send tokens from Karura to Quartz:
```
xtokens -> transfer
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -14,6 +14,7 @@
// 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
use std::sync::Arc;
use codec::{Decode, Encode};
node/cli/src/service.rsdiffbeforeafterboth--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -14,8 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-//! Service and ServiceFactory implementation. Specialized wrapper over substrate service.
-
// std
use std::sync::Arc;
use std::sync::Mutex;
pallets/scheduler/src/lib.rsdiffbeforeafterboth1// This file is part of Substrate.23// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Schedulerdo_reschedule19//!20//! This Pallet exposes capabilities for scheduling dispatches to occur at a21//! specified block number or at a specified period. These scheduled dispatches22//! may be named or anonymous and may be canceled.23//!24//! **NOTE:** The scheduled calls will be dispatched with the default filter25//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin26//! except root which will get no filter. And not the filter contained in origin27//! use to call `fn schedule`.28//!29//! If a call is scheduled using proxy or whatever mecanism which adds filter,30//! then those filter will not be used when dispatching the schedule call.31//!32//! ## Interface33//!34//! ### Dispatchable Functions35//!36//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and37//! with a specified priority.38//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.39//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter40//! that can be used for identification.41//! * `cancel_named` - the named complement to the cancel function.4243// Ensure we're `no_std` when compiling for Wasm.44#![cfg_attr(not(feature = "std"), no_std)]4546#[cfg(feature = "runtime-benchmarks")]47mod benchmarking;4849pub mod weights;5051use sp_core::H160;52use codec::{Codec, Decode, Encode};53use frame_system::{self as system, ensure_signed};54pub use pallet::*;55use scale_info::TypeInfo;56use sp_runtime::{57 traits::{BadOrigin, One, Saturating, Zero},58 RuntimeDebug, DispatchErrorWithPostInfo,59};60use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};6162use frame_support::{63 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},64 traits::{65 schedule::{self, DispatchTime, MaybeHashed},66 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,67 StorageVersion,68 },69 weights::{GetDispatchInfo, Weight},70};7172pub use weights::WeightInfo;7374/// Just a simple index for naming period tasks.75pub type PeriodicIndex = u32;76/// The location of a scheduled task that can be used to remove it.77pub type TaskAddress<BlockNumber> = (BlockNumber, u32);78pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;7980type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];81pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;8283/// Information regarding an item to be executed in the future.84#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]85#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]86pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {87 /// The unique identity for this task, if there is one.88 maybe_id: Option<ScheduledId>,89 /// This task's priority.90 priority: schedule::Priority,91 /// The call to be dispatched.92 call: Call,93 /// If the call is periodic, then this points to the information concerning that.94 maybe_periodic: Option<schedule::Period<BlockNumber>>,95 /// The origin to dispatch the call.96 origin: PalletsOrigin,97 _phantom: PhantomData<AccountId>,98}99100pub type ScheduledV3Of<T> = ScheduledV3<101 CallOrHashOf<T>,102 <T as frame_system::Config>::BlockNumber,103 <T as Config>::PalletsOrigin,104 <T as frame_system::Config>::AccountId,105>;106107pub type ScheduledOf<T> = ScheduledV3Of<T>;108109/// The current version of Scheduled struct.110pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =111 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;112113#[cfg(feature = "runtime-benchmarks")]114mod preimage_provider {115 use frame_support::traits::PreimageRecipient;116 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}117 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}118}119120#[cfg(not(feature = "runtime-benchmarks"))]121mod preimage_provider {122 use frame_support::traits::PreimageProvider;123 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}124 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}125}126127pub use preimage_provider::PreimageProviderAndMaybeRecipient;128129pub(crate) trait MarginalWeightInfo: WeightInfo {130 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {131 match (periodic, named, resolved) {132 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),133 (_, true, None) => {134 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)135 }136 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),137 (false, true, Some(false)) => {138 Self::on_initialize_named(2) - Self::on_initialize_named(1)139 }140 (true, false, Some(false)) => {141 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)142 }143 (true, true, Some(false)) => {144 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)145 }146 (false, false, Some(true)) => {147 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)148 }149 (false, true, Some(true)) => {150 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)151 }152 (true, false, Some(true)) => {153 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)154 }155 (true, true, Some(true)) => {156 Self::on_initialize_periodic_named_resolved(2)157 - Self::on_initialize_periodic_named_resolved(1)158 }159 }160 }161}162impl<T: WeightInfo> MarginalWeightInfo for T {}163164#[frame_support::pallet]165pub mod pallet {166 use super::*;167 use frame_support::{168 dispatch::PostDispatchInfo,169 pallet_prelude::*,170 traits::{schedule::LookupError, PreimageProvider},171 };172 use frame_system::pallet_prelude::*;173174 /// The current storage version.175 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);176177 #[pallet::pallet]178 #[pallet::generate_store(pub(super) trait Store)]179 #[pallet::storage_version(STORAGE_VERSION)]180 #[pallet::without_storage_info]181 pub struct Pallet<T>(_);182183 /// `system::Config` should always be included in our implied traits.184 #[pallet::config]185 pub trait Config: frame_system::Config {186 /// The overarching event type.187 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;188189 /// The aggregated origin which the dispatch will take.190 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>191 + From<Self::PalletsOrigin>192 + IsType<<Self as system::Config>::Origin>;193194 /// The caller origin, overarching type of all pallets origins.195 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;196197 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;198199 /// The aggregated call type.200 type Call: Parameter201 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>202 + GetDispatchInfo203 + From<system::Call<Self>>;204205 /// The maximum weight that may be scheduled per block for any dispatchables of less206 /// priority than `schedule::HARD_DEADLINE`.207 #[pallet::constant]208 type MaximumWeight: Get<Weight>;209210 /// Required origin to schedule or cancel calls.211 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;212213 /// Compare the privileges of origins.214 ///215 /// This will be used when canceling a task, to ensure that the origin that tries216 /// to cancel has greater or equal privileges as the origin that created the scheduled task.217 ///218 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can219 /// be used. This will only check if two given origins are equal.220 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;221222 /// The maximum number of scheduled calls in the queue for a single block.223 /// Not strictly enforced, but used for weight estimation.224 #[pallet::constant]225 type MaxScheduledPerBlock: Get<u32>;226227 /// Weight information for extrinsics in this pallet.228 type WeightInfo: WeightInfo;229230 /// The preimage provider with which we look up call hashes to get the call.231 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;232233 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.234 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;235236 /// Sponsoring function.237 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;238239 /// The helper type used for custom transaction fee logic.240 type CallExecutor: DispatchCall<Self, H160>;241 }242243 /// A Scheduler-Runtime interface for finer payment handling.244 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {245 fn reserve_balance(246 id: ScheduledId,247 sponsor: <T as frame_system::Config>::AccountId,248 call: <T as Config>::Call,249 count: u32,250 ) -> Result<(), DispatchError>;251252 fn pay_for_call(253 id: ScheduledId,254 sponsor: <T as frame_system::Config>::AccountId,255 call: <T as Config>::Call,256 ) -> Result<u128, DispatchError>;257258 /// Resolve the call dispatch, including any post-dispatch operations.259 fn dispatch_call(260 signer: T::AccountId,261 function: <T as Config>::Call,262 ) -> Result<263 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,264 TransactionValidityError,265 >;266267 fn cancel_reserve(268 id: ScheduledId,269 sponsor: <T as frame_system::Config>::AccountId,270 ) -> Result<u128, DispatchError>;271 }272273 /// Items to be executed, indexed by the block number that they should be executed on.274 #[pallet::storage]275 pub type Agenda<T: Config> =276 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;277278 /// Lookup from identity to the block number and index of the task.279 #[pallet::storage]280 pub(crate) type Lookup<T: Config> =281 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;282283 /// Events type.284 #[pallet::event]285 #[pallet::generate_deposit(pub(super) fn deposit_event)]286 pub enum Event<T: Config> {287 /// Scheduled some task.288 Scheduled { when: T::BlockNumber, index: u32 },289 /// Canceled some task.290 Canceled { when: T::BlockNumber, index: u32 },291 /// Dispatched some task.292 Dispatched {293 task: TaskAddress<T::BlockNumber>,294 id: Option<ScheduledId>,295 result: DispatchResult,296 },297 /// The call for the provided hash was not found so the task has been aborted.298 CallLookupFailed {299 task: TaskAddress<T::BlockNumber>,300 id: Option<ScheduledId>,301 error: LookupError,302 },303 }304305 #[pallet::error]306 pub enum Error<T> {307 /// Failed to schedule a call308 FailedToSchedule,309 /// Cannot find the scheduled call.310 NotFound,311 /// Given target block number is in the past.312 TargetBlockNumberInPast,313 /// Reschedule failed because it does not change scheduled time.314 RescheduleNoChange,315 }316317 #[pallet::hooks]318 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {319 /// Execute the scheduled calls320 fn on_initialize(now: T::BlockNumber) -> Weight {321 let limit = T::MaximumWeight::get();322323 let mut queued = Agenda::<T>::take(now)324 .into_iter()325 .enumerate()326 .filter_map(|(index, s)| Some((index as u32, s?)))327 .collect::<Vec<_>>();328329 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {330 log::warn!(331 target: "runtime::scheduler",332 "Warning: This block has more items queued in Scheduler than \333 expected from the runtime configuration. An update might be needed."334 );335 }336337 queued.sort_by_key(|(_, s)| s.priority);338339 let next = now + One::one();340341 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);342 for (order, (index, mut s)) in queued.into_iter().enumerate() {343 let named = if let Some(ref id) = s.maybe_id {344 Lookup::<T>::remove(id);345 true346 } else {347 false348 };349350 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();351 s.call = call;352353 let resolved = if let Some(completed) = maybe_completed {354 T::PreimageProvider::unrequest_preimage(&completed);355 true356 } else {357 false358 };359 let call = match s.call.as_value().cloned() {360 Some(c) => c,361 None => {362 // Preimage not available - postpone until some block.363 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));364 if let Some(delay) = T::NoPreimagePostponement::get() {365 let until = now.saturating_add(delay);366 if let Some(ref id) = s.maybe_id {367 let index = Agenda::<T>::decode_len(until).unwrap_or(0);368 Lookup::<T>::insert(id, (until, index as u32));369 }370 Agenda::<T>::append(until, Some(s));371 }372 continue;373 }374 };375376 let periodic = s.maybe_periodic.is_some();377 let call_weight = call.get_dispatch_info().weight;378 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));379 let origin =380 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())381 .into();382 if ensure_signed(origin).is_ok() {383 // Weights of Signed dispatches expect their signing account to be whitelisted.384 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));385 }386387 // We allow a scheduled call if any is true:388 // - It's priority is `HARD_DEADLINE`389 // - It does not push the weight past the limit.390 // - It is the first item in the schedule391 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;392 let test_weight = total_weight393 .saturating_add(call_weight)394 .saturating_add(item_weight);395 if !hard_deadline && order > 0 && test_weight > limit {396 // Cannot be scheduled this block - postpone until next.397 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));398 if let Some(ref id) = s.maybe_id {399 // NOTE: We could reasonably not do this (in which case there would be one400 // block where the named and delayed item could not be referenced by name),401 // but we will do it anyway since it should be mostly free in terms of402 // weight and it is slightly cleaner.403 let index = Agenda::<T>::decode_len(next).unwrap_or(0);404 Lookup::<T>::insert(id, (next, index as u32));405 }406 Agenda::<T>::append(next, Some(s));407 continue;408 }409410 let sender = ensure_signed(411 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())412 .into(),413 )414 .unwrap();415416 // // if call have id it was be reserved417 // if s.maybe_id.is_some() {418 // let _ = T::CallExecutor::pay_for_call(419 // s.maybe_id.unwrap(),420 // sender.clone(),421 // call.clone(),422 // );423 // }424425 let r = T::CallExecutor::dispatch_call(sender, call.clone());426427 let mut actual_call_weight: Weight = item_weight;428 let result: Result<_, DispatchError> = match r {429 Ok(o) => match o {430 Ok(di) => {431 actual_call_weight = di.actual_weight.unwrap_or(item_weight);432 Ok(())433 }434 Err(err) => Err(err.error),435 },436 Err(_) => {437 log::error!(438 target: "runtime::scheduler",439 "Warning: Scheduler has failed to execute a post-dispatch transaction. \440 This block might have become invalid.");441 Err(DispatchError::CannotLookup)442 } // todo possibly force a skip/return here, do something with the error443 };444445 total_weight.saturating_accrue(item_weight);446 total_weight.saturating_accrue(actual_call_weight);447448 Self::deposit_event(Event::Dispatched {449 task: (now, index),450 id: s.maybe_id.clone(),451 result,452 });453454 if let &Some((period, count)) = &s.maybe_periodic {455 if count > 1 {456 s.maybe_periodic = Some((period, count - 1));457 } else {458 s.maybe_periodic = None;459 }460 let wake = now + period;461 // If scheduled is named, place its information in `Lookup`462 if let Some(ref id) = s.maybe_id {463 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);464 Lookup::<T>::insert(id, (wake, wake_index as u32));465 }466 Agenda::<T>::append(wake, Some(s));467 }468 }469 0470 //total_weight471 }472 }473474 #[pallet::call]475 impl<T: Config> Pallet<T> {476 /// Schedule a named task.477 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]478 pub fn schedule_named(479 origin: OriginFor<T>,480 id: ScheduledId,481 when: T::BlockNumber,482 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,483 priority: schedule::Priority,484 call: Box<CallOrHashOf<T>>,485 ) -> DispatchResult {486 T::ScheduleOrigin::ensure_origin(origin.clone())?;487 let origin = <T as Config>::Origin::from(origin);488 Self::do_schedule_named(489 id,490 DispatchTime::At(when),491 maybe_periodic,492 priority,493 origin.caller().clone(),494 *call,495 )?;496 Ok(())497 }498499 /// Cancel a named scheduled task.500 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]501 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {502 T::ScheduleOrigin::ensure_origin(origin.clone())?;503 let origin = <T as Config>::Origin::from(origin);504 Self::do_cancel_named(Some(origin.caller().clone()), id)?;505 Ok(())506 }507508 /// Schedule a named task after a delay.509 ///510 /// # <weight>511 /// Same as [`schedule_named`](Self::schedule_named).512 /// # </weight>513 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]514 pub fn schedule_named_after(515 origin: OriginFor<T>,516 id: ScheduledId,517 after: T::BlockNumber,518 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,519 priority: schedule::Priority,520 call: Box<CallOrHashOf<T>>,521 ) -> DispatchResult {522 T::ScheduleOrigin::ensure_origin(origin.clone())?;523 let origin = <T as Config>::Origin::from(origin);524 Self::do_schedule_named(525 id,526 DispatchTime::After(after),527 maybe_periodic,528 priority,529 origin.caller().clone(),530 *call,531 )?;532 Ok(())533 }534 }535}536537impl<T: Config> Pallet<T> {538 #[cfg(feature = "try-runtime")]539 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {540 Ok(())541 }542543 #[cfg(feature = "try-runtime")]544 pub fn post_migrate_to_v3() -> Result<(), &'static str> {545 use frame_support::dispatch::GetStorageVersion;546547 assert!(Self::current_storage_version() == 3);548 for k in Agenda::<T>::iter_keys() {549 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;550 }551 Ok(())552 }553554 /// Helper to migrate scheduler when the pallet origin type has changed.555 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {556 Agenda::<T>::translate::<557 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,558 _,559 >(|_, agenda| {560 Some(561 agenda562 .into_iter()563 .map(|schedule| {564 schedule.map(|schedule| Scheduled {565 maybe_id: schedule.maybe_id,566 priority: schedule.priority,567 call: schedule.call,568 maybe_periodic: schedule.maybe_periodic,569 origin: schedule.origin.into(),570 _phantom: Default::default(),571 })572 })573 .collect::<Vec<_>>(),574 )575 });576 }577578 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {579 let now = frame_system::Pallet::<T>::block_number();580581 let when = match when {582 DispatchTime::At(x) => x,583 // The current block has already completed it's scheduled tasks, so584 // Schedule the task at lest one block after this current block.585 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),586 };587588 if when <= now {589 return Err(Error::<T>::TargetBlockNumberInPast.into());590 }591592 Ok(when)593 }594595 fn do_schedule(596 when: DispatchTime<T::BlockNumber>,597 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,598 priority: schedule::Priority,599 origin: T::PalletsOrigin,600 call: CallOrHashOf<T>,601 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {602 let when = Self::resolve_time(when)?;603 call.ensure_requested::<T::PreimageProvider>();604605 // sanitize maybe_periodic606 let maybe_periodic = maybe_periodic607 .filter(|p| p.1 > 1 && !p.0.is_zero())608 // Remove one from the number of repetitions since we will schedule one now.609 .map(|(p, c)| (p, c - 1));610 let s = Some(Scheduled {611 maybe_id: None,612 priority,613 call,614 maybe_periodic,615 origin,616 _phantom: PhantomData::<T::AccountId>::default(),617 });618 Agenda::<T>::append(when, s);619 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;620 Self::deposit_event(Event::Scheduled { when, index });621622 Ok((when, index))623 }624625 fn do_cancel(626 origin: Option<T::PalletsOrigin>,627 (when, index): TaskAddress<T::BlockNumber>,628 ) -> Result<(), DispatchError> {629 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {630 agenda.get_mut(index as usize).map_or(631 Ok(None),632 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {633 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {634 if matches!(635 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),636 Some(Ordering::Less) | None637 ) {638 return Err(BadOrigin.into());639 }640 };641 Ok(s.take())642 },643 )644 })?;645 if let Some(s) = scheduled {646 s.call.ensure_unrequested::<T::PreimageProvider>();647 if let Some(id) = s.maybe_id {648 Lookup::<T>::remove(id);649 }650 Self::deposit_event(Event::Canceled { when, index });651 Ok(())652 } else {653 Err(Error::<T>::NotFound)?654 }655 }656657 fn do_reschedule(658 (when, index): TaskAddress<T::BlockNumber>,659 new_time: DispatchTime<T::BlockNumber>,660 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {661 let new_time = Self::resolve_time(new_time)?;662663 if new_time == when {664 return Err(Error::<T>::RescheduleNoChange.into());665 }666667 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {668 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;669 let task = task.take().ok_or(Error::<T>::NotFound)?;670 Agenda::<T>::append(new_time, Some(task));671 Ok(())672 })?;673674 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;675 Self::deposit_event(Event::Canceled { when, index });676 Self::deposit_event(Event::Scheduled {677 when: new_time,678 index: new_index,679 });680681 Ok((new_time, new_index))682 }683684 fn do_schedule_named(685 id: ScheduledId,686 when: DispatchTime<T::BlockNumber>,687 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,688 priority: schedule::Priority,689 origin: T::PalletsOrigin,690 call: CallOrHashOf<T>,691 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {692 // ensure id it is unique693 if Lookup::<T>::contains_key(&id) {694 return Err(Error::<T>::FailedToSchedule)?;695 }696697 let when = Self::resolve_time(when)?;698699 call.ensure_requested::<T::PreimageProvider>();700701 // sanitize maybe_periodic702 let maybe_periodic = maybe_periodic703 .filter(|p| p.1 > 1 && !p.0.is_zero())704 // Remove one from the number of repetitions since we will schedule one now.705 .map(|(p, c)| (p, c - 1));706707 let s = Scheduled {708 maybe_id: Some(id.clone()),709 priority,710 call: call.clone(),711 maybe_periodic,712 origin: origin.clone(),713 _phantom: Default::default(),714 };715716 // reserve balance for periodic execution717 // let sender =718 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;719 // let repeats = match maybe_periodic {720 // Some(p) => p.1,721 // None => 1,722 // };723 // let _ = T::CallExecutor::reserve_balance(724 // id.clone(),725 // sender,726 // call.as_value().unwrap().clone(),727 // repeats,728 // );729730 Agenda::<T>::append(when, Some(s));731 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;732 let address = (when, index);733 Lookup::<T>::insert(&id, &address);734 Self::deposit_event(Event::Scheduled { when, index });735736 Ok(address)737 }738739 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {740 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {741 if let Some((when, index)) = lookup.take() {742 let i = index as usize;743 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {744 if let Some(s) = agenda.get_mut(i) {745 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {746 if matches!(747 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),748 Some(Ordering::Less) | None749 ) {750 return Err(BadOrigin.into());751 }752 // release balance reserve753 // let sender = ensure_signed(754 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(755 // origin.unwrap(),756 // )757 // .into(),758 // )?;759 // let _ = T::CallExecutor::cancel_reserve(id, sender);760761 s.call.ensure_unrequested::<T::PreimageProvider>();762 }763 *s = None;764 }765 Ok(())766 })?;767768 Self::deposit_event(Event::Canceled { when, index });769 Ok(())770 } else {771 Err(Error::<T>::NotFound)?772 }773 })774 }775776 fn do_reschedule_named(777 id: ScheduledId,778 new_time: DispatchTime<T::BlockNumber>,779 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {780 let new_time = Self::resolve_time(new_time)?;781782 Lookup::<T>::try_mutate_exists(783 id,784 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {785 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;786787 if new_time == when {788 return Err(Error::<T>::RescheduleNoChange.into());789 }790791 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {792 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;793 let task = task.take().ok_or(Error::<T>::NotFound)?;794 Agenda::<T>::append(new_time, Some(task));795796 Ok(())797 })?;798799 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;800 Self::deposit_event(Event::Canceled { when, index });801 Self::deposit_event(Event::Scheduled {802 when: new_time,803 index: new_index,804 });805806 *lookup = Some((new_time, new_index));807808 Ok((new_time, new_index))809 },810 )811 }812}813814impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>815 for Pallet<T>816{817 type Address = TaskAddress<T::BlockNumber>;818 type Hash = T::Hash;819820 fn schedule(821 when: DispatchTime<T::BlockNumber>,822 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,823 priority: schedule::Priority,824 origin: T::PalletsOrigin,825 call: CallOrHashOf<T>,826 ) -> Result<Self::Address, DispatchError> {827 Self::do_schedule(when, maybe_periodic, priority, origin, call)828 }829830 fn cancel((when, index): Self::Address) -> Result<(), ()> {831 Self::do_cancel(None, (when, index)).map_err(|_| ())832 }833834 fn reschedule(835 address: Self::Address,836 when: DispatchTime<T::BlockNumber>,837 ) -> Result<Self::Address, DispatchError> {838 Self::do_reschedule(address, when)839 }840841 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {842 Agenda::<T>::get(when)843 .get(index as usize)844 .ok_or(())845 .map(|_| when)846 }847}848849impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>850 for Pallet<T>851{852 type Address = TaskAddress<T::BlockNumber>;853 type Hash = T::Hash;854855 fn schedule_named(856 id: Vec<u8>,857 when: DispatchTime<T::BlockNumber>,858 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,859 priority: schedule::Priority,860 origin: T::PalletsOrigin,861 call: CallOrHashOf<T>,862 ) -> Result<Self::Address, ()> {863 let inner_id: ScheduledId = id864 .try_into()865 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);866 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)867 .map_err(|_| ())868 }869870 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {871 let inner_id: ScheduledId = id872 .try_into()873 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);874 Self::do_cancel_named(None, inner_id).map_err(|_| ())875 }876877 fn reschedule_named(878 id: Vec<u8>,879 when: DispatchTime<T::BlockNumber>,880 ) -> Result<Self::Address, DispatchError> {881 let inner_id: ScheduledId = id882 .try_into()883 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);884 Self::do_reschedule_named(inner_id, when)885 }886887 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {888 let inner_id: ScheduledId = id889 .try_into()890 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);891 Lookup::<T>::get(inner_id)892 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))893 .ok_or(())894 }895}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Schedulerdo_reschedule36//!37//! This Pallet exposes capabilities for scheduling dispatches to occur at a38//! specified block number or at a specified period. These scheduled dispatches39//! may be named or anonymous and may be canceled.40//!41//! **NOTE:** The scheduled calls will be dispatched with the default filter42//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin43//! except root which will get no filter. And not the filter contained in origin44//! use to call `fn schedule`.45//!46//! If a call is scheduled using proxy or whatever mecanism which adds filter,47//! then those filter will not be used when dispatching the schedule call.48//!49//! ## Interface50//!51//! ### Dispatchable Functions52//!53//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and54//! with a specified priority.55//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.56//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter57//! that can be used for identification.58//! * `cancel_named` - the named complement to the cancel function.5960// Ensure we're `no_std` when compiling for Wasm.61#![cfg_attr(not(feature = "std"), no_std)]6263#[cfg(feature = "runtime-benchmarks")]64mod benchmarking;6566pub mod weights;6768use sp_core::H160;69use codec::{Codec, Decode, Encode};70use frame_system::{self as system, ensure_signed};71pub use pallet::*;72use scale_info::TypeInfo;73use sp_runtime::{74 traits::{BadOrigin, One, Saturating, Zero},75 RuntimeDebug, DispatchErrorWithPostInfo,76};77use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7879use frame_support::{80 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},81 traits::{82 schedule::{self, DispatchTime, MaybeHashed},83 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,84 StorageVersion,85 },86 weights::{GetDispatchInfo, Weight},87};8889pub use weights::WeightInfo;9091/// Just a simple index for naming period tasks.92pub type PeriodicIndex = u32;93/// The location of a scheduled task that can be used to remove it.94pub type TaskAddress<BlockNumber> = (BlockNumber, u32);95pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9697type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];98pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;99100/// Information regarding an item to be executed in the future.101#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]102#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]103pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {104 /// The unique identity for this task, if there is one.105 maybe_id: Option<ScheduledId>,106 /// This task's priority.107 priority: schedule::Priority,108 /// The call to be dispatched.109 call: Call,110 /// If the call is periodic, then this points to the information concerning that.111 maybe_periodic: Option<schedule::Period<BlockNumber>>,112 /// The origin to dispatch the call.113 origin: PalletsOrigin,114 _phantom: PhantomData<AccountId>,115}116117pub type ScheduledV3Of<T> = ScheduledV3<118 CallOrHashOf<T>,119 <T as frame_system::Config>::BlockNumber,120 <T as Config>::PalletsOrigin,121 <T as frame_system::Config>::AccountId,122>;123124pub type ScheduledOf<T> = ScheduledV3Of<T>;125126/// The current version of Scheduled struct.127pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =128 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;129130#[cfg(feature = "runtime-benchmarks")]131mod preimage_provider {132 use frame_support::traits::PreimageRecipient;133 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}134 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}135}136137#[cfg(not(feature = "runtime-benchmarks"))]138mod preimage_provider {139 use frame_support::traits::PreimageProvider;140 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}141 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}142}143144pub use preimage_provider::PreimageProviderAndMaybeRecipient;145146pub(crate) trait MarginalWeightInfo: WeightInfo {147 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {148 match (periodic, named, resolved) {149 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),150 (_, true, None) => {151 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)152 }153 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),154 (false, true, Some(false)) => {155 Self::on_initialize_named(2) - Self::on_initialize_named(1)156 }157 (true, false, Some(false)) => {158 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)159 }160 (true, true, Some(false)) => {161 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)162 }163 (false, false, Some(true)) => {164 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)165 }166 (false, true, Some(true)) => {167 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)168 }169 (true, false, Some(true)) => {170 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)171 }172 (true, true, Some(true)) => {173 Self::on_initialize_periodic_named_resolved(2)174 - Self::on_initialize_periodic_named_resolved(1)175 }176 }177 }178}179impl<T: WeightInfo> MarginalWeightInfo for T {}180181#[frame_support::pallet]182pub mod pallet {183 use super::*;184 use frame_support::{185 dispatch::PostDispatchInfo,186 pallet_prelude::*,187 traits::{schedule::LookupError, PreimageProvider},188 };189 use frame_system::pallet_prelude::*;190191 /// The current storage version.192 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);193194 #[pallet::pallet]195 #[pallet::generate_store(pub(super) trait Store)]196 #[pallet::storage_version(STORAGE_VERSION)]197 #[pallet::without_storage_info]198 pub struct Pallet<T>(_);199200 /// `system::Config` should always be included in our implied traits.201 #[pallet::config]202 pub trait Config: frame_system::Config {203 /// The overarching event type.204 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;205206 /// The aggregated origin which the dispatch will take.207 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>208 + From<Self::PalletsOrigin>209 + IsType<<Self as system::Config>::Origin>;210211 /// The caller origin, overarching type of all pallets origins.212 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;213214 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;215216 /// The aggregated call type.217 type Call: Parameter218 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>219 + GetDispatchInfo220 + From<system::Call<Self>>;221222 /// The maximum weight that may be scheduled per block for any dispatchables of less223 /// priority than `schedule::HARD_DEADLINE`.224 #[pallet::constant]225 type MaximumWeight: Get<Weight>;226227 /// Required origin to schedule or cancel calls.228 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;229230 /// Compare the privileges of origins.231 ///232 /// This will be used when canceling a task, to ensure that the origin that tries233 /// to cancel has greater or equal privileges as the origin that created the scheduled task.234 ///235 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can236 /// be used. This will only check if two given origins are equal.237 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;238239 /// The maximum number of scheduled calls in the queue for a single block.240 /// Not strictly enforced, but used for weight estimation.241 #[pallet::constant]242 type MaxScheduledPerBlock: Get<u32>;243244 /// Weight information for extrinsics in this pallet.245 type WeightInfo: WeightInfo;246247 /// The preimage provider with which we look up call hashes to get the call.248 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;249250 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.251 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;252253 /// Sponsoring function.254 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;255256 /// The helper type used for custom transaction fee logic.257 type CallExecutor: DispatchCall<Self, H160>;258 }259260 /// A Scheduler-Runtime interface for finer payment handling.261 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {262 fn reserve_balance(263 id: ScheduledId,264 sponsor: <T as frame_system::Config>::AccountId,265 call: <T as Config>::Call,266 count: u32,267 ) -> Result<(), DispatchError>;268269 fn pay_for_call(270 id: ScheduledId,271 sponsor: <T as frame_system::Config>::AccountId,272 call: <T as Config>::Call,273 ) -> Result<u128, DispatchError>;274275 /// Resolve the call dispatch, including any post-dispatch operations.276 fn dispatch_call(277 signer: T::AccountId,278 function: <T as Config>::Call,279 ) -> Result<280 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,281 TransactionValidityError,282 >;283284 fn cancel_reserve(285 id: ScheduledId,286 sponsor: <T as frame_system::Config>::AccountId,287 ) -> Result<u128, DispatchError>;288 }289290 /// Items to be executed, indexed by the block number that they should be executed on.291 #[pallet::storage]292 pub type Agenda<T: Config> =293 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;294295 /// Lookup from identity to the block number and index of the task.296 #[pallet::storage]297 pub(crate) type Lookup<T: Config> =298 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;299300 /// Events type.301 #[pallet::event]302 #[pallet::generate_deposit(pub(super) fn deposit_event)]303 pub enum Event<T: Config> {304 /// Scheduled some task.305 Scheduled { when: T::BlockNumber, index: u32 },306 /// Canceled some task.307 Canceled { when: T::BlockNumber, index: u32 },308 /// Dispatched some task.309 Dispatched {310 task: TaskAddress<T::BlockNumber>,311 id: Option<ScheduledId>,312 result: DispatchResult,313 },314 /// The call for the provided hash was not found so the task has been aborted.315 CallLookupFailed {316 task: TaskAddress<T::BlockNumber>,317 id: Option<ScheduledId>,318 error: LookupError,319 },320 }321322 #[pallet::error]323 pub enum Error<T> {324 /// Failed to schedule a call325 FailedToSchedule,326 /// Cannot find the scheduled call.327 NotFound,328 /// Given target block number is in the past.329 TargetBlockNumberInPast,330 /// Reschedule failed because it does not change scheduled time.331 RescheduleNoChange,332 }333334 #[pallet::hooks]335 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {336 /// Execute the scheduled calls337 fn on_initialize(now: T::BlockNumber) -> Weight {338 let limit = T::MaximumWeight::get();339340 let mut queued = Agenda::<T>::take(now)341 .into_iter()342 .enumerate()343 .filter_map(|(index, s)| Some((index as u32, s?)))344 .collect::<Vec<_>>();345346 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {347 log::warn!(348 target: "runtime::scheduler",349 "Warning: This block has more items queued in Scheduler than \350 expected from the runtime configuration. An update might be needed."351 );352 }353354 queued.sort_by_key(|(_, s)| s.priority);355356 let next = now + One::one();357358 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);359 for (order, (index, mut s)) in queued.into_iter().enumerate() {360 let named = if let Some(ref id) = s.maybe_id {361 Lookup::<T>::remove(id);362 true363 } else {364 false365 };366367 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();368 s.call = call;369370 let resolved = if let Some(completed) = maybe_completed {371 T::PreimageProvider::unrequest_preimage(&completed);372 true373 } else {374 false375 };376 let call = match s.call.as_value().cloned() {377 Some(c) => c,378 None => {379 // Preimage not available - postpone until some block.380 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));381 if let Some(delay) = T::NoPreimagePostponement::get() {382 let until = now.saturating_add(delay);383 if let Some(ref id) = s.maybe_id {384 let index = Agenda::<T>::decode_len(until).unwrap_or(0);385 Lookup::<T>::insert(id, (until, index as u32));386 }387 Agenda::<T>::append(until, Some(s));388 }389 continue;390 }391 };392393 let periodic = s.maybe_periodic.is_some();394 let call_weight = call.get_dispatch_info().weight;395 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));396 let origin =397 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())398 .into();399 if ensure_signed(origin).is_ok() {400 // Weights of Signed dispatches expect their signing account to be whitelisted.401 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));402 }403404 // We allow a scheduled call if any is true:405 // - It's priority is `HARD_DEADLINE`406 // - It does not push the weight past the limit.407 // - It is the first item in the schedule408 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;409 let test_weight = total_weight410 .saturating_add(call_weight)411 .saturating_add(item_weight);412 if !hard_deadline && order > 0 && test_weight > limit {413 // Cannot be scheduled this block - postpone until next.414 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));415 if let Some(ref id) = s.maybe_id {416 // NOTE: We could reasonably not do this (in which case there would be one417 // block where the named and delayed item could not be referenced by name),418 // but we will do it anyway since it should be mostly free in terms of419 // weight and it is slightly cleaner.420 let index = Agenda::<T>::decode_len(next).unwrap_or(0);421 Lookup::<T>::insert(id, (next, index as u32));422 }423 Agenda::<T>::append(next, Some(s));424 continue;425 }426427 let sender = ensure_signed(428 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())429 .into(),430 )431 .unwrap();432433 // // if call have id it was be reserved434 // if s.maybe_id.is_some() {435 // let _ = T::CallExecutor::pay_for_call(436 // s.maybe_id.unwrap(),437 // sender.clone(),438 // call.clone(),439 // );440 // }441442 let r = T::CallExecutor::dispatch_call(sender, call.clone());443444 let mut actual_call_weight: Weight = item_weight;445 let result: Result<_, DispatchError> = match r {446 Ok(o) => match o {447 Ok(di) => {448 actual_call_weight = di.actual_weight.unwrap_or(item_weight);449 Ok(())450 }451 Err(err) => Err(err.error),452 },453 Err(_) => {454 log::error!(455 target: "runtime::scheduler",456 "Warning: Scheduler has failed to execute a post-dispatch transaction. \457 This block might have become invalid.");458 Err(DispatchError::CannotLookup)459 } // todo possibly force a skip/return here, do something with the error460 };461462 total_weight.saturating_accrue(item_weight);463 total_weight.saturating_accrue(actual_call_weight);464465 Self::deposit_event(Event::Dispatched {466 task: (now, index),467 id: s.maybe_id.clone(),468 result,469 });470471 if let &Some((period, count)) = &s.maybe_periodic {472 if count > 1 {473 s.maybe_periodic = Some((period, count - 1));474 } else {475 s.maybe_periodic = None;476 }477 let wake = now + period;478 // If scheduled is named, place its information in `Lookup`479 if let Some(ref id) = s.maybe_id {480 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);481 Lookup::<T>::insert(id, (wake, wake_index as u32));482 }483 Agenda::<T>::append(wake, Some(s));484 }485 }486 0487 //total_weight488 }489 }490491 #[pallet::call]492 impl<T: Config> Pallet<T> {493 /// Schedule a named task.494 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]495 pub fn schedule_named(496 origin: OriginFor<T>,497 id: ScheduledId,498 when: T::BlockNumber,499 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500 priority: schedule::Priority,501 call: Box<CallOrHashOf<T>>,502 ) -> DispatchResult {503 T::ScheduleOrigin::ensure_origin(origin.clone())?;504 let origin = <T as Config>::Origin::from(origin);505 Self::do_schedule_named(506 id,507 DispatchTime::At(when),508 maybe_periodic,509 priority,510 origin.caller().clone(),511 *call,512 )?;513 Ok(())514 }515516 /// Cancel a named scheduled task.517 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]518 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {519 T::ScheduleOrigin::ensure_origin(origin.clone())?;520 let origin = <T as Config>::Origin::from(origin);521 Self::do_cancel_named(Some(origin.caller().clone()), id)?;522 Ok(())523 }524525 /// Schedule a named task after a delay.526 ///527 /// # <weight>528 /// Same as [`schedule_named`](Self::schedule_named).529 /// # </weight>530 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]531 pub fn schedule_named_after(532 origin: OriginFor<T>,533 id: ScheduledId,534 after: T::BlockNumber,535 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,536 priority: schedule::Priority,537 call: Box<CallOrHashOf<T>>,538 ) -> DispatchResult {539 T::ScheduleOrigin::ensure_origin(origin.clone())?;540 let origin = <T as Config>::Origin::from(origin);541 Self::do_schedule_named(542 id,543 DispatchTime::After(after),544 maybe_periodic,545 priority,546 origin.caller().clone(),547 *call,548 )?;549 Ok(())550 }551 }552}553554impl<T: Config> Pallet<T> {555 #[cfg(feature = "try-runtime")]556 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {557 Ok(())558 }559560 #[cfg(feature = "try-runtime")]561 pub fn post_migrate_to_v3() -> Result<(), &'static str> {562 use frame_support::dispatch::GetStorageVersion;563564 assert!(Self::current_storage_version() == 3);565 for k in Agenda::<T>::iter_keys() {566 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;567 }568 Ok(())569 }570571 /// Helper to migrate scheduler when the pallet origin type has changed.572 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {573 Agenda::<T>::translate::<574 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,575 _,576 >(|_, agenda| {577 Some(578 agenda579 .into_iter()580 .map(|schedule| {581 schedule.map(|schedule| Scheduled {582 maybe_id: schedule.maybe_id,583 priority: schedule.priority,584 call: schedule.call,585 maybe_periodic: schedule.maybe_periodic,586 origin: schedule.origin.into(),587 _phantom: Default::default(),588 })589 })590 .collect::<Vec<_>>(),591 )592 });593 }594595 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {596 let now = frame_system::Pallet::<T>::block_number();597598 let when = match when {599 DispatchTime::At(x) => x,600 // The current block has already completed it's scheduled tasks, so601 // Schedule the task at lest one block after this current block.602 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),603 };604605 if when <= now {606 return Err(Error::<T>::TargetBlockNumberInPast.into());607 }608609 Ok(when)610 }611612 fn do_schedule(613 when: DispatchTime<T::BlockNumber>,614 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,615 priority: schedule::Priority,616 origin: T::PalletsOrigin,617 call: CallOrHashOf<T>,618 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {619 let when = Self::resolve_time(when)?;620 call.ensure_requested::<T::PreimageProvider>();621622 // sanitize maybe_periodic623 let maybe_periodic = maybe_periodic624 .filter(|p| p.1 > 1 && !p.0.is_zero())625 // Remove one from the number of repetitions since we will schedule one now.626 .map(|(p, c)| (p, c - 1));627 let s = Some(Scheduled {628 maybe_id: None,629 priority,630 call,631 maybe_periodic,632 origin,633 _phantom: PhantomData::<T::AccountId>::default(),634 });635 Agenda::<T>::append(when, s);636 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;637 Self::deposit_event(Event::Scheduled { when, index });638639 Ok((when, index))640 }641642 fn do_cancel(643 origin: Option<T::PalletsOrigin>,644 (when, index): TaskAddress<T::BlockNumber>,645 ) -> Result<(), DispatchError> {646 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {647 agenda.get_mut(index as usize).map_or(648 Ok(None),649 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {650 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {651 if matches!(652 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),653 Some(Ordering::Less) | None654 ) {655 return Err(BadOrigin.into());656 }657 };658 Ok(s.take())659 },660 )661 })?;662 if let Some(s) = scheduled {663 s.call.ensure_unrequested::<T::PreimageProvider>();664 if let Some(id) = s.maybe_id {665 Lookup::<T>::remove(id);666 }667 Self::deposit_event(Event::Canceled { when, index });668 Ok(())669 } else {670 Err(Error::<T>::NotFound)?671 }672 }673674 fn do_reschedule(675 (when, index): TaskAddress<T::BlockNumber>,676 new_time: DispatchTime<T::BlockNumber>,677 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {678 let new_time = Self::resolve_time(new_time)?;679680 if new_time == when {681 return Err(Error::<T>::RescheduleNoChange.into());682 }683684 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {685 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;686 let task = task.take().ok_or(Error::<T>::NotFound)?;687 Agenda::<T>::append(new_time, Some(task));688 Ok(())689 })?;690691 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;692 Self::deposit_event(Event::Canceled { when, index });693 Self::deposit_event(Event::Scheduled {694 when: new_time,695 index: new_index,696 });697698 Ok((new_time, new_index))699 }700701 fn do_schedule_named(702 id: ScheduledId,703 when: DispatchTime<T::BlockNumber>,704 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,705 priority: schedule::Priority,706 origin: T::PalletsOrigin,707 call: CallOrHashOf<T>,708 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {709 // ensure id it is unique710 if Lookup::<T>::contains_key(&id) {711 return Err(Error::<T>::FailedToSchedule)?;712 }713714 let when = Self::resolve_time(when)?;715716 call.ensure_requested::<T::PreimageProvider>();717718 // sanitize maybe_periodic719 let maybe_periodic = maybe_periodic720 .filter(|p| p.1 > 1 && !p.0.is_zero())721 // Remove one from the number of repetitions since we will schedule one now.722 .map(|(p, c)| (p, c - 1));723724 let s = Scheduled {725 maybe_id: Some(id.clone()),726 priority,727 call: call.clone(),728 maybe_periodic,729 origin: origin.clone(),730 _phantom: Default::default(),731 };732733 // reserve balance for periodic execution734 // let sender =735 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;736 // let repeats = match maybe_periodic {737 // Some(p) => p.1,738 // None => 1,739 // };740 // let _ = T::CallExecutor::reserve_balance(741 // id.clone(),742 // sender,743 // call.as_value().unwrap().clone(),744 // repeats,745 // );746747 Agenda::<T>::append(when, Some(s));748 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;749 let address = (when, index);750 Lookup::<T>::insert(&id, &address);751 Self::deposit_event(Event::Scheduled { when, index });752753 Ok(address)754 }755756 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {757 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {758 if let Some((when, index)) = lookup.take() {759 let i = index as usize;760 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {761 if let Some(s) = agenda.get_mut(i) {762 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {763 if matches!(764 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),765 Some(Ordering::Less) | None766 ) {767 return Err(BadOrigin.into());768 }769 // release balance reserve770 // let sender = ensure_signed(771 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(772 // origin.unwrap(),773 // )774 // .into(),775 // )?;776 // let _ = T::CallExecutor::cancel_reserve(id, sender);777778 s.call.ensure_unrequested::<T::PreimageProvider>();779 }780 *s = None;781 }782 Ok(())783 })?;784785 Self::deposit_event(Event::Canceled { when, index });786 Ok(())787 } else {788 Err(Error::<T>::NotFound)?789 }790 })791 }792793 fn do_reschedule_named(794 id: ScheduledId,795 new_time: DispatchTime<T::BlockNumber>,796 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {797 let new_time = Self::resolve_time(new_time)?;798799 Lookup::<T>::try_mutate_exists(800 id,801 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {802 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;803804 if new_time == when {805 return Err(Error::<T>::RescheduleNoChange.into());806 }807808 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {809 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;810 let task = task.take().ok_or(Error::<T>::NotFound)?;811 Agenda::<T>::append(new_time, Some(task));812813 Ok(())814 })?;815816 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;817 Self::deposit_event(Event::Canceled { when, index });818 Self::deposit_event(Event::Scheduled {819 when: new_time,820 index: new_index,821 });822823 *lookup = Some((new_time, new_index));824825 Ok((new_time, new_index))826 },827 )828 }829}830831impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>832 for Pallet<T>833{834 type Address = TaskAddress<T::BlockNumber>;835 type Hash = T::Hash;836837 fn schedule(838 when: DispatchTime<T::BlockNumber>,839 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,840 priority: schedule::Priority,841 origin: T::PalletsOrigin,842 call: CallOrHashOf<T>,843 ) -> Result<Self::Address, DispatchError> {844 Self::do_schedule(when, maybe_periodic, priority, origin, call)845 }846847 fn cancel((when, index): Self::Address) -> Result<(), ()> {848 Self::do_cancel(None, (when, index)).map_err(|_| ())849 }850851 fn reschedule(852 address: Self::Address,853 when: DispatchTime<T::BlockNumber>,854 ) -> Result<Self::Address, DispatchError> {855 Self::do_reschedule(address, when)856 }857858 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {859 Agenda::<T>::get(when)860 .get(index as usize)861 .ok_or(())862 .map(|_| when)863 }864}865866impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>867 for Pallet<T>868{869 type Address = TaskAddress<T::BlockNumber>;870 type Hash = T::Hash;871872 fn schedule_named(873 id: Vec<u8>,874 when: DispatchTime<T::BlockNumber>,875 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,876 priority: schedule::Priority,877 origin: T::PalletsOrigin,878 call: CallOrHashOf<T>,879 ) -> Result<Self::Address, ()> {880 let inner_id: ScheduledId = id881 .try_into()882 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);883 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)884 .map_err(|_| ())885 }886887 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {888 let inner_id: ScheduledId = id889 .try_into()890 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);891 Self::do_cancel_named(None, inner_id).map_err(|_| ())892 }893894 fn reschedule_named(895 id: Vec<u8>,896 when: DispatchTime<T::BlockNumber>,897 ) -> Result<Self::Address, DispatchError> {898 let inner_id: ScheduledId = id899 .try_into()900 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);901 Self::do_reschedule_named(inner_id, when)902 }903904 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {905 let inner_id: ScheduledId = id906 .try_into()907 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);908 Lookup::<T>::get(inner_id)909 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))910 .ok_or(())911 }912}tests/flipper-src/lib.rsdiffbeforeafterboth--- a/tests/flipper-src/lib.rs
+++ b/tests/flipper-src/lib.rs
@@ -14,7 +14,7 @@
// 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
+// Original License
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
tests/ink-types-node-runtime/src/calls.rsdiffbeforeafterboth--- a/tests/ink-types-node-runtime/src/calls.rs
+++ b/tests/ink-types-node-runtime/src/calls.rs
@@ -14,7 +14,7 @@
// 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
+// Original License
// Copyright 2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
tests/ink-types-node-runtime/src/lib.rsdiffbeforeafterboth--- a/tests/ink-types-node-runtime/src/lib.rs
+++ b/tests/ink-types-node-runtime/src/lib.rs
@@ -14,7 +14,7 @@
// 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
+// Original License
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
tests/loadtester-src/lib.rsdiffbeforeafterboth--- a/tests/loadtester-src/lib.rs
+++ b/tests/loadtester-src/lib.rs
@@ -14,6 +14,7 @@
// 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
#![cfg_attr(not(feature = "std"), no_std)]
use ink_lang as ink;
tests/src/xcmTransfer.test.tsdiffbeforeafterboth--- a/tests/src/xcmTransfer.test.ts
+++ b/tests/src/xcmTransfer.test.ts
@@ -33,7 +33,7 @@
const KARURA_CHAIN = 2000;
const KARURA_PORT = '9946';
-describe('Integration test: Exchanging OPL with Karura', () => {
+describe('Integration test: Exchanging QTZ with Karura', () => {
let alice: IKeyringPair;
before(async () => {
@@ -59,8 +59,8 @@
const metadata =
{
- name: 'OPL',
- symbol: 'OPL',
+ name: 'QTZ',
+ symbol: 'QTZ',
decimals: 18,
minimalBalance: 1,
};
@@ -73,7 +73,7 @@
}, karuraApiOptions);
});
- it('Should connect and send OPL to Karura', async () => {
+ it('Should connect and send QTZ to Karura', async () => {
let balanceOnKaruraBefore: bigint;
await usingApi(async (api) => {
@@ -140,7 +140,7 @@
}, {provider: new WsProvider('ws://127.0.0.1:' + KARURA_PORT)});
});
- it('Should connect to Karura and send OPL back', async () => {
+ it('Should connect to Karura and send QTZ back', async () => {
let balanceBefore: bigint;
await usingApi(async (api) => {