difftreelog
test fix unit tests
in: master
5 files changed
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -4,7 +4,7 @@
use frame_support::{
assert_ok, parameter_types,
- traits::{Currency, OnInitialize, Everything},
+ traits::{Currency, OnInitialize, Everything, ConstU32},
};
use frame_system::RawOrigin;
use sp_core::H256;
@@ -81,6 +81,7 @@
type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
type OnSetCode = ();
+ type MaxConsumers = ConstU32<16>;
}
parameter_types! {
pallets/scheduler/src/lib.rsdiffbeforeafterboth1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//! specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//! index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//! `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63};64use frame_support::{65 decl_module, decl_storage, decl_event, decl_error,66 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67 traits::{68 Get,69 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,71 },72 weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use up_sponsorship::SponsorshipHandler;77use scale_info::TypeInfo;7879/// Our pallet's configuration trait. All our types and constants go in here. If the80/// pallet is dependent on specific other pallets, then their configuration traits81/// should be added to our implied traits list.82///83/// `system::Config` should always be included in our implied traits.84/// //85pub trait Config: system::Config {86 /// The overarching event type.87 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8889 /// The aggregated origin which the dispatch will take.90 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>91 + From<Self::PalletsOrigin>92 + IsType<<Self as system::Config>::Origin>;9394 /// The caller origin, overarching type of all pallets origins.95 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;9697 /// The aggregated call type.98 type Call: Parameter99 + Dispatchable<Origin = <Self as Config>::Origin>100 + GetDispatchInfo101 + From<system::Call<Self>>;102103 /// The maximum weight that may be scheduled per block for any dispatchables of less priority104 /// than `schedule::HARD_DEADLINE`.105 type MaximumWeight: Get<Weight>;106107 /// Required origin to schedule or cancel calls.108 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;109110 /// The maximum number of scheduled calls in the queue for a single block.111 /// Not strictly enforced, but used for weight estimation.112 type MaxScheduledPerBlock: Get<u32>;113114 /// Sponsoring function115 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;116117 /// Weight information for extrinsics in this pallet.118 type WeightInfo: WeightInfo;119}120121// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;122123/// Just a simple index for naming period tasks.124pub type PeriodicIndex = u32;125/// The location of a scheduled task that can be used to remove it.126pub type TaskAddress<BlockNumber> = (BlockNumber, u32);127128#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]129#[derive(Clone, RuntimeDebug, Encode, Decode)]130struct ScheduledV1<Call, BlockNumber> {131 maybe_id: Option<Vec<u8>>,132 priority: schedule::Priority,133 call: Call,134 maybe_periodic: Option<schedule::Period<BlockNumber>>,135}136137/// Information regarding an item to be executed in the future.138#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]139#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]140pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {141 /// The unique identity for this task, if there is one.142 maybe_id: Option<Vec<u8>>,143 /// This task's priority.144 priority: schedule::Priority,145 /// The call to be dispatched.146 call: Call,147 /// If the call is periodic, then this points to the information concerning that.148 maybe_periodic: Option<schedule::Period<BlockNumber>>,149 /// The origin to dispatch the call.150 origin: PalletsOrigin,151 _phantom: PhantomData<AccountId>,152}153154/// The current version of Scheduled struct.155pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =156 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;157158// A value placed in storage that represents the current version of the Scheduler storage.159// This value is used by the `on_runtime_upgrade` logic to determine whether we run160// storage migration logic.161#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]162enum Releases {163 V1,164 V2,165}166167impl Default for Releases {168 fn default() -> Self {169 Releases::V1170 }171}172173#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]174pub struct CallSpec {175 module: u32,176 method: u32,177}178179decl_storage! {180 trait Store for Module<T: Config> as Scheduler {181 /// Items to be executed, indexed by the block number that they should be executed on.182 pub Agenda: map hasher(twox_64_concat) T::BlockNumber183 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;184185 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber186 => Vec<Option<CallSpec>>;187188 /// Lookup from identity to the block number and index of the task.189 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;190191 /// Storage version of the pallet.192 ///193 /// New networks start with last version.194 StorageVersion build(|_| Releases::V2): Releases;195 }196}197198decl_event!(199 pub enum Event<T> where <T as system::Config>::BlockNumber {200 /// Scheduled some task. \[when, index\]201 Scheduled(BlockNumber, u32),202 /// Canceled some task. \[when, index\]203 Canceled(BlockNumber, u32),204 /// Dispatched some task. \[task, id, result\]205 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),206 }207);208209decl_error! {210 pub enum Error for Module<T: Config> {211 /// Failed to schedule a call212 FailedToSchedule,213 /// Cannot find the scheduled call.214 NotFound,215 /// Given target block number is in the past.216 TargetBlockNumberInPast,217 /// Reschedule failed because it does not change scheduled time.218 RescheduleNoChange,219 }220}221222decl_module! {223 /// Scheduler module declaration.224 pub struct Module<T: Config> for enum Call225 where226 origin: <T as system::Config>::Origin227 {228 type Error = Error<T>;229 fn deposit_event() = default;230231232 /// Anonymously schedule a task.233 ///234 /// # <weight>235 /// - S = Number of already scheduled calls236 /// - Base Weight: 22.29 + .126 * S µs237 /// - DB Weight:238 /// - Read: Agenda239 /// - Write: Agenda240 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls241 /// # </weight>242 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]243 fn schedule(origin,244 when: T::BlockNumber,245 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,246 priority: schedule::Priority,247 call: Box<<T as Config>::Call>,248 )249 {250 let origin = <T as Config>::Origin::from(origin);251 Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;252 }253254 /// Cancel an anonymously scheduled task.255 ///256 /// # <weight>257 /// - S = Number of already scheduled calls258 /// - Base Weight: 22.15 + 2.869 * S µs259 /// - DB Weight:260 /// - Read: Agenda261 /// - Write: Agenda, Lookup262 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls263 /// # </weight>264 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]265 fn cancel(origin, when: T::BlockNumber, index: u32) {266 T::ScheduleOrigin::ensure_origin(origin.clone())?;267 let origin = <T as Config>::Origin::from(origin);268 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;269 }270271 /// Schedule a named task.272 ///273 /// # <weight>274 /// - S = Number of already scheduled calls275 /// - Base Weight: 29.6 + .159 * S µs276 /// - DB Weight:277 /// - Read: Agenda, Lookup278 /// - Write: Agenda, Lookup279 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls280 /// # </weight>281 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]282 fn schedule_named(origin,283 id: Vec<u8>,284 when: T::BlockNumber,285 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,286 priority: schedule::Priority,287 call: Box<<T as Config>::Call>,288 ) {289 T::ScheduleOrigin::ensure_origin(origin.clone())?;290 let origin = <T as Config>::Origin::from(origin);291 Self::do_schedule_named(292 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call293 )?;294 }295296 /// Cancel a named scheduled task.297 ///298 /// # <weight>299 /// - S = Number of already scheduled calls300 /// - Base Weight: 24.91 + 2.907 * S µs301 /// - DB Weight:302 /// - Read: Agenda, Lookup303 /// - Write: Agenda, Lookup304 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls305 /// # </weight>306 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]307 fn cancel_named(origin, id: Vec<u8>) {308 T::ScheduleOrigin::ensure_origin(origin.clone())?;309 let origin = <T as Config>::Origin::from(origin);310 Self::do_cancel_named(Some(origin.caller().clone()), id)?;311 }312313 /// Anonymously schedule a task after a delay.314 ///315 /// # <weight>316 /// Same as [`schedule`].317 /// # </weight>318 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]319 fn schedule_after(origin,320 after: T::BlockNumber,321 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,322 priority: schedule::Priority,323 call: Box<<T as Config>::Call>,324 ) {325 T::ScheduleOrigin::ensure_origin(origin.clone())?;326 let origin = <T as Config>::Origin::from(origin);327 Self::do_schedule(328 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call329 )?;330 }331332 /// Schedule a named task after a delay.333 ///334 /// # <weight>335 /// Same as [`schedule_named`].336 /// # </weight>337 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]338 fn schedule_named_after(origin,339 id: Vec<u8>,340 after: T::BlockNumber,341 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,342 priority: schedule::Priority,343 call: Box<<T as Config>::Call>,344 ) {345 T::ScheduleOrigin::ensure_origin(origin.clone())?;346 let origin = <T as Config>::Origin::from(origin);347 Self::do_schedule_named(348 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call349 )?;350 }351352 /// Execute the scheduled calls353 ///354 /// # <weight>355 /// - S = Number of already scheduled calls356 /// - N = Named scheduled calls357 /// - P = Periodic Calls358 /// - Base Weight: 9.243 + 23.45 * S µs359 /// - DB Weight:360 /// - Read: Agenda + Lookup * N + Agenda(Future) * P361 /// - Write: Agenda + Lookup * N + Agenda(future) * P362 /// # </weight>363 fn on_initialize(now: T::BlockNumber) -> Weight {364 let limit = T::MaximumWeight::get();365 let mut queued = Agenda::<T>::take(now).into_iter()366 .enumerate()367 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))368 .collect::<Vec<_>>();369 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {370 log::warn!(371 target: "runtime::scheduler",372 "Warning: This block has more items queued in Scheduler than \373 expected from the runtime configuration. An update might be needed."374 );375 }376 queued.sort_by_key(|(_, s)| s.priority);377 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)378 let mut total_weight: Weight = 0;379 queued.into_iter()380 .enumerate()381 .scan(base_weight, |cumulative_weight, (order, (index, s))| {382 *cumulative_weight = cumulative_weight383 .saturating_add(s.call.get_dispatch_info().weight);384385 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(386 s.origin.clone()387 ).into();388389 if ensure_signed(origin).is_ok() {390 // AccountData for inner call origin accountdata.391 *cumulative_weight = cumulative_weight392 .saturating_add(T::DbWeight::get().reads_writes(1, 1));393 }394395 if s.maybe_id.is_some() {396 // Remove/Modify Lookup397 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));398 }399 if s.maybe_periodic.is_some() {400 // Read/Write Agenda for future block401 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));402 }403404 Some((order, index, *cumulative_weight, s))405 })406 .filter_map(|(order, index, cumulative_weight, mut s)| {407 // We allow a scheduled call if any is true:408 // - It's priority is `HARD_DEADLINE`409 // - It does not push the weight past the limit.410 // - It is the first item in the schedule411 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {412413 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(414 s.origin.clone()415 ).into();416 let sender = match ensure_signed(origin) {417 Ok(v) => v,418 // TODO: Support for unsigned extrinsics?419 Err(_) => return Some(Some(s))420 };421 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);422 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));423 let r = s.call.clone().dispatch(sponsor.into());424 let maybe_id = s.maybe_id.clone();425 if let Some((period, count)) = s.maybe_periodic {426 if count > 1 {427 s.maybe_periodic = Some((period, count - 1));428 } else {429 s.maybe_periodic = None;430 }431 let next = now + period;432 // If scheduled is named, place it's information in `Lookup`433 if let Some(ref id) = s.maybe_id {434 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);435 Lookup::<T>::insert(id, (next, next_index as u32));436 }437 Agenda::<T>::append(next, Some(s));438 } else if let Some(ref id) = s.maybe_id {439 Lookup::<T>::remove(id);440 }441 Self::deposit_event(RawEvent::Dispatched(442 (now, index),443 maybe_id,444 r.map(|_| ()).map_err(|e| e.error)445 ));446 total_weight = cumulative_weight;447 None448 } else {449 Some(Some(s))450 }451 })452 .for_each(|unused| {453 let next = now + One::one();454 Agenda::<T>::append(next, unused);455 });456457 total_weight458 }459 }460}461462impl<T: Config> Module<T> {463 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {464 let now = frame_system::Pallet::<T>::block_number();465466 let when = match when {467 DispatchTime::At(x) => x,468 // The current block has already completed it's scheduled tasks, so469 // Schedule the task at lest one block after this current block.470 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),471 };472473 if when <= now {474 return Err(Error::<T>::TargetBlockNumberInPast.into());475 }476477 Ok(when)478 }479480 fn do_schedule(481 when: DispatchTime<T::BlockNumber>,482 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,483 priority: schedule::Priority,484 origin: T::PalletsOrigin,485 call: <T as Config>::Call,486 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {487 let when = Self::resolve_time(when)?;488489 // sanitize maybe_periodic490 let maybe_periodic = maybe_periodic491 .filter(|p| p.1 > 1 && !p.0.is_zero())492 // Remove one from the number of repetitions since we will schedule one now.493 .map(|(p, c)| (p, c - 1));494 let s = Some(Scheduled {495 maybe_id: None,496 priority,497 call,498 maybe_periodic,499 origin,500 _phantom: PhantomData::<T::AccountId>::default(),501 });502 Agenda::<T>::append(when, s);503 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;504 if index > T::MaxScheduledPerBlock::get() {505 log::warn!(506 target: "runtime::scheduler",507 "Warning: There are more items queued in the Scheduler than \508 expected from the runtime configuration. An update might be needed.",509 );510 }511 Self::deposit_event(RawEvent::Scheduled(when, index));512513 Ok((when, index))514 }515516 fn do_cancel(517 origin: Option<T::PalletsOrigin>,518 (when, index): TaskAddress<T::BlockNumber>,519 ) -> Result<(), DispatchError> {520 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {521 agenda.get_mut(index as usize).map_or(522 Ok(None),523 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {524 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {525 if *o != s.origin {526 return Err(BadOrigin.into());527 }528 };529 Ok(s.take())530 },531 )532 })?;533 if let Some(s) = scheduled {534 if let Some(id) = s.maybe_id {535 Lookup::<T>::remove(id);536 }537 Self::deposit_event(RawEvent::Canceled(when, index));538 Ok(())539 } else {540 Err(Error::<T>::NotFound.into())541 }542 }543544 fn do_reschedule(545 (when, index): TaskAddress<T::BlockNumber>,546 new_time: DispatchTime<T::BlockNumber>,547 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {548 let new_time = Self::resolve_time(new_time)?;549550 if new_time == when {551 return Err(Error::<T>::RescheduleNoChange.into());552 }553554 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {555 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;556 let task = task.take().ok_or(Error::<T>::NotFound)?;557 Agenda::<T>::append(new_time, Some(task));558 Ok(())559 })?;560561 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;562 Self::deposit_event(RawEvent::Canceled(when, index));563 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));564565 Ok((new_time, new_index))566 }567568 fn do_schedule_named(569 id: Vec<u8>,570 when: DispatchTime<T::BlockNumber>,571 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,572 priority: schedule::Priority,573 origin: T::PalletsOrigin,574 call: <T as Config>::Call,575 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {576 // ensure id it is unique577 if Lookup::<T>::contains_key(&id) {578 return Err(Error::<T>::FailedToSchedule.into());579 }580581 let when = Self::resolve_time(when)?;582583 // sanitize maybe_periodic584 let maybe_periodic = maybe_periodic585 .filter(|p| p.1 > 1 && !p.0.is_zero())586 // Remove one from the number of repetitions since we will schedule one now.587 .map(|(p, c)| (p, c - 1));588589 let s = Scheduled {590 maybe_id: Some(id.clone()),591 priority,592 call,593 maybe_periodic,594 origin,595 _phantom: Default::default(),596 };597 Agenda::<T>::append(when, Some(s));598 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;599 if index > T::MaxScheduledPerBlock::get() {600 log::warn!(601 target: "runtime::scheduler",602 "Warning: There are more items queued in the Scheduler than \603 expected from the runtime configuration. An update might be needed.",604 );605 }606 let address = (when, index);607 Lookup::<T>::insert(&id, &address);608 Self::deposit_event(RawEvent::Scheduled(when, index));609610 Ok(address)611 }612613 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {614 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {615 if let Some((when, index)) = lookup.take() {616 let i = index as usize;617 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {618 if let Some(s) = agenda.get_mut(i) {619 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {620 if *o != s.origin {621 return Err(BadOrigin.into());622 }623 }624 *s = None;625 }626 Ok(())627 })?;628 Self::deposit_event(RawEvent::Canceled(when, index));629 Ok(())630 } else {631 Err(Error::<T>::NotFound.into())632 }633 })634 }635636 fn do_reschedule_named(637 id: Vec<u8>,638 new_time: DispatchTime<T::BlockNumber>,639 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {640 let new_time = Self::resolve_time(new_time)?;641642 Lookup::<T>::try_mutate_exists(643 id,644 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {645 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;646647 if new_time == when {648 return Err(Error::<T>::RescheduleNoChange.into());649 }650651 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {652 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;653 let task = task.take().ok_or(Error::<T>::NotFound)?;654 Agenda::<T>::append(new_time, Some(task));655656 Ok(())657 })?;658659 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;660 Self::deposit_event(RawEvent::Canceled(when, index));661 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));662663 *lookup = Some((new_time, new_index));664665 Ok((new_time, new_index))666 },667 )668 }669}670671#[cfg(test)]672#[allow(clippy::from_over_into)]673mod tests {674 use super::*;675676 use frame_support::{677 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,678 };679 use sp_core::H256;680 use sp_runtime::{681 Perbill,682 testing::Header,683 traits::{BlakeTwo256, IdentityLookup},684 };685 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};686 use crate as scheduler;687688 mod logger {689 use super::*;690 use std::cell::RefCell;691692 thread_local! {693 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());694 }695 pub trait Config: system::Config {696 type Event: From<Event> + Into<<Self as system::Config>::Event>;697 }698 decl_event! {699 pub enum Event {700 Logged(u32, Weight),701 }702 }703 decl_module! {704 pub struct Module<T: Config> for enum Call705 where706 origin: <T as system::Config>::Origin,707 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>708 {709 fn deposit_event() = default;710711 #[weight = *weight]712 fn log(origin, i: u32, weight: Weight) {713 Self::deposit_event(Event::Logged(i, weight));714 LOG.with(|log| {715 log.borrow_mut().push((origin.caller().clone(), i));716 })717 }718719 #[weight = *weight]720 fn log_without_filter(origin, i: u32, weight: Weight) {721 Self::deposit_event(Event::Logged(i, weight));722 LOG.with(|log| {723 log.borrow_mut().push((origin.caller().clone(), i));724 })725 }726 }727 }728 }729730 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;731 type Block = frame_system::mocking::MockBlock<Test>;732733 frame_support::construct_runtime!(734 pub enum Test where735 Block = Block,736 NodeBlock = Block,737 UncheckedExtrinsic = UncheckedExtrinsic,738 {739 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},740 Logger: logger::{Pallet, Call, Event},741 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},742 }743 );744745 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.746 pub struct BaseFilter;747 impl Contains<Call> for BaseFilter {748 fn contains(call: &Call) -> bool {749 !matches!(call, Call::Logger(logger::Call::log { .. }))750 }751 }752753 parameter_types! {754 pub const BlockHashCount: u64 = 250;755 pub BlockWeights: frame_system::limits::BlockWeights =756 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);757 }758 impl system::Config for Test {759 type BaseCallFilter = BaseFilter;760 type BlockWeights = ();761 type BlockLength = ();762 type DbWeight = RocksDbWeight;763 type Origin = Origin;764 type Call = Call;765 type Index = u64;766 type BlockNumber = u64;767 type Hash = H256;768 type Hashing = BlakeTwo256;769 type AccountId = u64;770 type Lookup = IdentityLookup<Self::AccountId>;771 type Header = Header;772 type Event = Event;773 type BlockHashCount = BlockHashCount;774 type Version = ();775 type PalletInfo = PalletInfo;776 type AccountData = ();777 type OnNewAccount = ();778 type OnKilledAccount = ();779 type SystemWeightInfo = ();780 type SS58Prefix = ();781 type OnSetCode = ();782 }783 impl logger::Config for Test {784 type Event = Event;785 }786 parameter_types! {787 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;788 pub const MaxScheduledPerBlock: u32 = 10;789 }790 ord_parameter_types! {791 pub const One: u64 = 1;792 }793794 impl Config for Test {795 type Event = Event;796 type Origin = Origin;797 type PalletsOrigin = OriginCaller;798 type Call = Call;799 type MaximumWeight = MaximumSchedulerWeight;800 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;801 type MaxScheduledPerBlock = MaxScheduledPerBlock;802 type WeightInfo = ();803 type SponsorshipHandler = ();804 }805}pallets/unique/src/mock.rsdiffbeforeafterboth--- a/pallets/unique/src/mock.rs
+++ b/pallets/unique/src/mock.rs
@@ -9,10 +9,11 @@
};
use pallet_transaction_payment::{CurrencyAdapter};
use frame_system as system;
-use pallet_evm::AddressMapping;
+use pallet_evm::{AddressMapping, runner::stack::MaybeMirroredLog};
use pallet_common::account::{EvmBackwardsAddressMapping, CrossAccountId};
-use codec::{Encode, Decode};
+use codec::{Encode, Decode, MaxEncodedLen};
use scale_info::TypeInfo;
+use up_data_structs::ConstU32;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = frame_system::mocking::MockBlock<Test>;
@@ -63,6 +64,7 @@
type SystemWeightInfo = ();
type SS58Prefix = SS58Prefix;
type OnSetCode = ();
+ type MaxConsumers = ConstU32<16>;
}
parameter_types! {
@@ -125,7 +127,7 @@
}
}
-#[derive(Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, TypeInfo)]
+#[derive(Encode, Decode, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, TypeInfo, MaxEncodedLen)]
pub struct TestCrossAccountId(u64, sp_core::H160);
impl CrossAccountId<u64> for TestCrossAccountId {
fn as_sub(&self) -> &u64 {
@@ -161,7 +163,7 @@
fn submit_logs_transaction(
_source: H160,
_tx: pallet_ethereum::Transaction,
- _logs: Vec<pallet_ethereum::Log>,
+ _logs: Vec<MaybeMirroredLog>,
) {
}
}
pallets/unique/src/tests.rsdiffbeforeafterboth--- a/pallets/unique/src/tests.rs
+++ b/pallets/unique/src/tests.rs
@@ -41,9 +41,9 @@
let origin1 = Origin::signed(owner);
assert_ok!(TemplateModule::create_collection(
origin1,
- col_name1,
- col_desc1,
- token_prefix1,
+ col_name1.try_into().unwrap(),
+ col_desc1.try_into().unwrap(),
+ token_prefix1.try_into().unwrap(),
mode.clone()
));
@@ -131,9 +131,9 @@
assert_noop!(
TemplateModule::create_collection(
origin1,
- col_name1,
- col_desc1,
- token_prefix1,
+ col_name1.try_into().unwrap(),
+ col_desc1.try_into().unwrap(),
+ token_prefix1.try_into().unwrap(),
CollectionMode::Fungible(MAX_DECIMAL_POINTS + 1)
),
Error::<Test>::CollectionDecimalPointLimitExceeded
@@ -2271,9 +2271,9 @@
assert_noop!(
TemplateModule::create_collection(
origin1,
- col_name1,
- col_desc1,
- token_prefix1,
+ col_name1.try_into().unwrap(),
+ col_desc1.try_into().unwrap(),
+ token_prefix1.try_into().unwrap(),
CollectionMode::NFT
),
CommonError::<Test>::TotalCollectionsLimitExceeded
@@ -2372,7 +2372,7 @@
assert_ok!(TemplateModule::set_const_on_chain_schema(
origin1,
collection_id,
- b"test const on chain schema".to_vec()
+ b"test const on chain schema".to_vec().try_into().unwrap()
));
assert_eq!(
@@ -2399,7 +2399,10 @@
assert_ok!(TemplateModule::set_variable_on_chain_schema(
origin1,
collection_id,
- b"test variable on chain schema".to_vec()
+ b"test variable on chain schema"
+ .to_vec()
+ .try_into()
+ .unwrap()
));
assert_eq!(
@@ -2432,7 +2435,7 @@
origin1,
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.clone().try_into().unwrap()
));
assert_eq!(
@@ -2459,7 +2462,7 @@
origin1,
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.clone().try_into().unwrap()
));
assert_eq!(
@@ -2485,7 +2488,7 @@
origin1,
collection_id,
TokenId(0),
- variable_data
+ variable_data.try_into().unwrap()
)
.map_err(|e| e.error),
<pallet_fungible::Error<Test>>::FungibleItemsDontHaveData
@@ -2494,54 +2497,6 @@
}
#[test]
-fn set_variable_meta_data_on_nft_token_fails_for_big_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::NFT, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
- assert_noop!(
- TemplateModule::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data
- )
- .map_err(|e| e.error),
- CommonError::<Test>::TokenVariableDataLimitExceeded
- );
- });
-}
-
-#[test]
-fn set_variable_meta_data_on_re_fungible_token_fails_for_big_data() {
- new_test_ext().execute_with(|| {
- let collection_id = create_test_collection(&CollectionMode::ReFungible, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- let data = default_re_fungible_data();
- create_test_item(collection_id, &data.into());
-
- let variable_data = b"test set_variable_meta_data method, bigger than limits.".to_vec();
- assert_noop!(
- TemplateModule::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data
- )
- .map_err(|e| e.error),
- CommonError::<Test>::TokenVariableDataLimitExceeded
- );
- });
-}
-
-#[test]
fn set_variable_meta_data_on_nft_with_item_owner_permission_flag() {
new_test_ext().execute_with(|| {
//default_limits();
@@ -2564,7 +2519,7 @@
origin1,
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.clone().try_into().unwrap()
));
assert_eq!(
@@ -2574,48 +2529,6 @@
variable_data
);
});
-}
-
-#[test]
-fn set_variable_meta_data_on_nft_with_item_owner_permission_flag_neg() {
- new_test_ext().execute_with(|| {
- let collection_id =
- create_test_collection_for_owner(&CollectionMode::NFT, 1, CollectionId(1));
-
- let origin1 = Origin::signed(1);
-
- assert_ok!(TemplateModule::set_mint_permission(
- origin1.clone(),
- collection_id,
- true
- ));
- assert_ok!(TemplateModule::add_to_allow_list(
- origin1.clone(),
- collection_id,
- account(1)
- ));
-
- let data = default_nft_data();
- create_test_item(collection_id, &data.into());
-
- assert_ok!(TemplateModule::set_meta_update_permission_flag(
- origin1.clone(),
- collection_id,
- MetaUpdatePermission::ItemOwner,
- ));
-
- let variable_data = b"1234567890123".to_vec();
- assert_noop!(
- TemplateModule::set_variable_meta_data(
- origin1,
- collection_id,
- TokenId(1),
- variable_data.clone()
- )
- .map_err(|e| e.error),
- CommonError::<Test>::TokenVariableDataLimitExceeded
- );
- })
}
#[test]
@@ -2712,7 +2625,7 @@
origin1,
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.clone().try_into().unwrap()
));
assert_eq!(
@@ -2761,7 +2674,7 @@
origin1,
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.try_into().unwrap()
)
.map_err(|e| e.error),
CommonError::<Test>::NoPermission
@@ -2819,7 +2732,7 @@
origin1.clone(),
collection_id,
TokenId(1),
- variable_data.clone()
+ variable_data.try_into().unwrap()
)
.map_err(|e| e.error),
CommonError::<Test>::NoPermission
runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -68,7 +68,6 @@
use codec::{Encode, Decode};
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
use fp_rpc::TransactionStatus;
-use sp_core::crypto::Public;
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
transaction_validity::TransactionValidityError,