difftreelog
Merge pull request #341 from UniqueNetwork/feature/simple-scheduler
in: master
Feature/simple scheduler
11 files changed
pallets/scheduler/Cargo.tomldiffbeforeafterboth--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -15,11 +15,13 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
+
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
sp-io = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
+sp-core = { default-features = false, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.22' }
frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.22" }
up-sponsorship = { version = "0.1.0", default-features = false, git = "https://github.com/uniquenetwork/pallet-sponsoring", branch = "polkadot-v0.9.22" }
@@ -40,6 +42,7 @@
"up-sponsorship/std",
"sp-io/std",
"sp-std/std",
+ "sp-core/std",
"log/std",
]
runtime-benchmarks = [
pallets/scheduler/src/lib.rsdiffbeforeafterboth--- a/pallets/scheduler/src/lib.rs
+++ b/pallets/scheduler/src/lib.rs
@@ -1,23 +1,6 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license
// This file is part of Substrate.
-// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.
+// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,16 +15,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! # Scheduler
-//! A module for scheduling dispatches.
-//!
-//! - [`Config`]
-//! - [`Call`]
-//! - [`Module`]
-//!
-//! ## Overview
+//! # Schedulerdo_reschedule
//!
-//! This module exposes capabilities for scheduling dispatches to occur at a
+//! This Pallet exposes capabilities for scheduling dispatches to occur at a
//! specified block number or at a specified period. These scheduled dispatches
//! may be named or anonymous and may be canceled.
//!
@@ -57,106 +33,59 @@
//!
//! ### Dispatchable Functions
//!
-//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a
-//! specified block and with a specified priority.
-//! * `cancel` - cancel a scheduled dispatch, specified by block number and
-//! index.
-//! * `schedule_named` - augments the `schedule` interface with an additional
-//! `Vec<u8>` parameter that can be used for identification.
+//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and
+//! with a specified priority.
+//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.
+//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter
+//! that can be used for identification.
//! * `cancel_named` - the named complement to the cancel function.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
-#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]
+#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
+
pub mod weights;
-use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};
-use codec::{Encode, Decode, Codec};
+use sp_core::H160;
+use codec::{Codec, Decode, Encode};
+use frame_system::{self as system, ensure_signed};
+pub use pallet::*;
+use scale_info::TypeInfo;
use sp_runtime::{
- RuntimeDebug,
- traits::{Zero, One, BadOrigin, Saturating},
+ traits::{BadOrigin, One, Saturating, Zero},
+ RuntimeDebug, DispatchErrorWithPostInfo,
};
+use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};
+
use frame_support::{
- decl_module, decl_storage, decl_event, decl_error,
- dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},
+ dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},
traits::{
- Get,
- schedule::{self, DispatchTime},
- OriginTrait, EnsureOrigin, IsType,
+ schedule::{self, DispatchTime, MaybeHashed},
+ NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,
+ StorageVersion,
},
weights::{GetDispatchInfo, Weight},
};
-use frame_system::{self as system, ensure_signed};
-pub use weights::WeightInfo;
-use up_sponsorship::SponsorshipHandler;
-use scale_info::TypeInfo;
-/// Our pallet's configuration trait. All our types and constants go in here. If the
-/// pallet is dependent on specific other pallets, then their configuration traits
-/// should be added to our implied traits list.
-///
-/// `system::Config` should always be included in our implied traits.
-/// //
-pub trait Config: system::Config {
- /// The overarching event type.
- type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;
-
- /// The aggregated origin which the dispatch will take.
- type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
- + From<Self::PalletsOrigin>
- + IsType<<Self as system::Config>::Origin>;
-
- /// The caller origin, overarching type of all pallets origins.
- type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;
-
- /// The aggregated call type.
- type Call: Parameter
- + Dispatchable<Origin = <Self as Config>::Origin>
- + GetDispatchInfo
- + From<system::Call<Self>>;
-
- /// The maximum weight that may be scheduled per block for any dispatchables of less priority
- /// than `schedule::HARD_DEADLINE`.
- type MaximumWeight: Get<Weight>;
-
- /// Required origin to schedule or cancel calls.
- type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;
-
- /// The maximum number of scheduled calls in the queue for a single block.
- /// Not strictly enforced, but used for weight estimation.
- type MaxScheduledPerBlock: Get<u32>;
-
- /// Sponsoring function
- type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
-
- /// Weight information for extrinsics in this pallet.
- type WeightInfo: WeightInfo;
-}
+pub use weights::WeightInfo;
-// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;
-
/// Just a simple index for naming period tasks.
pub type PeriodicIndex = u32;
/// The location of a scheduled task that can be used to remove it.
pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
+pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;
-#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
-#[derive(Clone, RuntimeDebug, Encode, Decode)]
-struct ScheduledV1<Call, BlockNumber> {
- maybe_id: Option<Vec<u8>>,
- priority: schedule::Priority,
- call: Call,
- maybe_periodic: Option<schedule::Period<BlockNumber>>,
-}
+type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];
+pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;
/// Information regarding an item to be executed in the future.
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]
-pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {
+pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {
/// The unique identity for this task, if there is one.
- maybe_id: Option<Vec<u8>>,
+ maybe_id: Option<ScheduledId>,
/// This task's priority.
priority: schedule::Priority,
/// The call to be dispatched.
@@ -168,63 +97,213 @@
_phantom: PhantomData<AccountId>,
}
+pub type ScheduledV3Of<T> = ScheduledV3<
+ CallOrHashOf<T>,
+ <T as frame_system::Config>::BlockNumber,
+ <T as Config>::PalletsOrigin,
+ <T as frame_system::Config>::AccountId,
+>;
+
+pub type ScheduledOf<T> = ScheduledV3Of<T>;
+
/// The current version of Scheduled struct.
pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =
- ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;
+ ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;
-// A value placed in storage that represents the current version of the Scheduler storage.
-// This value is used by the `on_runtime_upgrade` logic to determine whether we run
-// storage migration logic.
-#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]
-enum Releases {
- V1,
- V2,
+#[cfg(feature = "runtime-benchmarks")]
+mod preimage_provider {
+ use frame_support::traits::PreimageRecipient;
+ pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}
+ impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}
}
-impl Default for Releases {
- fn default() -> Self {
- Releases::V1
- }
+#[cfg(not(feature = "runtime-benchmarks"))]
+mod preimage_provider {
+ use frame_support::traits::PreimageProvider;
+ pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}
+ impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}
}
-#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]
-pub struct CallSpec {
- module: u32,
- method: u32,
+pub use preimage_provider::PreimageProviderAndMaybeRecipient;
+
+pub(crate) trait MarginalWeightInfo: WeightInfo {
+ fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {
+ match (periodic, named, resolved) {
+ (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),
+ (_, true, None) => {
+ Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)
+ }
+ (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),
+ (false, true, Some(false)) => {
+ Self::on_initialize_named(2) - Self::on_initialize_named(1)
+ }
+ (true, false, Some(false)) => {
+ Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)
+ }
+ (true, true, Some(false)) => {
+ Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)
+ }
+ (false, false, Some(true)) => {
+ Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)
+ }
+ (false, true, Some(true)) => {
+ Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)
+ }
+ (true, false, Some(true)) => {
+ Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)
+ }
+ (true, true, Some(true)) => {
+ Self::on_initialize_periodic_named_resolved(2)
+ - Self::on_initialize_periodic_named_resolved(1)
+ }
+ }
+ }
}
+impl<T: WeightInfo> MarginalWeightInfo for T {}
-decl_storage! {
- trait Store for Module<T: Config> as Scheduler {
- /// Items to be executed, indexed by the block number that they should be executed on.
- pub Agenda: map hasher(twox_64_concat) T::BlockNumber
- => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;
+#[frame_support::pallet]
+pub mod pallet {
+ use super::*;
+ use frame_support::{
+ dispatch::PostDispatchInfo,
+ pallet_prelude::*,
+ traits::{schedule::LookupError, PreimageProvider},
+ };
+ use frame_system::pallet_prelude::*;
+
+ /// The current storage version.
+ const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);
+
+ #[pallet::pallet]
+ #[pallet::generate_store(pub(super) trait Store)]
+ #[pallet::storage_version(STORAGE_VERSION)]
+ #[pallet::without_storage_info]
+ pub struct Pallet<T>(_);
+
+ /// `system::Config` should always be included in our implied traits.
+ #[pallet::config]
+ pub trait Config: frame_system::Config {
+ /// The overarching event type.
+ type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
+
+ /// The aggregated origin which the dispatch will take.
+ type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
+ + From<Self::PalletsOrigin>
+ + IsType<<Self as system::Config>::Origin>;
+
+ /// The caller origin, overarching type of all pallets origins.
+ type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;
+
+ type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;
+
+ /// The aggregated call type.
+ type Call: Parameter
+ + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>
+ + GetDispatchInfo
+ + From<system::Call<Self>>;
- pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber
- => Vec<Option<CallSpec>>;
+ /// The maximum weight that may be scheduled per block for any dispatchables of less
+ /// priority than `schedule::HARD_DEADLINE`.
+ #[pallet::constant]
+ type MaximumWeight: Get<Weight>;
- /// Lookup from identity to the block number and index of the task.
- Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;
+ /// Required origin to schedule or cancel calls.
+ type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;
- /// Storage version of the pallet.
+ /// Compare the privileges of origins.
+ ///
+ /// This will be used when canceling a task, to ensure that the origin that tries
+ /// to cancel has greater or equal privileges as the origin that created the scheduled task.
///
- /// New networks start with last version.
- StorageVersion build(|_| Releases::V2): Releases;
+ /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can
+ /// be used. This will only check if two given origins are equal.
+ type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;
+
+ /// The maximum number of scheduled calls in the queue for a single block.
+ /// Not strictly enforced, but used for weight estimation.
+ #[pallet::constant]
+ type MaxScheduledPerBlock: Get<u32>;
+
+ /// Weight information for extrinsics in this pallet.
+ type WeightInfo: WeightInfo;
+
+ /// The preimage provider with which we look up call hashes to get the call.
+ type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;
+
+ /// If `Some` then the number of blocks to postpone execution for when the item is delayed.
+ type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;
+
+ /// Sponsoring function.
+ // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;
+
+ /// The helper type used for custom transaction fee logic.
+ type CallExecutor: DispatchCall<Self, H160>;
}
-}
-decl_event!(
- pub enum Event<T> where <T as system::Config>::BlockNumber {
- /// Scheduled some task. \[when, index\]
- Scheduled(BlockNumber, u32),
- /// Canceled some task. \[when, index\]
- Canceled(BlockNumber, u32),
- /// Dispatched some task. \[task, id, result\]
- Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),
+ /// A Scheduler-Runtime interface for finer payment handling.
+ pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {
+ fn reserve_balance(
+ id: ScheduledId,
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError>;
+
+ fn pay_for_call(
+ id: ScheduledId,
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as Config>::Call,
+ ) -> Result<u128, DispatchError>;
+
+ /// Resolve the call dispatch, including any post-dispatch operations.
+ fn dispatch_call(
+ signer: T::AccountId,
+ function: <T as Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ >;
+
+ fn cancel_reserve(
+ id: ScheduledId,
+ sponsor: <T as frame_system::Config>::AccountId,
+ ) -> Result<u128, DispatchError>;
}
-);
-decl_error! {
- pub enum Error for Module<T: Config> {
+ /// Items to be executed, indexed by the block number that they should be executed on.
+ #[pallet::storage]
+ pub type Agenda<T: Config> =
+ StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;
+
+ /// Lookup from identity to the block number and index of the task.
+ #[pallet::storage]
+ pub(crate) type Lookup<T: Config> =
+ StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;
+
+ /// Events type.
+ #[pallet::event]
+ #[pallet::generate_deposit(pub(super) fn deposit_event)]
+ pub enum Event<T: Config> {
+ /// Scheduled some task.
+ Scheduled { when: T::BlockNumber, index: u32 },
+ /// Canceled some task.
+ Canceled { when: T::BlockNumber, index: u32 },
+ /// Dispatched some task.
+ Dispatched {
+ task: TaskAddress<T::BlockNumber>,
+ id: Option<ScheduledId>,
+ result: DispatchResult,
+ },
+ /// The call for the provided hash was not found so the task has been aborted.
+ CallLookupFailed {
+ task: TaskAddress<T::BlockNumber>,
+ id: Option<ScheduledId>,
+ error: LookupError,
+ },
+ }
+
+ #[pallet::error]
+ pub enum Error<T> {
/// Failed to schedule a call
FailedToSchedule,
/// Cannot find the scheduled call.
@@ -234,249 +313,268 @@
/// Reschedule failed because it does not change scheduled time.
RescheduleNoChange,
}
-}
-decl_module! {
- /// Scheduler module declaration.
- pub struct Module<T: Config> for enum Call
- where
- origin: <T as system::Config>::Origin
- {
- type Error = Error<T>;
- fn deposit_event() = default;
+ #[pallet::hooks]
+ impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
+ /// Execute the scheduled calls
+ fn on_initialize(now: T::BlockNumber) -> Weight {
+ let limit = T::MaximumWeight::get();
+ let mut queued = Agenda::<T>::take(now)
+ .into_iter()
+ .enumerate()
+ .filter_map(|(index, s)| Some((index as u32, s?)))
+ .collect::<Vec<_>>();
- /// Anonymously schedule a task.
- ///
- /// # <weight>
- /// - S = Number of already scheduled calls
- /// - Base Weight: 22.29 + .126 * S µs
- /// - DB Weight:
- /// - Read: Agenda
- /// - Write: Agenda
- /// - Will use base weight of 25 which should be good for up to 30 scheduled calls
- /// # </weight>
- #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
- fn schedule(origin,
- when: T::BlockNumber,
- maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
- priority: schedule::Priority,
- call: Box<<T as Config>::Call>,
- )
- {
- let origin = <T as Config>::Origin::from(origin);
- Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;
- }
+ if queued.len() as u32 > T::MaxScheduledPerBlock::get() {
+ log::warn!(
+ target: "runtime::scheduler",
+ "Warning: This block has more items queued in Scheduler than \
+ expected from the runtime configuration. An update might be needed."
+ );
+ }
- /// Cancel an anonymously scheduled task.
- ///
- /// # <weight>
- /// - S = Number of already scheduled calls
- /// - Base Weight: 22.15 + 2.869 * S µs
- /// - DB Weight:
- /// - Read: Agenda
- /// - Write: Agenda, Lookup
- /// - Will use base weight of 100 which should be good for up to 30 scheduled calls
- /// # </weight>
- #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]
- fn cancel(origin, when: T::BlockNumber, index: u32) {
- T::ScheduleOrigin::ensure_origin(origin.clone())?;
- let origin = <T as Config>::Origin::from(origin);
- Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
+ queued.sort_by_key(|(_, s)| s.priority);
+
+ let next = now + One::one();
+
+ let mut total_weight: Weight = T::WeightInfo::on_initialize(0);
+ for (order, (index, mut s)) in queued.into_iter().enumerate() {
+ let named = if let Some(ref id) = s.maybe_id {
+ Lookup::<T>::remove(id);
+ true
+ } else {
+ false
+ };
+
+ let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();
+ s.call = call;
+
+ let resolved = if let Some(completed) = maybe_completed {
+ T::PreimageProvider::unrequest_preimage(&completed);
+ true
+ } else {
+ false
+ };
+ let call = match s.call.as_value().cloned() {
+ Some(c) => c,
+ None => {
+ // Preimage not available - postpone until some block.
+ total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));
+ if let Some(delay) = T::NoPreimagePostponement::get() {
+ let until = now.saturating_add(delay);
+ if let Some(ref id) = s.maybe_id {
+ let index = Agenda::<T>::decode_len(until).unwrap_or(0);
+ Lookup::<T>::insert(id, (until, index as u32));
+ }
+ Agenda::<T>::append(until, Some(s));
+ }
+ continue;
+ }
+ };
+
+ let periodic = s.maybe_periodic.is_some();
+ let call_weight = call.get_dispatch_info().weight;
+ let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));
+ let origin =
+ <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())
+ .into();
+ if ensure_signed(origin).is_ok() {
+ // Weights of Signed dispatches expect their signing account to be whitelisted.
+ item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
+ }
+
+ // We allow a scheduled call if any is true:
+ // - It's priority is `HARD_DEADLINE`
+ // - It does not push the weight past the limit.
+ // - It is the first item in the schedule
+ let hard_deadline = s.priority <= schedule::HARD_DEADLINE;
+ let test_weight = total_weight
+ .saturating_add(call_weight)
+ .saturating_add(item_weight);
+ if !hard_deadline && order > 0 && test_weight > limit {
+ // Cannot be scheduled this block - postpone until next.
+ total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));
+ if let Some(ref id) = s.maybe_id {
+ // NOTE: We could reasonably not do this (in which case there would be one
+ // block where the named and delayed item could not be referenced by name),
+ // but we will do it anyway since it should be mostly free in terms of
+ // weight and it is slightly cleaner.
+ let index = Agenda::<T>::decode_len(next).unwrap_or(0);
+ Lookup::<T>::insert(id, (next, index as u32));
+ }
+ Agenda::<T>::append(next, Some(s));
+ continue;
+ }
+
+ let sender = ensure_signed(
+ <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())
+ .into(),
+ )
+ .unwrap();
+
+ // // if call have id it was be reserved
+ // if s.maybe_id.is_some() {
+ // let _ = T::CallExecutor::pay_for_call(
+ // s.maybe_id.unwrap(),
+ // sender.clone(),
+ // call.clone(),
+ // );
+ // }
+
+ let r = T::CallExecutor::dispatch_call(sender, call.clone());
+
+ let mut actual_call_weight: Weight = item_weight;
+ let result: Result<_, DispatchError> = match r {
+ Ok(o) => match o {
+ Ok(di) => {
+ actual_call_weight = di.actual_weight.unwrap_or(item_weight);
+ Ok(())
+ }
+ Err(err) => Err(err.error),
+ },
+ Err(_) => {
+ log::error!(
+ target: "runtime::scheduler",
+ "Warning: Scheduler has failed to execute a post-dispatch transaction. \
+ This block might have become invalid.");
+ Err(DispatchError::CannotLookup)
+ } // todo possibly force a skip/return here, do something with the error
+ };
+
+ total_weight.saturating_accrue(item_weight);
+ total_weight.saturating_accrue(actual_call_weight);
+
+ Self::deposit_event(Event::Dispatched {
+ task: (now, index),
+ id: s.maybe_id.clone(),
+ result,
+ });
+
+ if let &Some((period, count)) = &s.maybe_periodic {
+ if count > 1 {
+ s.maybe_periodic = Some((period, count - 1));
+ } else {
+ s.maybe_periodic = None;
+ }
+ let wake = now + period;
+ // If scheduled is named, place its information in `Lookup`
+ if let Some(ref id) = s.maybe_id {
+ let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);
+ Lookup::<T>::insert(id, (wake, wake_index as u32));
+ }
+ Agenda::<T>::append(wake, Some(s));
+ }
+ }
+ 0
+ //total_weight
}
+ }
+ #[pallet::call]
+ impl<T: Config> Pallet<T> {
/// Schedule a named task.
- ///
- /// # <weight>
- /// - S = Number of already scheduled calls
- /// - Base Weight: 29.6 + .159 * S µs
- /// - DB Weight:
- /// - Read: Agenda, Lookup
- /// - Write: Agenda, Lookup
- /// - Will use base weight of 35 which should be good for more than 30 scheduled calls
- /// # </weight>
- #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
- fn schedule_named(origin,
- id: Vec<u8>,
+ #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule_named(
+ origin: OriginFor<T>,
+ id: ScheduledId,
when: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority,
- call: Box<<T as Config>::Call>,
- ) {
+ call: Box<CallOrHashOf<T>>,
+ ) -> DispatchResult {
T::ScheduleOrigin::ensure_origin(origin.clone())?;
let origin = <T as Config>::Origin::from(origin);
Self::do_schedule_named(
- id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call
+ id,
+ DispatchTime::At(when),
+ maybe_periodic,
+ priority,
+ origin.caller().clone(),
+ *call,
)?;
+ Ok(())
}
/// Cancel a named scheduled task.
- ///
- /// # <weight>
- /// - S = Number of already scheduled calls
- /// - Base Weight: 24.91 + 2.907 * S µs
- /// - DB Weight:
- /// - Read: Agenda, Lookup
- /// - Write: Agenda, Lookup
- /// - Will use base weight of 100 which should be good for up to 30 scheduled calls
- /// # </weight>
- #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]
- fn cancel_named(origin, id: Vec<u8>) {
+ #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
+ pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {
T::ScheduleOrigin::ensure_origin(origin.clone())?;
let origin = <T as Config>::Origin::from(origin);
Self::do_cancel_named(Some(origin.caller().clone()), id)?;
- }
-
- /// Anonymously schedule a task after a delay.
- ///
- /// # <weight>
- /// Same as [`schedule`].
- /// # </weight>
- #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
- fn schedule_after(origin,
- after: T::BlockNumber,
- maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
- priority: schedule::Priority,
- call: Box<<T as Config>::Call>,
- ) {
- T::ScheduleOrigin::ensure_origin(origin.clone())?;
- let origin = <T as Config>::Origin::from(origin);
- Self::do_schedule(
- DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
- )?;
+ Ok(())
}
/// Schedule a named task after a delay.
///
/// # <weight>
- /// Same as [`schedule_named`].
+ /// Same as [`schedule_named`](Self::schedule_named).
/// # </weight>
- #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
- fn schedule_named_after(origin,
- id: Vec<u8>,
+ #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
+ pub fn schedule_named_after(
+ origin: OriginFor<T>,
+ id: ScheduledId,
after: T::BlockNumber,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority,
- call: Box<<T as Config>::Call>,
- ) {
+ call: Box<CallOrHashOf<T>>,
+ ) -> DispatchResult {
T::ScheduleOrigin::ensure_origin(origin.clone())?;
let origin = <T as Config>::Origin::from(origin);
Self::do_schedule_named(
- id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
+ id,
+ DispatchTime::After(after),
+ maybe_periodic,
+ priority,
+ origin.caller().clone(),
+ *call,
)?;
+ Ok(())
}
-
- /// Execute the scheduled calls
- ///
- /// # <weight>
- /// - S = Number of already scheduled calls
- /// - N = Named scheduled calls
- /// - P = Periodic Calls
- /// - Base Weight: 9.243 + 23.45 * S µs
- /// - DB Weight:
- /// - Read: Agenda + Lookup * N + Agenda(Future) * P
- /// - Write: Agenda + Lookup * N + Agenda(future) * P
- /// # </weight>
- fn on_initialize(now: T::BlockNumber) -> Weight {
- let limit = T::MaximumWeight::get();
- let mut queued = Agenda::<T>::take(now).into_iter()
- .enumerate()
- .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))
- .collect::<Vec<_>>();
- if queued.len() as u32 > T::MaxScheduledPerBlock::get() {
- log::warn!(
- target: "runtime::scheduler",
- "Warning: This block has more items queued in Scheduler than \
- expected from the runtime configuration. An update might be needed."
- );
- }
- queued.sort_by_key(|(_, s)| s.priority);
- let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)
- let mut total_weight: Weight = 0;
- queued.into_iter()
- .enumerate()
- .scan(base_weight, |cumulative_weight, (order, (index, s))| {
- *cumulative_weight = cumulative_weight
- .saturating_add(s.call.get_dispatch_info().weight);
-
- let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
- s.origin.clone()
- ).into();
-
- if ensure_signed(origin).is_ok() {
- // AccountData for inner call origin accountdata.
- *cumulative_weight = cumulative_weight
- .saturating_add(T::DbWeight::get().reads_writes(1, 1));
- }
-
- if s.maybe_id.is_some() {
- // Remove/Modify Lookup
- *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));
- }
- if s.maybe_periodic.is_some() {
- // Read/Write Agenda for future block
- *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));
- }
+ }
+}
- Some((order, index, *cumulative_weight, s))
- })
- .filter_map(|(order, index, cumulative_weight, mut s)| {
- // We allow a scheduled call if any is true:
- // - It's priority is `HARD_DEADLINE`
- // - It does not push the weight past the limit.
- // - It is the first item in the schedule
- if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
+impl<T: Config> Pallet<T> {
+ #[cfg(feature = "try-runtime")]
+ pub fn pre_migrate_to_v3() -> Result<(), &'static str> {
+ Ok(())
+ }
- let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
- s.origin.clone()
- ).into();
- let sender = match ensure_signed(origin) {
- Ok(v) => v,
- // TODO: Support for unsigned extrinsics?
- Err(_) => return Some(Some(s))
- };
- let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);
- let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));
- let r = s.call.clone().dispatch(sponsor.into());
- let maybe_id = s.maybe_id.clone();
- if let Some((period, count)) = s.maybe_periodic {
- if count > 1 {
- s.maybe_periodic = Some((period, count - 1));
- } else {
- s.maybe_periodic = None;
- }
- let next = now + period;
- // If scheduled is named, place it's information in `Lookup`
- if let Some(ref id) = s.maybe_id {
- let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);
- Lookup::<T>::insert(id, (next, next_index as u32));
- }
- Agenda::<T>::append(next, Some(s));
- } else if let Some(ref id) = s.maybe_id {
- Lookup::<T>::remove(id);
- }
- Self::deposit_event(RawEvent::Dispatched(
- (now, index),
- maybe_id,
- r.map(|_| ()).map_err(|e| e.error)
- ));
- total_weight = cumulative_weight;
- None
- } else {
- Some(Some(s))
- }
- })
- .for_each(|unused| {
- let next = now + One::one();
- Agenda::<T>::append(next, unused);
- });
+ #[cfg(feature = "try-runtime")]
+ pub fn post_migrate_to_v3() -> Result<(), &'static str> {
+ use frame_support::dispatch::GetStorageVersion;
- total_weight
+ assert!(Self::current_storage_version() == 3);
+ for k in Agenda::<T>::iter_keys() {
+ let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;
}
+ Ok(())
+ }
+
+ /// Helper to migrate scheduler when the pallet origin type has changed.
+ pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {
+ Agenda::<T>::translate::<
+ Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,
+ _,
+ >(|_, agenda| {
+ Some(
+ agenda
+ .into_iter()
+ .map(|schedule| {
+ schedule.map(|schedule| Scheduled {
+ maybe_id: schedule.maybe_id,
+ priority: schedule.priority,
+ call: schedule.call,
+ maybe_periodic: schedule.maybe_periodic,
+ origin: schedule.origin.into(),
+ _phantom: Default::default(),
+ })
+ })
+ .collect::<Vec<_>>(),
+ )
+ });
}
-}
-impl<T: Config> Module<T> {
fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {
let now = frame_system::Pallet::<T>::block_number();
@@ -499,9 +597,10 @@
maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority,
origin: T::PalletsOrigin,
- call: <T as Config>::Call,
+ call: CallOrHashOf<T>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
let when = Self::resolve_time(when)?;
+ call.ensure_requested::<T::PreimageProvider>();
// sanitize maybe_periodic
let maybe_periodic = maybe_periodic
@@ -518,14 +617,7 @@
});
Agenda::<T>::append(when, s);
let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
- if index > T::MaxScheduledPerBlock::get() {
- log::warn!(
- target: "runtime::scheduler",
- "Warning: There are more items queued in the Scheduler than \
- expected from the runtime configuration. An update might be needed.",
- );
- }
- Self::deposit_event(RawEvent::Scheduled(when, index));
+ Self::deposit_event(Event::Scheduled { when, index });
Ok((when, index))
}
@@ -539,7 +631,10 @@
Ok(None),
|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
- if *o != s.origin {
+ if matches!(
+ T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
+ Some(Ordering::Less) | None
+ ) {
return Err(BadOrigin.into());
}
};
@@ -548,13 +643,14 @@
)
})?;
if let Some(s) = scheduled {
+ s.call.ensure_unrequested::<T::PreimageProvider>();
if let Some(id) = s.maybe_id {
Lookup::<T>::remove(id);
}
- Self::deposit_event(RawEvent::Canceled(when, index));
+ Self::deposit_event(Event::Canceled { when, index });
Ok(())
} else {
- Err(Error::<T>::NotFound.into())
+ Err(Error::<T>::NotFound)?
}
}
@@ -576,27 +672,32 @@
})?;
let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;
- Self::deposit_event(RawEvent::Canceled(when, index));
- Self::deposit_event(RawEvent::Scheduled(new_time, new_index));
+ Self::deposit_event(Event::Canceled { when, index });
+ Self::deposit_event(Event::Scheduled {
+ when: new_time,
+ index: new_index,
+ });
Ok((new_time, new_index))
}
fn do_schedule_named(
- id: Vec<u8>,
+ id: ScheduledId,
when: DispatchTime<T::BlockNumber>,
maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
priority: schedule::Priority,
origin: T::PalletsOrigin,
- call: <T as Config>::Call,
+ call: CallOrHashOf<T>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
// ensure id it is unique
if Lookup::<T>::contains_key(&id) {
- return Err(Error::<T>::FailedToSchedule.into());
+ return Err(Error::<T>::FailedToSchedule)?;
}
let when = Self::resolve_time(when)?;
+ call.ensure_requested::<T::PreimageProvider>();
+
// sanitize maybe_periodic
let maybe_periodic = maybe_periodic
.filter(|p| p.1 > 1 && !p.0.is_zero())
@@ -606,52 +707,74 @@
let s = Scheduled {
maybe_id: Some(id.clone()),
priority,
- call,
+ call: call.clone(),
maybe_periodic,
- origin,
+ origin: origin.clone(),
_phantom: Default::default(),
};
+
+ // reserve balance for periodic execution
+ // let sender =
+ // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;
+ // let repeats = match maybe_periodic {
+ // Some(p) => p.1,
+ // None => 1,
+ // };
+ // let _ = T::CallExecutor::reserve_balance(
+ // id.clone(),
+ // sender,
+ // call.as_value().unwrap().clone(),
+ // repeats,
+ // );
+
Agenda::<T>::append(when, Some(s));
let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
- if index > T::MaxScheduledPerBlock::get() {
- log::warn!(
- target: "runtime::scheduler",
- "Warning: There are more items queued in the Scheduler than \
- expected from the runtime configuration. An update might be needed.",
- );
- }
let address = (when, index);
Lookup::<T>::insert(&id, &address);
- Self::deposit_event(RawEvent::Scheduled(when, index));
+ Self::deposit_event(Event::Scheduled { when, index });
Ok(address)
}
- fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {
+ fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {
Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
if let Some((when, index)) = lookup.take() {
let i = index as usize;
Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
if let Some(s) = agenda.get_mut(i) {
- if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
- if *o != s.origin {
+ if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {
+ if matches!(
+ T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),
+ Some(Ordering::Less) | None
+ ) {
return Err(BadOrigin.into());
}
+ // release balance reserve
+ // let sender = ensure_signed(
+ // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(
+ // origin.unwrap(),
+ // )
+ // .into(),
+ // )?;
+ // let _ = T::CallExecutor::cancel_reserve(id, sender);
+
+ s.call.ensure_unrequested::<T::PreimageProvider>();
}
*s = None;
}
Ok(())
})?;
- Self::deposit_event(RawEvent::Canceled(when, index));
+
+ Self::deposit_event(Event::Canceled { when, index });
Ok(())
} else {
- Err(Error::<T>::NotFound.into())
+ Err(Error::<T>::NotFound)?
}
})
}
fn do_reschedule_named(
- id: Vec<u8>,
+ id: ScheduledId,
new_time: DispatchTime<T::BlockNumber>,
) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
let new_time = Self::resolve_time(new_time)?;
@@ -674,8 +797,11 @@
})?;
let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;
- Self::deposit_event(RawEvent::Canceled(when, index));
- Self::deposit_event(RawEvent::Scheduled(new_time, new_index));
+ Self::deposit_event(Event::Canceled { when, index });
+ Self::deposit_event(Event::Scheduled {
+ when: new_time,
+ index: new_index,
+ });
*lookup = Some((new_time, new_index));
@@ -684,161 +810,86 @@
)
}
}
-
-#[cfg(test)]
-#[allow(clippy::from_over_into)]
-mod tests {
- use super::*;
- use frame_support::{
- ord_parameter_types, parameter_types,
- traits::{Contains, ConstU32, EnsureOneOf},
- weights::constants::RocksDbWeight,
- };
- use sp_core::H256;
- use sp_runtime::{
- Perbill,
- testing::Header,
- traits::{BlakeTwo256, IdentityLookup},
- };
- use frame_system::{EnsureRoot, EnsureSignedBy};
- use crate as scheduler;
+impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>
+ for Pallet<T>
+{
+ type Address = TaskAddress<T::BlockNumber>;
+ type Hash = T::Hash;
- #[frame_support::pallet]
- pub mod logger {
- use super::{OriginCaller, OriginTrait};
- use frame_support::pallet_prelude::*;
- use frame_system::pallet_prelude::*;
- use std::cell::RefCell;
-
- thread_local! {
- static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());
- }
- pub fn log() -> Vec<(OriginCaller, u32)> {
- LOG.with(|log| log.borrow().clone())
- }
-
- #[pallet::pallet]
- #[pallet::generate_store(pub(super) trait Store)]
- pub struct Pallet<T>(PhantomData<T>);
-
- #[pallet::hooks]
- impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
-
- #[pallet::config]
- pub trait Config: frame_system::Config {
- type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
- }
-
- #[pallet::event]
- #[pallet::generate_deposit(pub(super) fn deposit_event)]
- pub enum Event<T: Config> {
- Logged(u32, Weight),
- }
+ fn schedule(
+ when: DispatchTime<T::BlockNumber>,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: schedule::Priority,
+ origin: T::PalletsOrigin,
+ call: CallOrHashOf<T>,
+ ) -> Result<Self::Address, DispatchError> {
+ Self::do_schedule(when, maybe_periodic, priority, origin, call)
+ }
- #[pallet::call]
- impl<T: Config> Pallet<T>
- where
- <T as frame_system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>,
- {
- #[pallet::weight(*weight)]
- pub fn log(origin: OriginFor<T>, i: u32, weight: Weight) -> DispatchResult {
- Self::deposit_event(Event::Logged(i, weight));
- LOG.with(|log| {
- log.borrow_mut().push((origin.caller().clone(), i));
- });
- Ok(())
- }
+ fn cancel((when, index): Self::Address) -> Result<(), ()> {
+ Self::do_cancel(None, (when, index)).map_err(|_| ())
+ }
- #[pallet::weight(*weight)]
- pub fn log_without_filter(
- origin: OriginFor<T>,
- i: u32,
- weight: Weight,
- ) -> DispatchResult {
- Self::deposit_event(Event::Logged(i, weight));
- LOG.with(|log| {
- log.borrow_mut().push((origin.caller().clone(), i));
- });
- Ok(())
- }
- }
+ fn reschedule(
+ address: Self::Address,
+ when: DispatchTime<T::BlockNumber>,
+ ) -> Result<Self::Address, DispatchError> {
+ Self::do_reschedule(address, when)
}
- type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
- type Block = frame_system::mocking::MockBlock<Test>;
+ fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {
+ Agenda::<T>::get(when)
+ .get(index as usize)
+ .ok_or(())
+ .map(|_| when)
+ }
+}
- frame_support::construct_runtime!(
- pub enum Test where
- Block = Block,
- NodeBlock = Block,
- UncheckedExtrinsic = UncheckedExtrinsic,
- {
- System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
- Logger: logger::{Pallet, Call, Event<T>},
- Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},
- }
- );
+impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>
+ for Pallet<T>
+{
+ type Address = TaskAddress<T::BlockNumber>;
+ type Hash = T::Hash;
- // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
- pub struct BaseFilter;
- impl Contains<Call> for BaseFilter {
- fn contains(call: &Call) -> bool {
- !matches!(call, Call::Logger(logger::Call::log { .. }))
- }
+ fn schedule_named(
+ id: Vec<u8>,
+ when: DispatchTime<T::BlockNumber>,
+ maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
+ priority: schedule::Priority,
+ origin: T::PalletsOrigin,
+ call: CallOrHashOf<T>,
+ ) -> Result<Self::Address, ()> {
+ let inner_id: ScheduledId = id
+ .try_into()
+ .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+ Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)
+ .map_err(|_| ())
}
- parameter_types! {
- pub const BlockHashCount: u64 = 250;
- pub BlockWeights: frame_system::limits::BlockWeights =
- frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);
+ fn cancel_named(id: Vec<u8>) -> Result<(), ()> {
+ let inner_id: ScheduledId = id
+ .try_into()
+ .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+ Self::do_cancel_named(None, inner_id).map_err(|_| ())
}
- impl system::Config for Test {
- type BaseCallFilter = BaseFilter;
- type BlockWeights = ();
- type BlockLength = ();
- type DbWeight = RocksDbWeight;
- type Origin = Origin;
- type Call = Call;
- type Index = u64;
- type BlockNumber = u64;
- type Hash = H256;
- type Hashing = BlakeTwo256;
- type AccountId = u64;
- type Lookup = IdentityLookup<Self::AccountId>;
- type Header = Header;
- type Event = Event;
- type BlockHashCount = BlockHashCount;
- type Version = ();
- type PalletInfo = PalletInfo;
- type AccountData = ();
- type OnNewAccount = ();
- type OnKilledAccount = ();
- type SystemWeightInfo = ();
- type SS58Prefix = ();
- type OnSetCode = ();
- type MaxConsumers = ConstU32<16>;
- }
- impl logger::Config for Test {
- type Event = Event;
- }
- parameter_types! {
- pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;
- pub const MaxScheduledPerBlock: u32 = 10;
- }
- ord_parameter_types! {
- pub const One: u64 = 1;
+
+ fn reschedule_named(
+ id: Vec<u8>,
+ when: DispatchTime<T::BlockNumber>,
+ ) -> Result<Self::Address, DispatchError> {
+ let inner_id: ScheduledId = id
+ .try_into()
+ .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+ Self::do_reschedule_named(inner_id, when)
}
- impl Config for Test {
- type Event = Event;
- type Origin = Origin;
- type PalletsOrigin = OriginCaller;
- type Call = Call;
- type MaximumWeight = MaximumSchedulerWeight;
- type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
- type MaxScheduledPerBlock = MaxScheduledPerBlock;
- type WeightInfo = ();
- type SponsorshipHandler = ();
+ fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {
+ let inner_id: ScheduledId = id
+ .try_into()
+ .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);
+ Lookup::<T>::get(inner_id)
+ .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))
+ .ok_or(())
}
}
pallets/scheduler/src/weights.rsdiffbeforeafterboth--- a/pallets/scheduler/src/weights.rs
+++ b/pallets/scheduler/src/weights.rs
@@ -1,23 +1,6 @@
-// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
-// This file is part of Unique Network.
-
-// Unique Network is free software: you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation, either version 3 of the License, or
-// (at your option) any later version.
-
-// Unique Network is distributed in the hope that it will be useful,
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-// GNU General Public License for more details.
-
-// You should have received a copy of the GNU General Public License
-// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-
-// Original license
// This file is part of Substrate.
-// Copyright (C) 2020-2021 Parity Technologies (UK) Ltd.
+// Copyright (C) 2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,13 +15,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-//! Weights for pallet_scheduler
-//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 2.0.0
-//! DATE: 2020-10-27, STEPS: `[50, ]`, REPEAT: 20, LOW RANGE: [], HIGH RANGE: []
-//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 128
+//! Autogenerated weights for pallet_scheduler
+//!
+//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
+//! DATE: 2022-01-31, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
// Executed Command:
-// target/release/substrate
+// ./target/production/substrate
// benchmark
// --chain=dev
// --steps=50
@@ -49,78 +33,332 @@
// --wasm-execution=compiled
// --heap-pages=4096
// --output=./frame/scheduler/src/weights.rs
-// --template=./.maintain/frame-weight-template.hbs
+// --template=.maintain/frame-weight-template.hbs
+// --header=HEADER-APACHE2
+// --raw
+#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(unused_parens)]
#![allow(unused_imports)]
-use frame_support::{
- traits::Get,
- weights::{Weight, constants::RocksDbWeight},
-};
+use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}};
use sp_std::marker::PhantomData;
/// Weight functions needed for pallet_scheduler.
pub trait WeightInfo {
- fn schedule(s: u32) -> Weight;
- fn cancel(s: u32) -> Weight;
- fn schedule_named(s: u32) -> Weight;
- fn cancel_named(s: u32) -> Weight;
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight;
+ fn on_initialize_named_resolved(s: u32, ) -> Weight;
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight;
+ fn on_initialize_resolved(s: u32, ) -> Weight;
+ fn on_initialize_named_aborted(s: u32, ) -> Weight;
+ fn on_initialize_aborted(s: u32, ) -> Weight;
+ fn on_initialize_periodic_named(s: u32, ) -> Weight;
+ fn on_initialize_periodic(s: u32, ) -> Weight;
+ fn on_initialize_named(s: u32, ) -> Weight;
+ fn on_initialize(s: u32, ) -> Weight;
+ fn schedule(s: u32, ) -> Weight;
+ fn cancel(s: u32, ) -> Weight;
+ fn schedule_named(s: u32, ) -> Weight;
+ fn cancel_named(s: u32, ) -> Weight;
}
/// Weights for pallet_scheduler using the Substrate node and recommended hardware.
pub struct SubstrateWeight<T>(PhantomData<T>);
impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
- fn schedule(s: u32) -> Weight {
- 35_029_000_u64
- .saturating_add(77_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(1_u64))
- .saturating_add(T::DbWeight::get().writes(1_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+ (11_587_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_resolved(s: u32, ) -> Weight {
+ (8_965_000 as Weight)
+ // Standard Error: 11_000
+ .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn cancel(s: u32) -> Weight {
- 31_419_000_u64
- .saturating_add(4_015_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(1_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+ (8_654_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_resolved(s: u32, ) -> Weight {
+ (9_303_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_aborted(s: u32, ) -> Weight {
+ (7_506_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ fn on_initialize_aborted(s: u32, ) -> Weight {
+ (8_046_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named(s: u32, ) -> Weight {
+ (13_704_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ fn on_initialize_periodic(s: u32, ) -> Weight {
+ (12_668_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named(s: u32, ) -> Weight {
+ (13_946_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn on_initialize(s: u32, ) -> Weight {
+ (13_151_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ (14_040_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ (14_376_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(1 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
- fn schedule_named(s: u32) -> Weight {
- 44_752_000_u64
- .saturating_add(123_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(2_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ (16_806_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
- fn cancel_named(s: u32) -> Weight {
- 35_712_000_u64
- .saturating_add(4_008_000_u64.saturating_mul(s as Weight))
- .saturating_add(T::DbWeight::get().reads(2_u64))
- .saturating_add(T::DbWeight::get().writes(2_u64))
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ (15_852_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(T::DbWeight::get().reads(2 as Weight))
+ .saturating_add(T::DbWeight::get().writes(2 as Weight))
}
}
// For backwards compatibility and tests
impl WeightInfo for () {
- fn schedule(s: u32) -> Weight {
- 35_029_000_u64
- .saturating_add(77_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(1_u64))
- .saturating_add(RocksDbWeight::get().writes(1_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named_resolved(s: u32, ) -> Weight {
+ (11_587_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((17_428_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((4 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_resolved(s: u32, ) -> Weight {
+ (8_965_000 as Weight)
+ // Standard Error: 11_000
+ .saturating_add((13_410_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn cancel(s: u32) -> Weight {
- 31_419_000_u64
- .saturating_add(4_015_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(1_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_periodic_resolved(s: u32, ) -> Weight {
+ (8_654_000 as Weight)
+ // Standard Error: 17_000
+ .saturating_add((14_990_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((3 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((3 as Weight).saturating_mul(s as Weight)))
}
- fn schedule_named(s: u32) -> Weight {
- 44_752_000_u64
- .saturating_add(123_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(2_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Preimage PreimageFor (r:1 w:1)
+ // Storage: Preimage StatusFor (r:1 w:1)
+ fn on_initialize_resolved(s: u32, ) -> Weight {
+ (9_303_000 as Weight)
+ // Standard Error: 10_000
+ .saturating_add((12_244_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((2 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
}
- fn cancel_named(s: u32) -> Weight {
- 35_712_000_u64
- .saturating_add(4_008_000_u64.saturating_mul(s as Weight))
- .saturating_add(RocksDbWeight::get().reads(2_u64))
- .saturating_add(RocksDbWeight::get().writes(2_u64))
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named_aborted(s: u32, ) -> Weight {
+ (7_506_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((5_208_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Preimage PreimageFor (r:1 w:0)
+ fn on_initialize_aborted(s: u32, ) -> Weight {
+ (8_046_000 as Weight)
+ // Standard Error: 3_000
+ .saturating_add((2_914_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_periodic_named(s: u32, ) -> Weight {
+ (13_704_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((8_186_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((2 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:2 w:2)
+ fn on_initialize_periodic(s: u32, ) -> Weight {
+ (12_668_000 as Weight)
+ // Standard Error: 5_000
+ .saturating_add((5_868_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().reads((1 as Weight).saturating_mul(s as Weight)))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn on_initialize_named(s: u32, ) -> Weight {
+ (13_946_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((4_367_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes((1 as Weight).saturating_mul(s as Weight)))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn on_initialize(s: u32, ) -> Weight {
+ (13_151_000 as Weight)
+ // Standard Error: 4_000
+ .saturating_add((3_455_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule(s: u32, ) -> Weight {
+ (14_040_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((89_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(1 as Weight))
+ }
+ // Storage: Scheduler Agenda (r:1 w:1)
+ // Storage: Scheduler Lookup (r:0 w:1)
+ fn cancel(s: u32, ) -> Weight {
+ (14_376_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((576_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(1 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn schedule_named(s: u32, ) -> Weight {
+ (16_806_000 as Weight)
+ // Standard Error: 1_000
+ .saturating_add((102_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
+ }
+ // Storage: Scheduler Lookup (r:1 w:1)
+ // Storage: Scheduler Agenda (r:1 w:1)
+ fn cancel_named(s: u32, ) -> Weight {
+ (15_852_000 as Weight)
+ // Standard Error: 2_000
+ .saturating_add((590_000 as Weight).saturating_mul(s as Weight))
+ .saturating_add(RocksDbWeight::get().reads(2 as Weight))
+ .saturating_add(RocksDbWeight::get().writes(2 as Weight))
}
}
runtime/opal/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53 OnMethodCall, Account as EVMAccount, FeeCalculator, GasWeightMapping,54};55pub use frame_support::{56 construct_runtime, match_types,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,68 },69};70use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};71use up_data_structs::*;72// use pallet_contracts::weights::WeightInfo;73// #[cfg(any(feature = "std", test))]74use frame_system::{75 self as frame_system, EnsureRoot, EnsureSigned,76 limits::{BlockWeights, BlockLength},77};78use sp_arithmetic::{79 traits::{BaseArithmetic, Unsigned},80};81use smallvec::smallvec;82use codec::{Encode, Decode};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;91pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9293// Polkadot imports94use pallet_xcm::XcmPassthrough;95use polkadot_parachain::primitives::Sibling;96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 impl_common_runtime_apis,120 types::*,121 constants::*,122 dispatch::{CollectionDispatchT, CollectionDispatch},123 sponsoring::UniqueSponsorshipHandler,124 eth_sponsoring::UniqueEthSponsorshipHandler,125 weights::CommonWeights,126};127128pub const RUNTIME_NAME: &str = "opal";129pub const TOKEN_SYMBOL: &str = "OPL";130131type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;132133impl RuntimeInstance for Runtime {134 type CrossAccountId = self::CrossAccountId;135 type TransactionConverter = self::TransactionConverter;136137 fn get_transaction_converter() -> TransactionConverter {138 TransactionConverter139 }140}141142/// The type for looking up accounts. We don't expect more than 4 billion of them, but you143/// never know...144pub type AccountIndex = u32;145146/// Balance of an account.147pub type Balance = u128;148149/// Index of a transaction in the chain.150pub type Index = u32;151152/// A hash of some data used by the chain.153pub type Hash = sp_core::H256;154155/// Digest item type.156pub type DigestItem = generic::DigestItem;157158/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know159/// the specifics of the runtime. They can then be made to be agnostic over specific formats160/// of data like extrinsics, allowing for them to continue syncing the network through upgrades161/// to even the core data structures.162pub mod opaque {163 use sp_std::prelude::*;164 use sp_runtime::impl_opaque_keys;165 use super::Aura;166167 pub use unique_runtime_common::types::*;168169 impl_opaque_keys! {170 pub struct SessionKeys {171 pub aura: Aura,172 }173 }174}175176/// This runtime version.177pub const VERSION: RuntimeVersion = RuntimeVersion {178 spec_name: create_runtime_str!(RUNTIME_NAME),179 impl_name: create_runtime_str!(RUNTIME_NAME),180 authoring_version: 1,181 spec_version: 922000,182 impl_version: 0,183 apis: RUNTIME_API_VERSIONS,184 transaction_version: 1,185 state_version: 0,186};187188#[derive(codec::Encode, codec::Decode)]189pub enum XCMPMessage<XAccountId, XBalance> {190 /// Transfer tokens to the given account from the Parachain account.191 TransferToken(XAccountId, XBalance),192}193194/// The version information used to identify this runtime when compiled natively.195#[cfg(feature = "std")]196pub fn native_version() -> NativeVersion {197 NativeVersion {198 runtime_version: VERSION,199 can_author_with: Default::default(),200 }201}202203type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;204205pub struct DealWithFees;206impl OnUnbalanced<NegativeImbalance> for DealWithFees {207 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {208 if let Some(fees) = fees_then_tips.next() {209 // for fees, 100% to treasury210 let mut split = fees.ration(100, 0);211 if let Some(tips) = fees_then_tips.next() {212 // for tips, if any, 100% to treasury213 tips.ration_merge_into(100, 0, &mut split);214 }215 Treasury::on_unbalanced(split.0);216 // Author::on_unbalanced(split.1);217 }218 }219}220221parameter_types! {222 pub const BlockHashCount: BlockNumber = 2400;223 pub RuntimeBlockLength: BlockLength =224 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228 .base_block(BlockExecutionWeight::get())229 .for_class(DispatchClass::all(), |weights| {230 weights.base_extrinsic = ExtrinsicBaseWeight::get();231 })232 .for_class(DispatchClass::Normal, |weights| {233 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234 })235 .for_class(DispatchClass::Operational, |weights| {236 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237 // Operational transactions have some extra reserved space, so that they238 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239 weights.reserved = Some(240 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241 );242 })243 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244 .build_or_panic();245 pub const Version: RuntimeVersion = VERSION;246 pub const SS58Prefix: u8 = 42;247}248249parameter_types! {250 pub const ChainId: u64 = 8882;251}252253pub struct FixedFee;254impl FeeCalculator for FixedFee {255 fn min_gas_price() -> (U256, u64) {256 (MIN_GAS_PRICE.into(), 0)257 }258}259260// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case261// (contract, which only writes a lot of data),262// approximating on top of our real store write weight263parameter_types! {264 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;265 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;266 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();267}268269/// Limiting EVM execution to 50% of block for substrate users and management tasks270/// EVM transaction consumes more weight than substrate's, so we can't rely on them being271/// scheduled fairly272const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);273parameter_types! {274 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());275}276277pub enum FixedGasWeightMapping {}278impl GasWeightMapping for FixedGasWeightMapping {279 fn gas_to_weight(gas: u64) -> Weight {280 gas.saturating_mul(WeightPerGas::get())281 }282 fn weight_to_gas(weight: Weight) -> u64 {283 weight / WeightPerGas::get()284 }285}286287impl pallet_evm::account::Config for Runtime {288 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;289 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;290 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;291}292293impl pallet_evm::Config for Runtime {294 type BlockGasLimit = BlockGasLimit;295 type FeeCalculator = FixedFee;296 type GasWeightMapping = FixedGasWeightMapping;297 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;298 type CallOrigin = EnsureAddressTruncated<Self>;299 type WithdrawOrigin = EnsureAddressTruncated<Self>;300 type AddressMapping = HashedAddressMapping<Self::Hashing>;301 type PrecompilesType = ();302 type PrecompilesValue = ();303 type Currency = Balances;304 type Event = Event;305 type OnMethodCall = (306 pallet_evm_migration::OnMethodCall<Self>,307 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,308 CollectionDispatchT<Self>,309 pallet_unique::eth::CollectionHelpersOnMethodCall<Self>,310 );311 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;312 type ChainId = ChainId;313 type Runner = pallet_evm::runner::stack::Runner<Self>;314 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;315 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;316 type FindAuthor = EthereumFindAuthor<Aura>;317}318319impl pallet_evm_migration::Config for Runtime {320 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;321}322323pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);324impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {325 fn find_author<'a, I>(digests: I) -> Option<H160>326 where327 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,328 {329 if let Some(author_index) = F::find_author(digests) {330 let authority_id = Aura::authorities()[author_index as usize].clone();331 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));332 }333 None334 }335}336337impl pallet_ethereum::Config for Runtime {338 type Event = Event;339 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;340}341342impl pallet_randomness_collective_flip::Config for Runtime {}343344impl frame_system::Config for Runtime {345 /// The data to be stored in an account.346 type AccountData = pallet_balances::AccountData<Balance>;347 /// The identifier used to distinguish between accounts.348 type AccountId = AccountId;349 /// The basic call filter to use in dispatchable.350 type BaseCallFilter = Everything;351 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).352 type BlockHashCount = BlockHashCount;353 /// The maximum length of a block (in bytes).354 type BlockLength = RuntimeBlockLength;355 /// The index type for blocks.356 type BlockNumber = BlockNumber;357 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.358 type BlockWeights = RuntimeBlockWeights;359 /// The aggregated dispatch type that is available for extrinsics.360 type Call = Call;361 /// The weight of database operations that the runtime can invoke.362 type DbWeight = RocksDbWeight;363 /// The ubiquitous event type.364 type Event = Event;365 /// The type for hashing blocks and tries.366 type Hash = Hash;367 /// The hashing algorithm used.368 type Hashing = BlakeTwo256;369 /// The header type.370 type Header = generic::Header<BlockNumber, BlakeTwo256>;371 /// The index type for storing how many extrinsics an account has signed.372 type Index = Index;373 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.374 type Lookup = AccountIdLookup<AccountId, ()>;375 /// What to do if an account is fully reaped from the system.376 type OnKilledAccount = ();377 /// What to do if a new account is created.378 type OnNewAccount = ();379 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;380 /// The ubiquitous origin type.381 type Origin = Origin;382 /// This type is being generated by `construct_runtime!`.383 type PalletInfo = PalletInfo;384 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.385 type SS58Prefix = SS58Prefix;386 /// Weight information for the extrinsics of this pallet.387 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;388 /// Version of the runtime.389 type Version = Version;390 type MaxConsumers = ConstU32<16>;391}392393parameter_types! {394 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;395}396397impl pallet_timestamp::Config for Runtime {398 /// A timestamp: milliseconds since the unix epoch.399 type Moment = u64;400 type OnTimestampSet = ();401 type MinimumPeriod = MinimumPeriod;402 type WeightInfo = ();403}404405parameter_types! {406 // pub const ExistentialDeposit: u128 = 500;407 pub const ExistentialDeposit: u128 = 0;408 pub const MaxLocks: u32 = 50;409}410411impl pallet_balances::Config for Runtime {412 type MaxLocks = MaxLocks;413 type MaxReserves = ();414 type ReserveIdentifier = [u8; 8];415 /// The type for recording an account's balance.416 type Balance = Balance;417 /// The ubiquitous event type.418 type Event = Event;419 type DustRemoval = Treasury;420 type ExistentialDeposit = ExistentialDeposit;421 type AccountStore = System;422 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;423}424425pub const fn deposit(items: u32, bytes: u32) -> Balance {426 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE427}428429/*430parameter_types! {431 pub TombstoneDeposit: Balance = deposit(432 1,433 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,434 );435 pub DepositPerContract: Balance = TombstoneDeposit::get();436 pub const DepositPerStorageByte: Balance = deposit(0, 1);437 pub const DepositPerStorageItem: Balance = deposit(1, 0);438 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);439 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;440 pub const SignedClaimHandicap: u32 = 2;441 pub const MaxDepth: u32 = 32;442 pub const MaxValueSize: u32 = 16 * 1024;443 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb444 // The lazy deletion runs inside on_initialize.445 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *446 RuntimeBlockWeights::get().max_block;447 // The weight needed for decoding the queue should be less or equal than a fifth448 // of the overall weight dedicated to the lazy deletion.449 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (450 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -451 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)452 )) / 5) as u32;453 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();454}455456impl pallet_contracts::Config for Runtime {457 type Time = Timestamp;458 type Randomness = RandomnessCollectiveFlip;459 type Currency = Balances;460 type Event = Event;461 type RentPayment = ();462 type SignedClaimHandicap = SignedClaimHandicap;463 type TombstoneDeposit = TombstoneDeposit;464 type DepositPerContract = DepositPerContract;465 type DepositPerStorageByte = DepositPerStorageByte;466 type DepositPerStorageItem = DepositPerStorageItem;467 type RentFraction = RentFraction;468 type SurchargeReward = SurchargeReward;469 type WeightPrice = pallet_transaction_payment::Pallet<Self>;470 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;471 type ChainExtension = NFTExtension;472 type DeletionQueueDepth = DeletionQueueDepth;473 type DeletionWeightLimit = DeletionWeightLimit;474 type Schedule = Schedule;475 type CallStack = [pallet_contracts::Frame<Self>; 31];476}477*/478479parameter_types! {480 /// This value increases the priority of `Operational` transactions by adding481 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.482 pub const OperationalFeeMultiplier: u8 = 5;483}484485/// Linear implementor of `WeightToFeePolynomial`486pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);487488impl<T> WeightToFeePolynomial for LinearFee<T>489where490 T: BaseArithmetic + From<u32> + Copy + Unsigned,491{492 type Balance = T;493494 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {495 smallvec!(WeightToFeeCoefficient {496 // Targeting 0.1 Unique per NFT transfer497 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),498 coeff_frac: Perbill::zero(),499 negative: false,500 degree: 1,501 })502 }503}504505impl pallet_transaction_payment::Config for Runtime {506 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;507 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;508 type OperationalFeeMultiplier = OperationalFeeMultiplier;509 type WeightToFee = LinearFee<Balance>;510 type FeeMultiplierUpdate = ();511}512513parameter_types! {514 pub const ProposalBond: Permill = Permill::from_percent(5);515 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;516 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;517 pub const SpendPeriod: BlockNumber = 5 * MINUTES;518 pub const Burn: Permill = Permill::from_percent(0);519 pub const TipCountdown: BlockNumber = 1 * DAYS;520 pub const TipFindersFee: Percent = Percent::from_percent(20);521 pub const TipReportDepositBase: Balance = 1 * UNIQUE;522 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;523 pub const BountyDepositBase: Balance = 1 * UNIQUE;524 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;525 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");526 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;527 pub const MaximumReasonLength: u32 = 16384;528 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);529 pub const BountyValueMinimum: Balance = 5 * UNIQUE;530 pub const MaxApprovals: u32 = 100;531}532533impl pallet_treasury::Config for Runtime {534 type PalletId = TreasuryModuleId;535 type Currency = Balances;536 type ApproveOrigin = EnsureRoot<AccountId>;537 type RejectOrigin = EnsureRoot<AccountId>;538 type Event = Event;539 type OnSlash = ();540 type ProposalBond = ProposalBond;541 type ProposalBondMinimum = ProposalBondMinimum;542 type ProposalBondMaximum = ProposalBondMaximum;543 type SpendPeriod = SpendPeriod;544 type Burn = Burn;545 type BurnDestination = ();546 type SpendFunds = ();547 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;548 type MaxApprovals = MaxApprovals;549}550551impl pallet_sudo::Config for Runtime {552 type Event = Event;553 type Call = Call;554}555556pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);557558impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider559 for RelayChainBlockNumberProvider<T>560{561 type BlockNumber = BlockNumber;562563 fn current_block_number() -> Self::BlockNumber {564 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()565 .map(|d| d.relay_parent_number)566 .unwrap_or_default()567 }568}569570parameter_types! {571 pub const MinVestedTransfer: Balance = 10 * UNIQUE;572 pub const MaxVestingSchedules: u32 = 28;573}574575impl orml_vesting::Config for Runtime {576 type Event = Event;577 type Currency = pallet_balances::Pallet<Runtime>;578 type MinVestedTransfer = MinVestedTransfer;579 type VestedTransferOrigin = EnsureSigned<AccountId>;580 type WeightInfo = ();581 type MaxVestingSchedules = MaxVestingSchedules;582 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;583}584585parameter_types! {586 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;587 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;588}589590impl cumulus_pallet_parachain_system::Config for Runtime {591 type Event = Event;592 type SelfParaId = parachain_info::Pallet<Self>;593 type OnSystemEvent = ();594 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<595 // MaxDownwardMessageWeight,596 // XcmExecutor<XcmConfig>,597 // Call,598 // >;599 type OutboundXcmpMessageSource = XcmpQueue;600 type DmpMessageHandler = DmpQueue;601 type ReservedDmpWeight = ReservedDmpWeight;602 type ReservedXcmpWeight = ReservedXcmpWeight;603 type XcmpMessageHandler = XcmpQueue;604}605606impl parachain_info::Config for Runtime {}607608impl cumulus_pallet_aura_ext::Config for Runtime {}609610parameter_types! {611 pub const RelayLocation: MultiLocation = MultiLocation::parent();612 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;613 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();614 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();615}616617/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used618/// when determining ownership of accounts for asset transacting and when attempting to use XCM619/// `Transact` in order to determine the dispatch Origin.620pub type LocationToAccountId = (621 // The parent (Relay-chain) origin converts to the default `AccountId`.622 ParentIsPreset<AccountId>,623 // Sibling parachain origins convert to AccountId via the `ParaId::into`.624 SiblingParachainConvertsVia<Sibling, AccountId>,625 // Straight up local `AccountId32` origins just alias directly to `AccountId`.626 AccountId32Aliases<RelayNetwork, AccountId>,627);628629pub struct OnlySelfCurrency;630impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {631 fn matches_fungible(a: &MultiAsset) -> Option<B> {632 match (&a.id, &a.fun) {633 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),634 _ => None,635 }636 }637}638639/// Means for transacting assets on this chain.640pub type LocalAssetTransactor = CurrencyAdapter<641 // Use this currency:642 Balances,643 // Use this currency when it is a fungible asset matching the given location or name:644 OnlySelfCurrency,645 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:646 LocationToAccountId,647 // Our chain's account ID type (we can't get away without mentioning it explicitly):648 AccountId,649 // We don't track any teleports.650 (),651>;652653/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,654/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can655/// biases the kind of local `Origin` it will become.656pub type XcmOriginToTransactDispatchOrigin = (657 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location658 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for659 // foreign chains who want to have a local sovereign account on this chain which they control.660 SovereignSignedViaLocation<LocationToAccountId, Origin>,661 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when662 // recognised.663 RelayChainAsNative<RelayOrigin, Origin>,664 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when665 // recognised.666 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,667 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a668 // transaction from the Root origin.669 ParentAsSuperuser<Origin>,670 // Native signed account converter; this just converts an `AccountId32` origin into a normal671 // `Origin::Signed` origin of the same 32-byte value.672 SignedAccountId32AsNative<RelayNetwork, Origin>,673 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.674 XcmPassthrough<Origin>,675);676677parameter_types! {678 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.679 pub UnitWeightCost: Weight = 1_000_000;680 // 1200 UNIQUEs buy 1 second of weight.681 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);682 pub const MaxInstructions: u32 = 100;683 pub const MaxAuthorities: u32 = 100_000;684}685686match_types! {687 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {688 MultiLocation { parents: 1, interior: Here } |689 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }690 };691}692693pub type Barrier = (694 TakeWeightCredit,695 AllowTopLevelPaidExecutionFrom<Everything>,696 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,697 // ^^^ Parent & its unit plurality gets free execution698);699700pub struct UsingOnlySelfCurrencyComponents<701 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,702 AssetId: Get<MultiLocation>,703 AccountId,704 Currency: CurrencyT<AccountId>,705 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,706>(707 Weight,708 Currency::Balance,709 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,710);711impl<712 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,713 AssetId: Get<MultiLocation>,714 AccountId,715 Currency: CurrencyT<AccountId>,716 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,717 > WeightTrader718 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>719{720 fn new() -> Self {721 Self(0, Zero::zero(), PhantomData)722 }723724 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {725 let amount = WeightToFee::calc(&weight);726 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;727728 // location to this parachain through relay chain729 let option1: xcm::v1::AssetId = Concrete(MultiLocation {730 parents: 1,731 interior: X1(Parachain(ParachainInfo::parachain_id().into())),732 });733 // direct location734 let option2: xcm::v1::AssetId = Concrete(MultiLocation {735 parents: 0,736 interior: Here,737 });738739 let required = if payment.fungible.contains_key(&option1) {740 (option1, u128_amount).into()741 } else if payment.fungible.contains_key(&option2) {742 (option2, u128_amount).into()743 } else {744 (Concrete(MultiLocation::default()), u128_amount).into()745 };746747 let unused = payment748 .checked_sub(required)749 .map_err(|_| XcmError::TooExpensive)?;750 self.0 = self.0.saturating_add(weight);751 self.1 = self.1.saturating_add(amount);752 Ok(unused)753 }754755 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {756 let weight = weight.min(self.0);757 let amount = WeightToFee::calc(&weight);758 self.0 -= weight;759 self.1 = self.1.saturating_sub(amount);760 let amount: u128 = amount.saturated_into();761 if amount > 0 {762 Some((AssetId::get(), amount).into())763 } else {764 None765 }766 }767}768impl<769 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,770 AssetId: Get<MultiLocation>,771 AccountId,772 Currency: CurrencyT<AccountId>,773 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,774 > Drop775 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>776{777 fn drop(&mut self) {778 OnUnbalanced::on_unbalanced(Currency::issue(self.1));779 }780}781782pub struct XcmConfig;783impl Config for XcmConfig {784 type Call = Call;785 type XcmSender = XcmRouter;786 // How to withdraw and deposit an asset.787 type AssetTransactor = LocalAssetTransactor;788 type OriginConverter = XcmOriginToTransactDispatchOrigin;789 type IsReserve = NativeAsset;790 type IsTeleporter = (); // Teleportation is disabled791 type LocationInverter = LocationInverter<Ancestry>;792 type Barrier = Barrier;793 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;794 type Trader = UsingOnlySelfCurrencyComponents<795 IdentityFee<Balance>,796 RelayLocation,797 AccountId,798 Balances,799 (),800 >;801 type ResponseHandler = (); // Don't handle responses for now.802 type SubscriptionService = PolkadotXcm;803804 type AssetTrap = PolkadotXcm;805 type AssetClaims = PolkadotXcm;806}807808// parameter_types! {809// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;810// }811812/// No local origins on this chain are allowed to dispatch XCM sends/executions.813pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);814815/// The means for routing XCM messages which are not for local execution into the right message816/// queues.817pub type XcmRouter = (818 // Two routers - use UMP to communicate with the relay chain:819 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,820 // ..and XCMP to communicate with the sibling chains.821 XcmpQueue,822);823824impl pallet_evm_coder_substrate::Config for Runtime {}825826impl pallet_xcm::Config for Runtime {827 type Event = Event;828 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;829 type XcmRouter = XcmRouter;830 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;831 type XcmExecuteFilter = Everything;832 type XcmExecutor = XcmExecutor<XcmConfig>;833 type XcmTeleportFilter = Everything;834 type XcmReserveTransferFilter = Everything;835 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;836 type LocationInverter = LocationInverter<Ancestry>;837 type Origin = Origin;838 type Call = Call;839 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;840 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;841}842843impl cumulus_pallet_xcm::Config for Runtime {844 type Event = Event;845 type XcmExecutor = XcmExecutor<XcmConfig>;846}847848impl cumulus_pallet_xcmp_queue::Config for Runtime {849 type WeightInfo = ();850 type Event = Event;851 type XcmExecutor = XcmExecutor<XcmConfig>;852 type ChannelInfo = ParachainSystem;853 type VersionWrapper = ();854 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;855 type ControllerOrigin = EnsureRoot<AccountId>;856 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;857}858859impl cumulus_pallet_dmp_queue::Config for Runtime {860 type Event = Event;861 type XcmExecutor = XcmExecutor<XcmConfig>;862 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;863}864865impl pallet_aura::Config for Runtime {866 type AuthorityId = AuraId;867 type DisabledValidators = ();868 type MaxAuthorities = MaxAuthorities;869}870871parameter_types! {872 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();873 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;874}875876impl pallet_common::Config for Runtime {877 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;878 type Event = Event;879 type Currency = Balances;880 type CollectionCreationPrice = CollectionCreationPrice;881 type TreasuryAccountId = TreasuryAccountId;882 type CollectionDispatch = CollectionDispatchT<Self>;883884 type EvmTokenAddressMapping = EvmTokenAddressMapping;885 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;886 type ContractAddress = EvmCollectionHelpersAddress;887}888889impl pallet_structure::Config for Runtime {890 type Event = Event;891 type Call = Call;892 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;893}894895impl pallet_fungible::Config for Runtime {896 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;897}898impl pallet_refungible::Config for Runtime {899 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;900}901impl pallet_nonfungible::Config for Runtime {902 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;903}904905/*906TODO free RMRK!907impl pallet_proxy_rmrk_core::Config for Runtime {908 type Event = Event;909}910911impl pallet_proxy_rmrk_equip::Config for Runtime {912 type Event = Event;913}*/914915impl pallet_unique::Config for Runtime {916 type Event = Event;917 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;918 type CommonWeightInfo = CommonWeights<Self>;919}920921parameter_types! {922 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied923}924925/// Used for the pallet inflation926impl pallet_inflation::Config for Runtime {927 type Currency = Balances;928 type TreasuryAccountId = TreasuryAccountId;929 type InflationBlockInterval = InflationBlockInterval;930 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;931}932933// parameter_types! {934// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *935// RuntimeBlockWeights::get().max_block;936// pub const MaxScheduledPerBlock: u32 = 50;937// }938939type EvmSponsorshipHandler = (940 UniqueEthSponsorshipHandler<Runtime>,941 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,942);943type SponsorshipHandler = (944 UniqueSponsorshipHandler<Runtime>,945 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,946 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,947);948949// impl pallet_unq_scheduler::Config for Runtime {950// type Event = Event;951// type Origin = Origin;952// type PalletsOrigin = OriginCaller;953// type Call = Call;954// type MaximumWeight = MaximumSchedulerWeight;955// type ScheduleOrigin = EnsureSigned<AccountId>;956// type MaxScheduledPerBlock = MaxScheduledPerBlock;957// type SponsorshipHandler = SponsorshipHandler;958// type WeightInfo = ();959// }960961impl pallet_evm_transaction_payment::Config for Runtime {962 type EvmSponsorshipHandler = EvmSponsorshipHandler;963 type Currency = Balances;964}965966impl pallet_charge_transaction::Config for Runtime {967 type SponsorshipHandler = SponsorshipHandler;968}969970// impl pallet_contract_helpers::Config for Runtime {971// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;972// }973974parameter_types! {975 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049976 pub const HelpersContractAddress: H160 = H160([977 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,978 ]);979980 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f981 pub const EvmCollectionHelpersAddress: H160 = H160([982 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,983 ]);984}985986impl pallet_evm_contract_helpers::Config for Runtime {987 type ContractAddress = HelpersContractAddress;988 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;989}990991construct_runtime!(992 pub enum Runtime where993 Block = Block,994 NodeBlock = opaque::Block,995 UncheckedExtrinsic = UncheckedExtrinsic996 {997 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,998 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,9991000 Aura: pallet_aura::{Pallet, Config<T>} = 22,1001 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10021003 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1004 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1005 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1006 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1007 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1008 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1009 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1010 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1011 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1012 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10131014 // XCM helpers.1015 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1016 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1017 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1018 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10191020 // Unique Pallets1021 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1022 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1023 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1024 // free = 631025 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1026 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1027 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1028 Fungible: pallet_fungible::{Pallet, Storage} = 67,1029 Refungible: pallet_refungible::{Pallet, Storage} = 68,1030 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1031 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1032 /* TODO free RMRK!1033 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1034 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,1035 */10361037 // Frontier1038 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1039 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10401041 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1042 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1043 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1044 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1045 }1046);10471048pub struct TransactionConverter;10491050impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1051 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1052 UncheckedExtrinsic::new_unsigned(1053 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1054 )1055 }1056}10571058impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1059 fn convert_transaction(1060 &self,1061 transaction: pallet_ethereum::Transaction,1062 ) -> opaque::UncheckedExtrinsic {1063 let extrinsic = UncheckedExtrinsic::new_unsigned(1064 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1065 );1066 let encoded = extrinsic.encode();1067 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1068 .expect("Encoded extrinsic is always valid")1069 }1070}10711072/// The address format for describing accounts.1073pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1074/// Block header type as expected by this runtime.1075pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1076/// Block type as expected by this runtime.1077pub type Block = generic::Block<Header, UncheckedExtrinsic>;1078/// A Block signed with a Justification1079pub type SignedBlock = generic::SignedBlock<Block>;1080/// BlockId type as expected by this runtime.1081pub type BlockId = generic::BlockId<Block>;1082/// The SignedExtension to the basic transaction logic.1083pub type SignedExtra = (1084 frame_system::CheckSpecVersion<Runtime>,1085 // system::CheckTxVersion<Runtime>,1086 frame_system::CheckGenesis<Runtime>,1087 frame_system::CheckEra<Runtime>,1088 frame_system::CheckNonce<Runtime>,1089 frame_system::CheckWeight<Runtime>,1090 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1091 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1092 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1093);1094/// Unchecked extrinsic type as expected by this runtime.1095pub type UncheckedExtrinsic =1096 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1097/// Extrinsic type that has already been checked.1098pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1099/// Executive: handles dispatch to the various modules.1100pub type Executive = frame_executive::Executive<1101 Runtime,1102 Block,1103 frame_system::ChainContext<Runtime>,1104 Runtime,1105 AllPalletsReversedWithSystemFirst,1106>;11071108impl_opaque_keys! {1109 pub struct SessionKeys {1110 pub aura: Aura,1111 }1112}11131114impl fp_self_contained::SelfContainedCall for Call {1115 type SignedInfo = H160;11161117 fn is_self_contained(&self) -> bool {1118 match self {1119 Call::Ethereum(call) => call.is_self_contained(),1120 _ => false,1121 }1122 }11231124 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1125 match self {1126 Call::Ethereum(call) => call.check_self_contained(),1127 _ => None,1128 }1129 }11301131 fn validate_self_contained(1132 &self,1133 info: &Self::SignedInfo,1134 dispatch_info: &DispatchInfoOf<Call>,1135 len: usize,1136 ) -> Option<TransactionValidity> {1137 match self {1138 Call::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),1139 _ => None,1140 }1141 }11421143 fn pre_dispatch_self_contained(1144 &self,1145 info: &Self::SignedInfo,1146 ) -> Option<Result<(), TransactionValidityError>> {1147 match self {1148 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1149 _ => None,1150 }1151 }11521153 fn apply_self_contained(1154 self,1155 info: Self::SignedInfo,1156 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1157 match self {1158 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1159 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1160 )),1161 _ => None,1162 }1163 }1164}11651166macro_rules! dispatch_unique_runtime {1167 ($collection:ident.$method:ident($($name:ident),*)) => {{1168 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1169 let dispatch = collection.as_dyn();11701171 Ok::<_, DispatchError>(dispatch.$method($($name),*))1172 }};1173}11741175impl_common_runtime_apis!();11761177struct CheckInherents;11781179impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1180 fn check_inherents(1181 block: &Block,1182 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1183 ) -> sp_inherents::CheckInherentsResult {1184 let relay_chain_slot = relay_state_proof1185 .read_slot()1186 .expect("Could not read the relay chain slot from the proof");11871188 let inherent_data =1189 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1190 relay_chain_slot,1191 sp_std::time::Duration::from_secs(6),1192 )1193 .create_inherent_data()1194 .expect("Could not create the timestamp inherent data");11951196 inherent_data.check_extrinsics(block)1197 }1198}11991200cumulus_pallet_parachain_system::register_validate_block!(1201 Runtime = Runtime,1202 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1203 CheckInherents = CheckInherents,1204);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//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31use fp_self_contained::*;32use sp_runtime::traits::{Member};33// #[cfg(any(feature = "std", test))]34// pub use sp_runtime::BuildStorage;3536use sp_runtime::{37 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,38 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},39 transaction_validity::{TransactionSource, TransactionValidity},40 ApplyExtrinsicResult, RuntimeAppPublic,41};4243use sp_std::prelude::*;4445#[cfg(feature = "std")]46use sp_version::NativeVersion;47use sp_version::RuntimeVersion;48pub use pallet_transaction_payment::{49 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,50};51// A few exports that help ease life for downstream crates.52pub use pallet_balances::Call as BalancesCall;53pub use pallet_evm::{54 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,55 OnMethodCall, Account as EVMAccount, FeeCalculator, GasWeightMapping,56};57pub use frame_support::{58 construct_runtime, match_types,59 dispatch::DispatchResult,60 PalletId, parameter_types, StorageValue, ConsensusEngineId,61 traits::{62 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,63 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,64 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,65 },66 weights::{67 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},68 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,69 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,70 },71};72use pallet_unq_scheduler::DispatchCall;73use up_data_structs::{74 CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,75 CollectionStats, RpcCollection,76 mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping},77};7879// use pallet_contracts::weights::WeightInfo;80// #[cfg(any(feature = "std", test))]81use frame_system::{82 self as frame_system, EnsureRoot, EnsureSigned,83 limits::{BlockWeights, BlockLength},84};85use sp_arithmetic::{86 traits::{BaseArithmetic, Unsigned},87};88use smallvec::smallvec;89// use scale_info::TypeInfo;90use codec::{Encode, Decode};91use fp_rpc::TransactionStatus;92use sp_runtime::{93 traits::{94 Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, DispatchInfoOf,95 Saturating, CheckedConversion,96 },97 generic::Era,98 transaction_validity::TransactionValidityError,99 DispatchErrorWithPostInfo, SaturatedConversion,100};101102// pub use pallet_timestamp::Call as TimestampCall;103pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;104105// Polkadot imports106use pallet_xcm::XcmPassthrough;107use polkadot_parachain::primitives::Sibling;108use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};109use xcm_builder::{110 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,111 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,112 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,113 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,114 ParentIsPreset,115};116use xcm_executor::{Config, XcmExecutor, Assets};117use sp_std::{cmp::Ordering, marker::PhantomData};118119use xcm::latest::{120 // Xcm,121 AssetId::{Concrete},122 Fungibility::Fungible as XcmFungible,123 MultiAsset,124 Error as XcmError,125};126use xcm_executor::traits::{MatchesFungible, WeightTrader};127//use xcm_executor::traits::MatchesFungible;128129use unique_runtime_common::{130 impl_common_runtime_apis,131 types::*,132 constants::*,133 dispatch::{CollectionDispatchT, CollectionDispatch},134 sponsoring::UniqueSponsorshipHandler,135 eth_sponsoring::UniqueEthSponsorshipHandler,136 weights::CommonWeights,137};138139pub const RUNTIME_NAME: &str = "opal";140pub const TOKEN_SYMBOL: &str = "OPL";141142type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;143144impl RuntimeInstance for Runtime {145 type CrossAccountId = self::CrossAccountId;146 type TransactionConverter = self::TransactionConverter;147148 fn get_transaction_converter() -> TransactionConverter {149 TransactionConverter150 }151}152153/// The type for looking up accounts. We don't expect more than 4 billion of them, but you154/// never know...155pub type AccountIndex = u32;156157/// Balance of an account.158pub type Balance = u128;159160/// Index of a transaction in the chain.161pub type Index = u32;162163/// A hash of some data used by the chain.164pub type Hash = sp_core::H256;165166/// Digest item type.167pub type DigestItem = generic::DigestItem;168169/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know170/// the specifics of the runtime. They can then be made to be agnostic over specific formats171/// of data like extrinsics, allowing for them to continue syncing the network through upgrades172/// to even the core data structures.173pub mod opaque {174 use sp_std::prelude::*;175 use sp_runtime::impl_opaque_keys;176 use super::Aura;177178 pub use unique_runtime_common::types::*;179180 impl_opaque_keys! {181 pub struct SessionKeys {182 pub aura: Aura,183 }184 }185}186187/// This runtime version.188pub const VERSION: RuntimeVersion = RuntimeVersion {189 spec_name: create_runtime_str!(RUNTIME_NAME),190 impl_name: create_runtime_str!(RUNTIME_NAME),191 authoring_version: 1,192 spec_version: 922000,193 impl_version: 0,194 apis: RUNTIME_API_VERSIONS,195 transaction_version: 1,196 state_version: 0,197};198199#[derive(codec::Encode, codec::Decode)]200pub enum XCMPMessage<XAccountId, XBalance> {201 /// Transfer tokens to the given account from the Parachain account.202 TransferToken(XAccountId, XBalance),203}204205/// The version information used to identify this runtime when compiled natively.206#[cfg(feature = "std")]207pub fn native_version() -> NativeVersion {208 NativeVersion {209 runtime_version: VERSION,210 can_author_with: Default::default(),211 }212}213214type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;215216pub struct DealWithFees;217impl OnUnbalanced<NegativeImbalance> for DealWithFees {218 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {219 if let Some(fees) = fees_then_tips.next() {220 // for fees, 100% to treasury221 let mut split = fees.ration(100, 0);222 if let Some(tips) = fees_then_tips.next() {223 // for tips, if any, 100% to treasury224 tips.ration_merge_into(100, 0, &mut split);225 }226 Treasury::on_unbalanced(split.0);227 // Author::on_unbalanced(split.1);228 }229 }230}231232parameter_types! {233 pub const BlockHashCount: BlockNumber = 2400;234 pub RuntimeBlockLength: BlockLength =235 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);236 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);237 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;238 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()239 .base_block(BlockExecutionWeight::get())240 .for_class(DispatchClass::all(), |weights| {241 weights.base_extrinsic = ExtrinsicBaseWeight::get();242 })243 .for_class(DispatchClass::Normal, |weights| {244 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);245 })246 .for_class(DispatchClass::Operational, |weights| {247 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);248 // Operational transactions have some extra reserved space, so that they249 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.250 weights.reserved = Some(251 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT252 );253 })254 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)255 .build_or_panic();256 pub const Version: RuntimeVersion = VERSION;257 pub const SS58Prefix: u8 = 42;258}259260parameter_types! {261 pub const ChainId: u64 = 8882;262}263264pub struct FixedFee;265impl FeeCalculator for FixedFee {266 fn min_gas_price() -> (U256, u64) {267 (MIN_GAS_PRICE.into(), 0)268 }269}270271// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case272// (contract, which only writes a lot of data),273// approximating on top of our real store write weight274parameter_types! {275 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;276 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;277 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();278}279280/// Limiting EVM execution to 50% of block for substrate users and management tasks281/// EVM transaction consumes more weight than substrate's, so we can't rely on them being282/// scheduled fairly283const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);284parameter_types! {285 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());286}287288pub enum FixedGasWeightMapping {}289impl GasWeightMapping for FixedGasWeightMapping {290 fn gas_to_weight(gas: u64) -> Weight {291 gas.saturating_mul(WeightPerGas::get())292 }293 fn weight_to_gas(weight: Weight) -> u64 {294 weight / WeightPerGas::get()295 }296}297298impl pallet_evm::account::Config for Runtime {299 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;300 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;301 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;302}303304impl pallet_evm::Config for Runtime {305 type BlockGasLimit = BlockGasLimit;306 type FeeCalculator = FixedFee;307 type GasWeightMapping = FixedGasWeightMapping;308 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;309 type CallOrigin = EnsureAddressTruncated<Self>;310 type WithdrawOrigin = EnsureAddressTruncated<Self>;311 type AddressMapping = HashedAddressMapping<Self::Hashing>;312 type PrecompilesType = ();313 type PrecompilesValue = ();314 type Currency = Balances;315 type Event = Event;316 type OnMethodCall = (317 pallet_evm_migration::OnMethodCall<Self>,318 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,319 CollectionDispatchT<Self>,320 pallet_unique::eth::CollectionHelpersOnMethodCall<Self>,321 );322 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;323 type ChainId = ChainId;324 type Runner = pallet_evm::runner::stack::Runner<Self>;325 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;326 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;327 type FindAuthor = EthereumFindAuthor<Aura>;328}329330impl pallet_evm_migration::Config for Runtime {331 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;332}333334pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);335impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {336 fn find_author<'a, I>(digests: I) -> Option<H160>337 where338 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,339 {340 if let Some(author_index) = F::find_author(digests) {341 let authority_id = Aura::authorities()[author_index as usize].clone();342 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));343 }344 None345 }346}347348impl pallet_ethereum::Config for Runtime {349 type Event = Event;350 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;351}352353impl pallet_randomness_collective_flip::Config for Runtime {}354355impl frame_system::Config for Runtime {356 /// The data to be stored in an account.357 type AccountData = pallet_balances::AccountData<Balance>;358 /// The identifier used to distinguish between accounts.359 type AccountId = AccountId;360 /// The basic call filter to use in dispatchable.361 type BaseCallFilter = Everything;362 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).363 type BlockHashCount = BlockHashCount;364 /// The maximum length of a block (in bytes).365 type BlockLength = RuntimeBlockLength;366 /// The index type for blocks.367 type BlockNumber = BlockNumber;368 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.369 type BlockWeights = RuntimeBlockWeights;370 /// The aggregated dispatch type that is available for extrinsics.371 type Call = Call;372 /// The weight of database operations that the runtime can invoke.373 type DbWeight = RocksDbWeight;374 /// The ubiquitous event type.375 type Event = Event;376 /// The type for hashing blocks and tries.377 type Hash = Hash;378 /// The hashing algorithm used.379 type Hashing = BlakeTwo256;380 /// The header type.381 type Header = generic::Header<BlockNumber, BlakeTwo256>;382 /// The index type for storing how many extrinsics an account has signed.383 type Index = Index;384 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.385 type Lookup = AccountIdLookup<AccountId, ()>;386 /// What to do if an account is fully reaped from the system.387 type OnKilledAccount = ();388 /// What to do if a new account is created.389 type OnNewAccount = ();390 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;391 /// The ubiquitous origin type.392 type Origin = Origin;393 /// This type is being generated by `construct_runtime!`.394 type PalletInfo = PalletInfo;395 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.396 type SS58Prefix = SS58Prefix;397 /// Weight information for the extrinsics of this pallet.398 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;399 /// Version of the runtime.400 type Version = Version;401 type MaxConsumers = ConstU32<16>;402}403404parameter_types! {405 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;406}407408impl pallet_timestamp::Config for Runtime {409 /// A timestamp: milliseconds since the unix epoch.410 type Moment = u64;411 type OnTimestampSet = ();412 type MinimumPeriod = MinimumPeriod;413 type WeightInfo = ();414}415416parameter_types! {417 // pub const ExistentialDeposit: u128 = 500;418 pub const ExistentialDeposit: u128 = 0;419 pub const MaxLocks: u32 = 50;420 pub const MaxReserves: u32 = 50;421}422423impl pallet_balances::Config for Runtime {424 type MaxLocks = MaxLocks;425 type MaxReserves = MaxReserves;426 type ReserveIdentifier = [u8; 16];427 /// The type for recording an account's balance.428 type Balance = Balance;429 /// The ubiquitous event type.430 type Event = Event;431 type DustRemoval = Treasury;432 type ExistentialDeposit = ExistentialDeposit;433 type AccountStore = System;434 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;435}436437pub const fn deposit(items: u32, bytes: u32) -> Balance {438 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE439}440441/*442parameter_types! {443 pub TombstoneDeposit: Balance = deposit(444 1,445 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,446 );447 pub DepositPerContract: Balance = TombstoneDeposit::get();448 pub const DepositPerStorageByte: Balance = deposit(0, 1);449 pub const DepositPerStorageItem: Balance = deposit(1, 0);450 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);451 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;452 pub const SignedClaimHandicap: u32 = 2;453 pub const MaxDepth: u32 = 32;454 pub const MaxValueSize: u32 = 16 * 1024;455 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb456 // The lazy deletion runs inside on_initialize.457 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *458 RuntimeBlockWeights::get().max_block;459 // The weight needed for decoding the queue should be less or equal than a fifth460 // of the overall weight dedicated to the lazy deletion.461 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (462 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -463 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)464 )) / 5) as u32;465 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();466}467468impl pallet_contracts::Config for Runtime {469 type Time = Timestamp;470 type Randomness = RandomnessCollectiveFlip;471 type Currency = Balances;472 type Event = Event;473 type RentPayment = ();474 type SignedClaimHandicap = SignedClaimHandicap;475 type TombstoneDeposit = TombstoneDeposit;476 type DepositPerContract = DepositPerContract;477 type DepositPerStorageByte = DepositPerStorageByte;478 type DepositPerStorageItem = DepositPerStorageItem;479 type RentFraction = RentFraction;480 type SurchargeReward = SurchargeReward;481 type WeightPrice = pallet_transaction_payment::Pallet<Self>;482 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;483 type ChainExtension = NFTExtension;484 type DeletionQueueDepth = DeletionQueueDepth;485 type DeletionWeightLimit = DeletionWeightLimit;486 type Schedule = Schedule;487 type CallStack = [pallet_contracts::Frame<Self>; 31];488}489*/490491parameter_types! {492 /// This value increases the priority of `Operational` transactions by adding493 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.494 pub const OperationalFeeMultiplier: u8 = 5;495}496497/// Linear implementor of `WeightToFeePolynomial`498pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);499500impl<T> WeightToFeePolynomial for LinearFee<T>501where502 T: BaseArithmetic + From<u32> + Copy + Unsigned,503{504 type Balance = T;505506 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {507 smallvec!(WeightToFeeCoefficient {508 // Targeting 0.1 Unique per NFT transfer509 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),510 coeff_frac: Perbill::zero(),511 negative: false,512 degree: 1,513 })514 }515}516517impl pallet_transaction_payment::Config for Runtime {518 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;519 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;520 type OperationalFeeMultiplier = OperationalFeeMultiplier;521 type WeightToFee = LinearFee<Balance>;522 type FeeMultiplierUpdate = ();523}524525parameter_types! {526 pub const ProposalBond: Permill = Permill::from_percent(5);527 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;528 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;529 pub const SpendPeriod: BlockNumber = 5 * MINUTES;530 pub const Burn: Permill = Permill::from_percent(0);531 pub const TipCountdown: BlockNumber = 1 * DAYS;532 pub const TipFindersFee: Percent = Percent::from_percent(20);533 pub const TipReportDepositBase: Balance = 1 * UNIQUE;534 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;535 pub const BountyDepositBase: Balance = 1 * UNIQUE;536 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;537 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");538 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;539 pub const MaximumReasonLength: u32 = 16384;540 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);541 pub const BountyValueMinimum: Balance = 5 * UNIQUE;542 pub const MaxApprovals: u32 = 100;543}544545impl pallet_treasury::Config for Runtime {546 type PalletId = TreasuryModuleId;547 type Currency = Balances;548 type ApproveOrigin = EnsureRoot<AccountId>;549 type RejectOrigin = EnsureRoot<AccountId>;550 type Event = Event;551 type OnSlash = ();552 type ProposalBond = ProposalBond;553 type ProposalBondMinimum = ProposalBondMinimum;554 type ProposalBondMaximum = ProposalBondMaximum;555 type SpendPeriod = SpendPeriod;556 type Burn = Burn;557 type BurnDestination = ();558 type SpendFunds = ();559 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;560 type MaxApprovals = MaxApprovals;561}562563impl pallet_sudo::Config for Runtime {564 type Event = Event;565 type Call = Call;566}567568pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);569570impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider571 for RelayChainBlockNumberProvider<T>572{573 type BlockNumber = BlockNumber;574575 fn current_block_number() -> Self::BlockNumber {576 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()577 .map(|d| d.relay_parent_number)578 .unwrap_or_default()579 }580}581582parameter_types! {583 pub const MinVestedTransfer: Balance = 10 * UNIQUE;584 pub const MaxVestingSchedules: u32 = 28;585}586587impl orml_vesting::Config for Runtime {588 type Event = Event;589 type Currency = pallet_balances::Pallet<Runtime>;590 type MinVestedTransfer = MinVestedTransfer;591 type VestedTransferOrigin = EnsureSigned<AccountId>;592 type WeightInfo = ();593 type MaxVestingSchedules = MaxVestingSchedules;594 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;595}596597parameter_types! {598 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;599 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;600}601602impl cumulus_pallet_parachain_system::Config for Runtime {603 type Event = Event;604 type SelfParaId = parachain_info::Pallet<Self>;605 type OnSystemEvent = ();606 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<607 // MaxDownwardMessageWeight,608 // XcmExecutor<XcmConfig>,609 // Call,610 // >;611 type OutboundXcmpMessageSource = XcmpQueue;612 type DmpMessageHandler = DmpQueue;613 type ReservedDmpWeight = ReservedDmpWeight;614 type ReservedXcmpWeight = ReservedXcmpWeight;615 type XcmpMessageHandler = XcmpQueue;616}617618impl parachain_info::Config for Runtime {}619620impl cumulus_pallet_aura_ext::Config for Runtime {}621622parameter_types! {623 pub const RelayLocation: MultiLocation = MultiLocation::parent();624 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;625 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();626 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();627}628629/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used630/// when determining ownership of accounts for asset transacting and when attempting to use XCM631/// `Transact` in order to determine the dispatch Origin.632pub type LocationToAccountId = (633 // The parent (Relay-chain) origin converts to the default `AccountId`.634 ParentIsPreset<AccountId>,635 // Sibling parachain origins convert to AccountId via the `ParaId::into`.636 SiblingParachainConvertsVia<Sibling, AccountId>,637 // Straight up local `AccountId32` origins just alias directly to `AccountId`.638 AccountId32Aliases<RelayNetwork, AccountId>,639);640641pub struct OnlySelfCurrency;642impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {643 fn matches_fungible(a: &MultiAsset) -> Option<B> {644 match (&a.id, &a.fun) {645 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),646 _ => None,647 }648 }649}650651/// Means for transacting assets on this chain.652pub type LocalAssetTransactor = CurrencyAdapter<653 // Use this currency:654 Balances,655 // Use this currency when it is a fungible asset matching the given location or name:656 OnlySelfCurrency,657 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:658 LocationToAccountId,659 // Our chain's account ID type (we can't get away without mentioning it explicitly):660 AccountId,661 // We don't track any teleports.662 (),663>;664665/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,666/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can667/// biases the kind of local `Origin` it will become.668pub type XcmOriginToTransactDispatchOrigin = (669 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location670 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for671 // foreign chains who want to have a local sovereign account on this chain which they control.672 SovereignSignedViaLocation<LocationToAccountId, Origin>,673 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when674 // recognised.675 RelayChainAsNative<RelayOrigin, Origin>,676 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when677 // recognised.678 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,679 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a680 // transaction from the Root origin.681 ParentAsSuperuser<Origin>,682 // Native signed account converter; this just converts an `AccountId32` origin into a normal683 // `Origin::Signed` origin of the same 32-byte value.684 SignedAccountId32AsNative<RelayNetwork, Origin>,685 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.686 XcmPassthrough<Origin>,687);688689parameter_types! {690 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.691 pub UnitWeightCost: Weight = 1_000_000;692 // 1200 UNIQUEs buy 1 second of weight.693 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);694 pub const MaxInstructions: u32 = 100;695 pub const MaxAuthorities: u32 = 100_000;696}697698match_types! {699 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {700 MultiLocation { parents: 1, interior: Here } |701 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }702 };703}704705pub type Barrier = (706 TakeWeightCredit,707 AllowTopLevelPaidExecutionFrom<Everything>,708 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,709 // ^^^ Parent & its unit plurality gets free execution710);711712pub struct UsingOnlySelfCurrencyComponents<713 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,714 AssetId: Get<MultiLocation>,715 AccountId,716 Currency: CurrencyT<AccountId>,717 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,718>(719 Weight,720 Currency::Balance,721 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,722);723impl<724 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,725 AssetId: Get<MultiLocation>,726 AccountId,727 Currency: CurrencyT<AccountId>,728 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,729 > WeightTrader730 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>731{732 fn new() -> Self {733 Self(0, Zero::zero(), PhantomData)734 }735736 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {737 let amount = WeightToFee::calc(&weight);738 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;739740 // location to this parachain through relay chain741 let option1: xcm::v1::AssetId = Concrete(MultiLocation {742 parents: 1,743 interior: X1(Parachain(ParachainInfo::parachain_id().into())),744 });745 // direct location746 let option2: xcm::v1::AssetId = Concrete(MultiLocation {747 parents: 0,748 interior: Here,749 });750751 let required = if payment.fungible.contains_key(&option1) {752 (option1, u128_amount).into()753 } else if payment.fungible.contains_key(&option2) {754 (option2, u128_amount).into()755 } else {756 (Concrete(MultiLocation::default()), u128_amount).into()757 };758759 let unused = payment760 .checked_sub(required)761 .map_err(|_| XcmError::TooExpensive)?;762 self.0 = self.0.saturating_add(weight);763 self.1 = self.1.saturating_add(amount);764 Ok(unused)765 }766767 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {768 let weight = weight.min(self.0);769 let amount = WeightToFee::calc(&weight);770 self.0 -= weight;771 self.1 = self.1.saturating_sub(amount);772 let amount: u128 = amount.saturated_into();773 if amount > 0 {774 Some((AssetId::get(), amount).into())775 } else {776 None777 }778 }779}780impl<781 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,782 AssetId: Get<MultiLocation>,783 AccountId,784 Currency: CurrencyT<AccountId>,785 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,786 > Drop787 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>788{789 fn drop(&mut self) {790 OnUnbalanced::on_unbalanced(Currency::issue(self.1));791 }792}793794pub struct XcmConfig;795impl Config for XcmConfig {796 type Call = Call;797 type XcmSender = XcmRouter;798 // How to withdraw and deposit an asset.799 type AssetTransactor = LocalAssetTransactor;800 type OriginConverter = XcmOriginToTransactDispatchOrigin;801 type IsReserve = NativeAsset;802 type IsTeleporter = (); // Teleportation is disabled803 type LocationInverter = LocationInverter<Ancestry>;804 type Barrier = Barrier;805 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;806 type Trader = UsingOnlySelfCurrencyComponents<807 IdentityFee<Balance>,808 RelayLocation,809 AccountId,810 Balances,811 (),812 >;813 type ResponseHandler = (); // Don't handle responses for now.814 type SubscriptionService = PolkadotXcm;815816 type AssetTrap = PolkadotXcm;817 type AssetClaims = PolkadotXcm;818}819820// parameter_types! {821// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;822// }823824/// No local origins on this chain are allowed to dispatch XCM sends/executions.825pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);826827/// The means for routing XCM messages which are not for local execution into the right message828/// queues.829pub type XcmRouter = (830 // Two routers - use UMP to communicate with the relay chain:831 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,832 // ..and XCMP to communicate with the sibling chains.833 XcmpQueue,834);835836impl pallet_evm_coder_substrate::Config for Runtime {}837838impl pallet_xcm::Config for Runtime {839 type Event = Event;840 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;841 type XcmRouter = XcmRouter;842 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;843 type XcmExecuteFilter = Everything;844 type XcmExecutor = XcmExecutor<XcmConfig>;845 type XcmTeleportFilter = Everything;846 type XcmReserveTransferFilter = Everything;847 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;848 type LocationInverter = LocationInverter<Ancestry>;849 type Origin = Origin;850 type Call = Call;851 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;852 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;853}854855impl cumulus_pallet_xcm::Config for Runtime {856 type Event = Event;857 type XcmExecutor = XcmExecutor<XcmConfig>;858}859860impl cumulus_pallet_xcmp_queue::Config for Runtime {861 type WeightInfo = ();862 type Event = Event;863 type XcmExecutor = XcmExecutor<XcmConfig>;864 type ChannelInfo = ParachainSystem;865 type VersionWrapper = ();866 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;867 type ControllerOrigin = EnsureRoot<AccountId>;868 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;869}870871impl cumulus_pallet_dmp_queue::Config for Runtime {872 type Event = Event;873 type XcmExecutor = XcmExecutor<XcmConfig>;874 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;875}876877impl pallet_aura::Config for Runtime {878 type AuthorityId = AuraId;879 type DisabledValidators = ();880 type MaxAuthorities = MaxAuthorities;881}882883parameter_types! {884 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();885 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;886}887888impl pallet_common::Config for Runtime {889 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;890 type Event = Event;891 type Currency = Balances;892 type CollectionCreationPrice = CollectionCreationPrice;893 type TreasuryAccountId = TreasuryAccountId;894 type CollectionDispatch = CollectionDispatchT<Self>;895896 type EvmTokenAddressMapping = EvmTokenAddressMapping;897 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;898 type ContractAddress = EvmCollectionHelpersAddress;899}900901impl pallet_structure::Config for Runtime {902 type Event = Event;903 type Call = Call;904 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;905}906907impl pallet_fungible::Config for Runtime {908 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;909}910impl pallet_refungible::Config for Runtime {911 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;912}913impl pallet_nonfungible::Config for Runtime {914 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;915}916917/*918TODO free RMRK!919impl pallet_proxy_rmrk_core::Config for Runtime {920 type Event = Event;921}922923impl pallet_proxy_rmrk_equip::Config for Runtime {924 type Event = Event;925}*/926927impl pallet_unique::Config for Runtime {928 type Event = Event;929 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;930 type CommonWeightInfo = CommonWeights<Self>;931}932933parameter_types! {934 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied935}936937/// Used for the pallet inflation938impl pallet_inflation::Config for Runtime {939 type Currency = Balances;940 type TreasuryAccountId = TreasuryAccountId;941 type InflationBlockInterval = InflationBlockInterval;942 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;943}944945parameter_types! {946 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *947 RuntimeBlockWeights::get().max_block;948 pub const MaxScheduledPerBlock: u32 = 50;949}950951type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;952use frame_support::traits::NamedReservableCurrency;953954fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {955 (956 frame_system::CheckSpecVersion::<Runtime>::new(),957 frame_system::CheckGenesis::<Runtime>::new(),958 frame_system::CheckEra::<Runtime>::from(Era::Immortal),959 frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(960 from,961 )),962 frame_system::CheckWeight::<Runtime>::new(),963 // sponsoring transaction logic964 // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),965 )966}967968pub struct SchedulerPaymentExecutor;969impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>970 DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor971where972 <T as frame_system::Config>::Call: Member973 + Dispatchable<Origin = Origin, Info = DispatchInfo>974 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>975 + GetDispatchInfo976 + From<frame_system::Call<Runtime>>,977 SelfContainedSignedInfo: Send + Sync + 'static,978 Call: From<<T as frame_system::Config>::Call>979 + From<<T as pallet_unq_scheduler::Config>::Call>980 + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,981 sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,982{983 fn dispatch_call(984 signer: <T as frame_system::Config>::AccountId,985 call: <T as pallet_unq_scheduler::Config>::Call,986 ) -> Result<987 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,988 TransactionValidityError,989 > {990 let dispatch_info = call.get_dispatch_info();991 let extrinsic = fp_self_contained::CheckedExtrinsic::<992 AccountId,993 Call,994 SignedExtraScheduler,995 SelfContainedSignedInfo,996 > {997 signed:998 CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(999 signer.clone().into(),1000 get_signed_extras(signer.into()),1001 ),1002 function: call.into(),1003 };10041005 extrinsic.apply::<Runtime>(&dispatch_info, 0)1006 }10071008 fn reserve_balance(1009 id: [u8; 16],1010 sponsor: <T as frame_system::Config>::AccountId,1011 call: <T as pallet_unq_scheduler::Config>::Call,1012 count: u32,1013 ) -> Result<(), DispatchError> {1014 let dispatch_info = call.get_dispatch_info();1015 let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)1016 .saturating_mul(count.into());10171018 <Balances as NamedReservableCurrency<AccountId>>::reserve_named(1019 &id,1020 &(sponsor.into()),1021 weight,1022 )1023 }10241025 fn pay_for_call(1026 id: [u8; 16],1027 sponsor: <T as frame_system::Config>::AccountId,1028 call: <T as pallet_unq_scheduler::Config>::Call,1029 ) -> Result<u128, DispatchError> {1030 let dispatch_info = call.get_dispatch_info();1031 let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);1032 Ok(1033 <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(1034 &id,1035 &(sponsor.into()),1036 weight,1037 ),1038 )1039 }10401041 fn cancel_reserve(1042 id: [u8; 16],1043 sponsor: <T as frame_system::Config>::AccountId,1044 ) -> Result<u128, DispatchError> {1045 Ok(1046 <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(1047 &id,1048 &(sponsor.into()),1049 u128::MAX,1050 ),1051 )1052 }1053}10541055parameter_types! {1056 pub const NoPreimagePostponement: Option<u32> = Some(10);1057 pub const Preimage: Option<u32> = Some(10);1058}10591060/// Used the compare the privilege of an origin inside the scheduler.1061pub struct OriginPrivilegeCmp;10621063impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {1064 fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {1065 Some(Ordering::Equal)1066 }1067}10681069impl pallet_unq_scheduler::Config for Runtime {1070 type Event = Event;1071 type Origin = Origin;1072 type Currency = Balances;1073 type PalletsOrigin = OriginCaller;1074 type Call = Call;1075 type MaximumWeight = MaximumSchedulerWeight;1076 type ScheduleOrigin = EnsureSigned<AccountId>;1077 type MaxScheduledPerBlock = MaxScheduledPerBlock;1078 type WeightInfo = ();1079 type CallExecutor = SchedulerPaymentExecutor;1080 type OriginPrivilegeCmp = OriginPrivilegeCmp;1081 type PreimageProvider = ();1082 type NoPreimagePostponement = NoPreimagePostponement;1083}10841085type EvmSponsorshipHandler = (1086 UniqueEthSponsorshipHandler<Runtime>,1087 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,1088);10891090type SponsorshipHandler = (1091 UniqueSponsorshipHandler<Runtime>,1092 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,1093 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,1094);10951096impl pallet_evm_transaction_payment::Config for Runtime {1097 type EvmSponsorshipHandler = EvmSponsorshipHandler;1098 type Currency = Balances;1099}11001101impl pallet_charge_transaction::Config for Runtime {1102 type SponsorshipHandler = SponsorshipHandler;1103}11041105// impl pallet_contract_helpers::Config for Runtime {1106// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;1107// }11081109parameter_types! {1110 // 0x842899ECF380553E8a4de75bF534cdf6fBF640491111 pub const HelpersContractAddress: H160 = H160([1112 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,1113 ]);11141115 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f1116 pub const EvmCollectionHelpersAddress: H160 = H160([1117 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,1118 ]);1119}11201121impl pallet_evm_contract_helpers::Config for Runtime {1122 type ContractAddress = HelpersContractAddress;1123 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;1124}11251126construct_runtime!(1127 pub enum Runtime where1128 Block = Block,1129 NodeBlock = opaque::Block,1130 UncheckedExtrinsic = UncheckedExtrinsic1131 {1132 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1133 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,11341135 Aura: pallet_aura::{Pallet, Config<T>} = 22,1136 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,11371138 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1139 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1140 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1141 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1142 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1143 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1144 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1145 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1146 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1147 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,11481149 // XCM helpers.1150 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1151 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1152 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1153 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,11541155 // Unique Pallets1156 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1157 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1158 Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1159 // free = 631160 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1161 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1162 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1163 Fungible: pallet_fungible::{Pallet, Storage} = 67,1164 Refungible: pallet_refungible::{Pallet, Storage} = 68,1165 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1166 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1167 /* TODO free RMRK!1168 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1169 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,1170 */11711172 // Frontier1173 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1174 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,11751176 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1177 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1178 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1179 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1180 }1181);11821183pub struct TransactionConverter;11841185impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1186 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1187 UncheckedExtrinsic::new_unsigned(1188 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1189 )1190 }1191}11921193impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1194 fn convert_transaction(1195 &self,1196 transaction: pallet_ethereum::Transaction,1197 ) -> opaque::UncheckedExtrinsic {1198 let extrinsic = UncheckedExtrinsic::new_unsigned(1199 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1200 );1201 let encoded = extrinsic.encode();1202 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1203 .expect("Encoded extrinsic is always valid")1204 }1205}12061207/// The address format for describing accounts.1208pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1209/// Block header type as expected by this runtime.1210pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1211/// Block type as expected by this runtime.1212pub type Block = generic::Block<Header, UncheckedExtrinsic>;1213/// A Block signed with a Justification1214pub type SignedBlock = generic::SignedBlock<Block>;1215/// BlockId type as expected by this runtime.1216pub type BlockId = generic::BlockId<Block>;1217/// The SignedExtension to the basic transaction logic.1218pub type SignedExtra = (1219 frame_system::CheckSpecVersion<Runtime>,1220 // system::CheckTxVersion<Runtime>,1221 frame_system::CheckGenesis<Runtime>,1222 frame_system::CheckEra<Runtime>,1223 frame_system::CheckNonce<Runtime>,1224 frame_system::CheckWeight<Runtime>,1225 ChargeTransactionPayment,1226 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1227 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1228);1229pub type SignedExtraScheduler = (1230 frame_system::CheckSpecVersion<Runtime>,1231 frame_system::CheckGenesis<Runtime>,1232 frame_system::CheckEra<Runtime>,1233 frame_system::CheckNonce<Runtime>,1234 frame_system::CheckWeight<Runtime>,1235);1236/// Unchecked extrinsic type as expected by this runtime.1237pub type UncheckedExtrinsic =1238 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1239/// Extrinsic type that has already been checked.1240pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1241/// Executive: handles dispatch to the various modules.1242pub type Executive = frame_executive::Executive<1243 Runtime,1244 Block,1245 frame_system::ChainContext<Runtime>,1246 Runtime,1247 AllPalletsReversedWithSystemFirst,1248>;12491250impl_opaque_keys! {1251 pub struct SessionKeys {1252 pub aura: Aura,1253 }1254}12551256impl fp_self_contained::SelfContainedCall for Call {1257 type SignedInfo = H160;12581259 fn is_self_contained(&self) -> bool {1260 match self {1261 Call::Ethereum(call) => call.is_self_contained(),1262 _ => false,1263 }1264 }12651266 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1267 match self {1268 Call::Ethereum(call) => call.check_self_contained(),1269 _ => None,1270 }1271 }12721273 fn validate_self_contained(1274 &self,1275 info: &Self::SignedInfo,1276 dispatch_info: &DispatchInfoOf<Call>,1277 len: usize,1278 ) -> Option<TransactionValidity> {1279 match self {1280 Call::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),1281 _ => None,1282 }1283 }12841285 fn pre_dispatch_self_contained(1286 &self,1287 info: &Self::SignedInfo,1288 ) -> Option<Result<(), TransactionValidityError>> {1289 match self {1290 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1291 _ => None,1292 }1293 }12941295 fn apply_self_contained(1296 self,1297 info: Self::SignedInfo,1298 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1299 match self {1300 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1301 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1302 )),1303 _ => None,1304 }1305 }1306}13071308macro_rules! dispatch_unique_runtime {1309 ($collection:ident.$method:ident($($name:ident),*)) => {{1310 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1311 let dispatch = collection.as_dyn();13121313 Ok::<_, DispatchError>(dispatch.$method($($name),*))1314 }};1315}13161317impl_common_runtime_apis!();13181319struct CheckInherents;13201321impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1322 fn check_inherents(1323 block: &Block,1324 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1325 ) -> sp_inherents::CheckInherentsResult {1326 let relay_chain_slot = relay_state_proof1327 .read_slot()1328 .expect("Could not read the relay chain slot from the proof");13291330 let inherent_data =1331 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1332 relay_chain_slot,1333 sp_std::time::Duration::from_secs(6),1334 )1335 .create_inherent_data()1336 .expect("Could not create the timestamp inherent data");13371338 inherent_data.check_extrinsics(block)1339 }1340}13411342cumulus_pallet_parachain_system::register_validate_block!(1343 Runtime = Runtime,1344 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1345 CheckInherents = CheckInherents,1346);runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -33,7 +33,7 @@
use sp_runtime::{
Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
- traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
+ traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero, Member},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, RuntimeAppPublic,
};
@@ -58,7 +58,7 @@
traits::{
tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
- OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+ OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -81,18 +81,28 @@
use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};
use fp_rpc::TransactionStatus;
use sp_runtime::{
- traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
+ traits::{
+ Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+ CheckedConversion,
+ },
+ generic::Era,
transaction_validity::TransactionValidityError,
- SaturatedConversion,
+ SaturatedConversion, DispatchErrorWithPostInfo,
};
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+
// pub use pallet_timestamp::Call as TimestampCall;
pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;
// Polkadot imports
use pallet_xcm::XcmPassthrough;
use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+ CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+ CollectionStats, RpcCollection,
+ mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
use xcm_builder::{
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -102,7 +112,8 @@
ParentIsPreset,
};
use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
use xcm::latest::{
// Xcm,
@@ -112,8 +123,6 @@
Error as XcmError,
};
use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
-use sp_runtime::traits::CheckedConversion;
use unique_runtime_common::{
impl_common_runtime_apis,
@@ -390,7 +399,7 @@
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -913,11 +922,11 @@
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
-// parameter_types! {
-// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// RuntimeBlockWeights::get().max_block;
-// pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+ RuntimeBlockWeights::get().max_block;
+ pub const MaxScheduledPerBlock: u32 = 50;
+}
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
@@ -929,17 +938,34 @@
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-// impl pallet_unq_scheduler::Config for Runtime {
-// type Event = Event;
-// type Origin = Origin;
-// type PalletsOrigin = OriginCaller;
-// type Call = Call;
-// type MaximumWeight = MaximumSchedulerWeight;
-// type ScheduleOrigin = EnsureSigned<AccountId>;
-// type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// type SponsorshipHandler = SponsorshipHandler;
-// type WeightInfo = ();
-// }
+parameter_types! {
+ pub const NoPreimagePostponement: Option<u32> = Some(10);
+ pub const Preimage: Option<u32> = Some(10);
+}
+
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+ fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+ Some(Ordering::Equal)
+ }
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+ type Event = Event;
+ type Origin = Origin;
+ type Currency = Balances;
+ type PalletsOrigin = OriginCaller;
+ type Call = Call;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSigned<AccountId>;
+ type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type WeightInfo = ();
+ type CallExecutor = SchedulerPaymentExecutor;
+ type OriginPrivilegeCmp = OriginPrivilegeCmp;
+ type PreimageProvider = ();
+ type NoPreimagePostponement = NoPreimagePostponement;
+}
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -954,6 +980,110 @@
// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
// }
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+ (
+ frame_system::CheckSpecVersion::<Runtime>::new(),
+ frame_system::CheckGenesis::<Runtime>::new(),
+ frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+ frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+ from,
+ )),
+ frame_system::CheckWeight::<Runtime>::new(),
+ // sponsoring transaction logic
+ // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+ )
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+ DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+where
+ <T as frame_system::Config>::Call: Member
+ + Dispatchable<Origin = Origin, Info = DispatchInfo>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+ + GetDispatchInfo
+ + From<frame_system::Call<Runtime>>,
+ SelfContainedSignedInfo: Send + Sync + 'static,
+ Call: From<<T as frame_system::Config>::Call>
+ + From<<T as pallet_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ fn dispatch_call(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let dispatch_info = call.get_dispatch_info();
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtraScheduler,
+ SelfContainedSignedInfo,
+ > {
+ signed:
+ CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
+ function: call.into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)
+ }
+
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+ .saturating_mul(count.into());
+
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ )
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<u128, DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ ),
+ )
+ }
+
+ fn cancel_reserve(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ ) -> Result<u128, DispatchError> {
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ u128::MAX,
+ ),
+ )
+ }
+}
+
parameter_types! {
// 0x842899ECF380553E8a4de75bF534cdf6fBF64049
pub const HelpersContractAddress: H160 = H160([
@@ -1003,7 +1133,7 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1073,6 +1203,15 @@
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
+
+pub type SignedExtraScheduler = (
+ frame_system::CheckSpecVersion<Runtime>,
+ frame_system::CheckGenesis<Runtime>,
+ frame_system::CheckEra<Runtime>,
+ frame_system::CheckNonce<Runtime>,
+ frame_system::CheckWeight<Runtime>,
+ // pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -33,11 +33,20 @@
use sp_runtime::{
Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,
- traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},
- transaction_validity::{TransactionSource, TransactionValidity},
- ApplyExtrinsicResult, RuntimeAppPublic,
+ generic::Era,
+ traits::{
+ Applyable, BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating,
+ CheckedConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion,
+ Zero, Member,
+ },
+ transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError},
+ ApplyExtrinsicResult, RuntimeAppPublic, SaturatedConversion, DispatchErrorWithPostInfo,
};
+use fp_self_contained::{SelfContainedCall, CheckedSignature};
+use sp_std::{cmp::Ordering, marker::PhantomData};
+use pallet_unq_scheduler::DispatchCall;
+
use sp_std::prelude::*;
#[cfg(feature = "std")]
@@ -59,7 +68,7 @@
traits::{
tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,
Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,
- OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,
+ OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance, PrivilegeCmp,
},
weights::{
constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
@@ -86,18 +95,17 @@
use smallvec::smallvec;
use codec::{Encode, Decode};
use fp_rpc::TransactionStatus;
-use sp_runtime::{
- traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
- transaction_validity::TransactionValidityError,
- SaturatedConversion,
-};
// pub use pallet_timestamp::Call as TimestampCall;
// Polkadot imports
use pallet_xcm::XcmPassthrough;
use polkadot_parachain::primitives::Sibling;
-use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};
+use up_data_structs::{
+ CollectionId, TokenId, TokenData, Property, PropertyKeyPermission, CollectionLimits,
+ CollectionStats, RpcCollection,
+ mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping}
+};
use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};
use xcm_builder::{
AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,
@@ -107,7 +115,6 @@
ParentIsPreset,
};
use xcm_executor::{Config, XcmExecutor, Assets};
-use sp_std::{marker::PhantomData};
use xcm::latest::{
// Xcm,
@@ -117,7 +124,6 @@
Error as XcmError,
};
use xcm_executor::traits::{MatchesFungible, WeightTrader};
-//use xcm_executor::traits::MatchesFungible;
use sp_runtime::traits::CheckedConversion;
use unique_runtime_common::{
@@ -395,7 +401,7 @@
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -918,12 +924,145 @@
type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;
}
-// parameter_types! {
-// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
-// RuntimeBlockWeights::get().max_block;
-// pub const MaxScheduledPerBlock: u32 = 50;
-// }
+parameter_types! {
+ pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *
+ RuntimeBlockWeights::get().max_block;
+ pub const MaxScheduledPerBlock: u32 = 50;
+}
+
+parameter_types! {
+ pub const NoPreimagePostponement: Option<u32> = Some(10);
+ pub const Preimage: Option<u32> = Some(10);
+}
+/// Used the compare the privilege of an origin inside the scheduler.
+pub struct OriginPrivilegeCmp;
+impl PrivilegeCmp<OriginCaller> for OriginPrivilegeCmp {
+ fn cmp_privilege(_left: &OriginCaller, _right: &OriginCaller) -> Option<Ordering> {
+ Some(Ordering::Equal)
+ }
+}
+
+impl pallet_unq_scheduler::Config for Runtime {
+ type Event = Event;
+ type Origin = Origin;
+ type Currency = Balances;
+ type PalletsOrigin = OriginCaller;
+ type Call = Call;
+ type MaximumWeight = MaximumSchedulerWeight;
+ type ScheduleOrigin = EnsureSigned<AccountId>;
+ type MaxScheduledPerBlock = MaxScheduledPerBlock;
+ type WeightInfo = ();
+ type CallExecutor = SchedulerPaymentExecutor;
+ type OriginPrivilegeCmp = OriginPrivilegeCmp;
+ type PreimageProvider = ();
+ type NoPreimagePostponement = NoPreimagePostponement;
+}
+
+type ChargeTransactionPayment = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+use frame_support::traits::NamedReservableCurrency;
+
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtraScheduler {
+ (
+ frame_system::CheckSpecVersion::<Runtime>::new(),
+ frame_system::CheckGenesis::<Runtime>::new(),
+ frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+ frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+ from,
+ )),
+ frame_system::CheckWeight::<Runtime>::new(),
+ // sponsoring transaction logic
+ // pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+ )
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+ DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
+where
+ <T as frame_system::Config>::Call: Member
+ + Dispatchable<Origin = Origin, Info = DispatchInfo>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+ + GetDispatchInfo
+ + From<frame_system::Call<Runtime>>,
+ SelfContainedSignedInfo: Send + Sync + 'static,
+ Call: From<<T as frame_system::Config>::Call>
+ + From<<T as pallet_unq_scheduler::Config>::Call>
+ + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+ sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
+{
+ fn dispatch_call(
+ signer: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let dispatch_info = call.get_dispatch_info();
+ let extrinsic = fp_self_contained::CheckedExtrinsic::<
+ AccountId,
+ Call,
+ SignedExtraScheduler,
+ SelfContainedSignedInfo,
+ > {
+ signed:
+ CheckedSignature::<AccountId, SignedExtraScheduler, SelfContainedSignedInfo>::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
+ function: call.into(),
+ };
+
+ extrinsic.apply::<Runtime>(&dispatch_info, 0)
+ }
+
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0)
+ .saturating_mul(count.into());
+
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ )
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ ) -> Result<u128, DispatchError> {
+ let dispatch_info = call.get_dispatch_info();
+ let weight: Balance = ChargeTransactionPayment::traditional_fee(0, &dispatch_info, 0);
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ weight.into(),
+ ),
+ )
+ }
+
+ fn cancel_reserve(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ ) -> Result<u128, DispatchError> {
+ Ok(
+ <Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ u128::MAX,
+ ),
+ )
+ }
+}
+
type EvmSponsorshipHandler = (
UniqueEthSponsorshipHandler<Runtime>,
pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,
@@ -933,18 +1072,6 @@
//pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,
pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,
);
-
-// impl pallet_unq_scheduler::Config for Runtime {
-// type Event = Event;
-// type Origin = Origin;
-// type PalletsOrigin = OriginCaller;
-// type Call = Call;
-// type MaximumWeight = MaximumSchedulerWeight;
-// type ScheduleOrigin = EnsureSigned<AccountId>;
-// type MaxScheduledPerBlock = MaxScheduledPerBlock;
-// type SponsorshipHandler = SponsorshipHandler;
-// type WeightInfo = ();
-// }
impl pallet_evm_transaction_payment::Config for Runtime {
type EvmSponsorshipHandler = EvmSponsorshipHandler;
@@ -1008,7 +1135,7 @@
// Unique Pallets
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
// free = 63
Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
// ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
@@ -1078,6 +1205,14 @@
//pallet_contract_helpers::ContractHelpersExtension<Runtime>,
pallet_ethereum::FakeTransactionFinalizer<Runtime>,
);
+pub type SignedExtraScheduler = (
+ frame_system::CheckSpecVersion<Runtime>,
+ frame_system::CheckGenesis<Runtime>,
+ frame_system::CheckEra<Runtime>,
+ frame_system::CheckNonce<Runtime>,
+ frame_system::CheckWeight<Runtime>,
+ // pallet_charge_transaction::ChargeTransactionPayment<Runtime>,
+);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;
tests/package.jsondiffbeforeafterboth--- a/tests/package.json
+++ b/tests/package.json
@@ -68,6 +68,8 @@
"testOverflow": "mocha --timeout 9999999 -r ts-node/register ./**/overflow.test.ts",
"testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
"testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
+ "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
+ "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
"testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
"testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
"testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
tests/src/eth/scheduling.test.tsdiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/scheduling.test.ts
@@ -0,0 +1,55 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
+import {scheduleExpectSuccess, waitNewBlocks} from '../util/helpers';
+import privateKey from '../substrate/privateKey';
+
+describe('Scheduing EVM smart contracts', () => {
+ itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3}) => {
+ const deployer = await createEthAccountWithBalance(api, web3);
+ const flipper = await deployFlipper(web3, deployer);
+ const initialValue = await flipper.methods.getValue().call();
+ const alice = privateKey('//Alice');
+ await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+ {
+ const tx = api.tx.evm.call(
+ subToEth(alice.address),
+ flipper.options.address,
+ flipper.methods.flip().encodeABI(),
+ '0',
+ GAS_ARGS.gas,
+ await web3.eth.getGasPrice(),
+ null,
+ null,
+ [],
+ );
+ const waitForBlocks = 4;
+ const periodBlocks = 2;
+
+ await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+
+ await waitNewBlocks(waitForBlocks - 1);
+ expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+
+ await waitNewBlocks(periodBlocks);
+ expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+ }
+ });
+});
\ No newline at end of file
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -50,7 +50,7 @@
'unique',
'nonfungible',
'refungible',
- //'scheduler',
+ 'scheduler',
'charging',
];
tests/src/scheduler.test.tsdiffbeforeafterboth--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -14,32 +14,197 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-import chai from 'chai';
+import chai, {expect} from 'chai';
import chaiAsPromised from 'chai-as-promised';
import privateKey from './substrate/privateKey';
-import usingApi from './substrate/substrate-api';
import {
+ default as usingApi,
+ submitTransactionAsync,
+} from './substrate/substrate-api';
+import {
createItemExpectSuccess,
createCollectionExpectSuccess,
scheduleTransferExpectSuccess,
+ scheduleTransferAndWaitExpectSuccess,
setCollectionSponsorExpectSuccess,
confirmSponsorshipExpectSuccess,
+ findUnusedAddress,
+ UNIQUE,
+ enablePublicMintingExpectSuccess,
+ addToAllowListExpectSuccess,
+ waitNewBlocks,
+ normalizeAccountId,
+ getTokenOwner,
+ getGenericResult,
+ scheduleTransferFundsPeriodicExpectSuccess,
+ getFreeBalance,
+ confirmSponsorshipByKeyExpectSuccess,
+ scheduleExpectFailure,
} from './util/helpers';
+import {IKeyringPair} from '@polkadot/types/types';
chai.use(chaiAsPromised);
-describe.skip('Integration Test scheduler base transaction', () => {
- it('User can transfer owned token with delay (scheduler)', async () => {
+describe.skip('Scheduling token and balance transfers', () => {
+ let alice: IKeyringPair;
+ let bob: IKeyringPair;
+ let scheduledIdBase: string;
+ let scheduledIdSlider: number;
+
+ before(async() => {
await usingApi(async () => {
- const alice = privateKey('//Alice');
- const bob = privateKey('//Bob');
- // nft
+ alice = privateKey('//Alice');
+ bob = privateKey('//Bob');
+ });
+
+ scheduledIdBase = '0x' + '0'.repeat(31);
+ scheduledIdSlider = 0;
+ });
+
+ // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+ function makeScheduledId(): string {
+ return scheduledIdBase + ((scheduledIdSlider++) % 10);
+ }
+
+ it('Can schedule a transfer of an owned token with delay', async () => {
+ await usingApi(async () => {
const nftCollectionId = await createCollectionExpectSuccess();
const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
await confirmSponsorshipExpectSuccess(nftCollectionId);
- await scheduleTransferExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+ await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
+ });
+ });
+
+ it('Can transfer funds periodically', async () => {
+ await usingApi(async () => {
+ const waitForBlocks = 4;
+ const period = 2;
+ await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+ const bobsBalanceBefore = await getFreeBalance(bob);
+
+ // discounting already waited-for operations
+ await waitNewBlocks(waitForBlocks - 2);
+ const bobsBalanceAfterFirst = await getFreeBalance(bob);
+ expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
+
+ await waitNewBlocks(period);
+ const bobsBalanceAfterSecond = await getFreeBalance(bob);
+ expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
+ });
+ });
+
+ it('Can sponsor scheduling a transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async () => {
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+ const waitForBlocks = 4;
+ // no need to wait to check, fees must be deducted on scheduling, immediately
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+ const bobBalanceAfter = await getFreeBalance(bob);
+ // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+ expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+ // wait for sequentiality matters
+ await waitNewBlocks(waitForBlocks - 1);
+ });
+ });
+
+ it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
+ await usingApi(async (api) => {
+ // Find an empty, unused account
+ const zeroBalance = await findUnusedAddress(api);
+
+ const collectionId = await createCollectionExpectSuccess();
+
+ // Add zeroBalance address to allow list
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ // Grace zeroBalance with money, enough to cover future transactions
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ // Mint a fresh NFT
+ const tokenId = await createItemExpectSuccess(zeroBalance, collectionId, 'NFT');
+
+ // Schedule transfer of the NFT a few blocks ahead
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
+
+ // Get rid of the account's funds before the scheduled transaction takes place
+ const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+ const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+ expect(getGenericResult(events).success).to.be.true;
+ /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;*/
+
+ // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(alice.address));
+ });
+ });
+
+ it('Sponsor going bankrupt does not impact a scheduled transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+ const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
+ await submitTransactionAsync(alice, balanceTx);
+
+ await setCollectionSponsorExpectSuccess(collectionId, zeroBalance.address);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, zeroBalance);
+
+ const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+
+ const waitForBlocks = 5;
+ await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
+
+ const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
+ const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
+ const events = await submitTransactionAsync(alice, sudoTx);
+ expect(getGenericResult(events).success).to.be.true;
+
+ // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
+ await waitNewBlocks(waitForBlocks - 3);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
+ });
+ });
+
+ it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
+ const collectionId = await createCollectionExpectSuccess();
+ await setCollectionSponsorExpectSuccess(collectionId, bob.address);
+ await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
+
+ await usingApi(async (api) => {
+ const zeroBalance = await findUnusedAddress(api);
+
+ await enablePublicMintingExpectSuccess(alice, collectionId);
+ await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
+
+ const bobBalanceBefore = await getFreeBalance(bob);
+
+ const createData = {nft: {const_data: [], variable_data: []}};
+ const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
+
+ /*const badTransaction = async function () {
+ await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
+ };
+ await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
+
+ await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
+
+ expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
});
});
});
tests/src/util/helpers.tsdiffbeforeafterboth--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -630,10 +630,16 @@
}
export async function confirmSponsorshipExpectSuccess(collectionId: number, senderSeed = '//Alice') {
+ await usingApi(async () => {
+ const sender = privateKey(senderSeed);
+ await confirmSponsorshipByKeyExpectSuccess(collectionId, sender);
+ });
+}
+
+export async function confirmSponsorshipByKeyExpectSuccess(collectionId: number, sender: IKeyringPair) {
await usingApi(async (api) => {
// Run the transaction
- const sender = privateKey(senderSeed);
const tx = api.tx.unique.confirmSponsorship(collectionId);
const events = await submitTransactionAsync(sender, tx);
const result = getGenericResult(events);
@@ -899,7 +905,7 @@
}
/* eslint no-async-promise-executor: "off" */
-async function getBlockNumber(api: ApiPromise): Promise<number> {
+export async function getBlockNumber(api: ApiPromise): Promise<number> {
return new Promise<number>(async (resolve) => {
const unsubscribe = await api.rpc.chain.subscribeNewHeads((head) => {
unsubscribe();
@@ -935,29 +941,76 @@
}
export async function
-scheduleTransferExpectSuccess(
- collectionId: number,
- tokenId: number,
+scheduleExpectSuccess(
+ operationTx: any,
sender: IKeyringPair,
- recipient: IKeyringPair,
- value: number | bigint = 1,
blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
) {
await usingApi(async (api: ApiPromise) => {
const blockNumber: number | undefined = await getBlockNumber(api);
const expectedBlockNumber = blockNumber + blockSchedule;
expect(blockNumber).to.be.greaterThan(0);
- const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
- const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions > 1 ? [period, repetitions] : null,
+ 0,
+ {value: operationTx as any},
+ );
+
+ const events = await submitTransactionAsync(sender, scheduleTx);
+ expect(getGenericResult(events).success).to.be.true;
+ });
+}
+
+export async function
+scheduleExpectFailure(
+ operationTx: any,
+ sender: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period = 1,
+ repetitions = 1,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const blockNumber: number | undefined = await getBlockNumber(api);
+ const expectedBlockNumber = blockNumber + blockSchedule;
+
+ expect(blockNumber).to.be.greaterThan(0);
+ const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+ scheduledId,
+ expectedBlockNumber,
+ repetitions <= 1 ? null : [period, repetitions],
+ 0,
+ {value: operationTx as any},
+ );
+
+ //const events =
+ await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
+ //expect(getGenericResult(events).success).to.be.false;
+ });
+}
- await submitTransactionAsync(sender, scheduleTx);
+export async function
+scheduleTransferAndWaitExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
- expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
-
- // sleep for 4 blocks
+ // sleep for n + 1 blocks
await waitNewBlocks(blockSchedule + 1);
const recipientBalanceAfter = (await api.query.system.account(recipient.address)).data.free.toBigInt();
@@ -967,6 +1020,45 @@
});
}
+export async function
+scheduleTransferExpectSuccess(
+ collectionId: number,
+ tokenId: number,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ value: number | bigint = 1,
+ blockSchedule: number,
+ scheduledId: string,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
+
+ expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
+ });
+}
+
+export async function
+scheduleTransferFundsPeriodicExpectSuccess(
+ amount: bigint,
+ sender: IKeyringPair,
+ recipient: IKeyringPair,
+ blockSchedule: number,
+ scheduledId: string,
+ period: number,
+ repetitions: number,
+) {
+ await usingApi(async (api: ApiPromise) => {
+ const transferTx = api.tx.balances.transfer(recipient.address, amount);
+
+ const balanceBefore = await getFreeBalance(recipient);
+
+ await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
+
+ expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
+ });
+}
export async function
transferExpectSuccess(